diff --git a/.changeset/stable-notes.md b/.changeset/stable-notes.md new file mode 100644 index 00000000..acbf1ac5 --- /dev/null +++ b/.changeset/stable-notes.md @@ -0,0 +1,2 @@ +### Changes +- **Stable release notes** - Updating from one stable version to the next lists every change in between, instead of only the newest version's. diff --git a/.changeset/whats-new-long-jump.md b/.changeset/whats-new-long-jump.md new file mode 100644 index 00000000..a7087301 --- /dev/null +++ b/.changeset/whats-new-long-jump.md @@ -0,0 +1,2 @@ +### Changes +- **What's new after a long update** - Updating across more than 8 versions (stable to stable) lists every change since your old version, grouped as New, Fixed and Improved, instead of the newest 8 versions and a count of the rest. diff --git a/.github/release-highlights/3.7.5.md b/.github/release-highlights/3.7.5.md new file mode 100644 index 00000000..9c0822c7 --- /dev/null +++ b/.github/release-highlights/3.7.5.md @@ -0,0 +1,9 @@ +## Highlights + +- **Share a database as a web studio.** Anyone with the link opens it in the browser at stroke.click, end-to-end encrypted. Everyone sees each other's cursors on the grid, and the shared console is one SQL tab you all type into at once. +- **AI agents can show you data.** `npx strokedb mcp` gives Claude Code and other agents your tables, read-only, and a link that opens the one they mean. +- **New engines (beta):** Google Cloud Spanner, BigQuery, Snowflake, Neo4j, InfluxDB, YugabyteDB, AlloyDB, and any database with an ODBC driver. +- **Five languages:** Spanish, French, German, Portuguese and Japanese. +- **Proxy settings** for app, AI, database and tunnel traffic, and tunnels through Kubernetes port-forward and AWS SSM besides SSH. +- **Large tables feel local.** A big table is copied to disk in the background, deep jumps land in a fraction of the time, and wide JSON or HTML rows show what's on screen first. +- **Your own fonts** for the interface, editor, grid, AI chat and terminal, plus SQL snippets, a display timezone, and export/import of your whole setup. diff --git a/.github/workflows/aur.yml b/.github/workflows/aur.yml new file mode 100644 index 00000000..5acf71c1 --- /dev/null +++ b/.github/workflows/aur.yml @@ -0,0 +1,52 @@ +# Republish stroke-bin to the AUR for a release that is already out, after a +# fix to packaging/aur/stroke-bin/PKGBUILD.in. Bump `pkgrel` (2, 3, ...) so +# yay and paru see a new package. release.yml publishes pkgrel 1 itself. +# +# Run it from Actions → Republish to the AUR → Run workflow. + +name: Republish to the AUR + +on: + workflow_dispatch: + inputs: + tag: + description: Released tag, e.g. v3.0.0 + required: true + pkgrel: + description: Package release (2 or higher) + required: true + default: '2' + +permissions: + contents: read + +jobs: + aur: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - name: Fill in the PKGBUILD + env: + TAG: ${{ inputs.tag }} + PKGREL: ${{ inputs.pkgrel }} + run: | + set -euo pipefail + [[ "$PKGREL" =~ ^[0-9]+$ ]] || { echo "::error::pkgrel must be a number"; exit 1; } + VERSION="${TAG#v}" + curl -fsSL -o stroke.deb "https://github.com/stroke-app/stroke/releases/download/${TAG}/stroke_${VERSION}_amd64.deb" + SHA=$(sha256sum stroke.deb | cut -d' ' -f1) + mkdir -p aur + sed -e "s/@VERSION@/${VERSION}/" -e "s/@PKGREL@/${PKGREL}/" -e "s/@SHA256@/${SHA}/" packaging/aur/stroke-bin/PKGBUILD.in > aur/PKGBUILD + cat aur/PKGBUILD + + - name: Push to the AUR + uses: KSXGitHub/github-actions-deploy-aur@v4.1.1 + with: + pkgname: stroke-bin + pkgbuild: aur/PKGBUILD + commit_username: broisnees + commit_email: broisnees@users.noreply.github.com + ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }} + commit_message: "Fix the package for ${{ inputs.tag }} (pkgrel ${{ inputs.pkgrel }})" + ssh_keyscan_types: rsa,ecdsa,ed25519 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 6f597c9c..328f7313 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -313,21 +313,32 @@ jobs: run: | set -euo pipefail BASE="https://github.com/${GITHUB_REPOSITORY}/releases/download/nightly" + # The updater downloads a copy named for this build. Every nightly + # reuses the plain names, so an app reading the new latest.json + # could be served last night's file under the same URL (mid-upload, + # or from GitHub's download cache) and fail its signature check. A + # name no earlier build used can only be this build's file. + TAG=$(printf '%s' "$VERSION" | tr -c 'A-Za-z0-9.-' '-') + for f in stroke-nightly_aarch64.app.tar.gz stroke-nightly_x64.app.tar.gz stroke-nightly_amd64.AppImage \ + stroke-nightly_amd64.deb stroke-nightly_x86_64.pkg.tar.zst stroke-nightly_x64-setup.exe; do + cp "out/$f" "out/${f/stroke-nightly_/stroke-nightly_${TAG}_}" + done git fetch -q origin master || true STABLE=$(git show origin/master:src-tauri/tauri.conf.json 2>/dev/null | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{try{console.log(JSON.parse(s).version)}catch{console.log('')}})") - VERSION="$VERSION" BASE="$BASE" STABLE="$STABLE" node -e " + VERSION="$VERSION" BASE="$BASE" TAG="$TAG" STABLE="$STABLE" node -e " const fs = require('fs') - const { VERSION, BASE } = process.env + const { VERSION, TAG } = process.env + const BASE = process.env.BASE + '/stroke-nightly_' + TAG + '_' const sig = (f) => fs.readFileSync('out/' + f, 'utf8').trim() const platforms = { - 'darwin-aarch64': { url: BASE + '/stroke-nightly_aarch64.app.tar.gz', signature: sig('stroke-nightly_aarch64.app.tar.gz.sig') }, - 'darwin-x86_64': { url: BASE + '/stroke-nightly_x64.app.tar.gz', signature: sig('stroke-nightly_x64.app.tar.gz.sig') }, - 'linux-x86_64': { url: BASE + '/stroke-nightly_amd64.AppImage', signature: sig('stroke-nightly_amd64.AppImage.sig') }, + 'darwin-aarch64': { url: BASE + 'aarch64.app.tar.gz', signature: sig('stroke-nightly_aarch64.app.tar.gz.sig') }, + 'darwin-x86_64': { url: BASE + 'x64.app.tar.gz', signature: sig('stroke-nightly_x64.app.tar.gz.sig') }, + 'linux-x86_64': { url: BASE + 'amd64.AppImage', signature: sig('stroke-nightly_amd64.AppImage.sig') }, // Linux packages update from the app too, each from its own entry: // a .deb through pkexec dpkg, an Arch install through pkexec pacman. - 'linux-x86_64-deb': { url: BASE + '/stroke-nightly_amd64.deb', signature: sig('stroke-nightly_amd64.deb.sig') }, - 'linux-x86_64-pacman': { url: BASE + '/stroke-nightly_x86_64.pkg.tar.zst', signature: sig('stroke-nightly_x86_64.pkg.tar.zst.sig') }, - 'windows-x86_64': { url: BASE + '/stroke-nightly_x64-setup.exe', signature: sig('stroke-nightly_x64-setup.exe.sig') }, + 'linux-x86_64-deb': { url: BASE + 'amd64.deb', signature: sig('stroke-nightly_amd64.deb.sig') }, + 'linux-x86_64-pacman': { url: BASE + 'x86_64.pkg.tar.zst', signature: sig('stroke-nightly_x86_64.pkg.tar.zst.sig') }, + 'windows-x86_64': { url: BASE + 'x64-setup.exe', signature: sig('stroke-nightly_x64-setup.exe.sig') }, } // The changelog since the last stable release, in CHANGELOG.md's own // format: the update window parses it into New / Improved / Fixed. @@ -338,7 +349,9 @@ jobs: const start = cl.indexOf('## [') const end = stable ? cl.indexOf('## [' + stable + ']') : -1 const body = start === -1 ? '' : cl.slice(start, end > start ? end : undefined).trim() - if (body) notes = body.slice(0, 60000) + // Plain titles: apps before 3.6.5 print markdown bold as asterisks, + // and newer ones read `Title - text` without them (splitEntry). + if (body) notes = body.replace(/\*\*([^*\n]+)\*\*/g, '\$1').slice(0, 60000) } catch {} fs.writeFileSync('out/latest.json', JSON.stringify({ version: VERSION, notes, pub_date: new Date().toISOString(), platforms }, null, 2)) " @@ -382,13 +395,16 @@ jobs: # from ever becoming the repo's "latest" release. gh release delete nightly --repo "$GITHUB_REPOSITORY" --cleanup-tag --yes 2>/dev/null || true git push origin ":refs/tags/nightly" 2>/dev/null || true - gh release create nightly out/* \ + # The feed goes up last, so it never names a file that isn't there. + mapfile -t FILES < <(ls out/* | grep -v '/latest.json$') + gh release create nightly "${FILES[@]}" \ --repo "$GITHUB_REPOSITORY" \ --target "$SHA" \ --title "Stroke Nightly ${VERSION}" \ --notes-file notes.md \ --prerelease \ --latest=false + gh release upload nightly out/latest.json --repo "$GITHUB_REPOSITORY" echo "✅ Published Stroke Nightly ${VERSION}" # Arch: refresh stroke-nightly-bin on the AUR with this build. Skipped diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f100c640..099b05e4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,25 +54,13 @@ jobs: PRERELEASE="" [[ "$TAG" == *-* ]] && PRERELEASE="--prerelease" - # Extract changelog for this version from CHANGELOG.md. - # Grabs everything between the matching "## [X.Y.Z]" header and the next one. - # VERSION goes in the environment: it used to trail the script as - # `VERSION=...`, which node receives as an argument, so the script - # looked for "## [undefined]" and every release said "No changelog". + # Notes: every CHANGELOG.md section since the previous stable tag, + # merged by heading, under .github/release-highlights/.md + # when there is one (scripts/release-notes.mjs). Stable ships far + # less often than nightly, so this version's section alone left out + # most of what someone on the last stable gets. export VERSION="${TAG#v}" - CHANGELOG=$(node -e " - const fs = require('fs') - const lines = fs.readFileSync('CHANGELOG.md', 'utf8').split('\n') - const header = '## [' + process.env.VERSION + ']' - let inside = false - const out = [] - for (const l of lines) { - if (l.startsWith(header)) { inside = true; continue } - if (inside && /^## \[/.test(l)) break - if (inside) out.push(l) - } - process.stdout.write(out.join('\n').trim()) - ") + CHANGELOG=$(node scripts/release-notes.mjs "$VERSION") cat > /tmp/notes.md << EOF ${CHANGELOG:-No changelog available for this release.} @@ -390,19 +378,11 @@ jobs: const read = (f) => { try { return fs.readFileSync(f, 'utf8').trim() } catch { return '' } } - // Extract this version's changelog section from CHANGELOG.md + // Every changelog section since the previous stable tag, as plain + // text the update dialog reads (scripts/release-notes.mjs --plain). function extractChangelog(version) { try { - const lines = fs.readFileSync('CHANGELOG.md', 'utf8').split('\n') - const header = `## [${version}]` - let inside = false - const out = [] - for (const l of lines) { - if (l.startsWith(header)) { inside = true; continue } - if (inside && /^## \[/.test(l)) break - if (inside) out.push(l) - } - return out.join('\n').trim() + return require('child_process').execFileSync('node', ['scripts/release-notes.mjs', version, '--plain'], { encoding: 'utf8' }).trim() } catch { return '' } } @@ -418,6 +398,8 @@ jobs: add('linux-x86_64', 'sig-linux/updater.sig', `${BASE}/stroke_amd64.AppImage.tar.gz`) add('windows-x86_64', 'sig-windows/updater.sig', `${BASE}/stroke_x64-setup.nsis.zip`) + // Plain titles: apps before 3.6.5 print markdown bold as asterisks, and + // newer ones read `Title - text` without them (changelog.js splitEntry). const notes = extractChangelog(VERSION) || `See https://github.com/stroke-app/stroke/releases/tag/v${VERSION}` const out = { @@ -465,7 +447,7 @@ jobs: curl -fsSL -o stroke.deb "$URL" SHA=$(sha256sum stroke.deb | cut -d' ' -f1) mkdir -p aur - sed -e "s/@VERSION@/${VERSION}/" -e "s/@SHA256@/${SHA}/" packaging/aur/stroke-bin/PKGBUILD.in > aur/PKGBUILD + sed -e "s/@VERSION@/${VERSION}/" -e "s/@PKGREL@/1/" -e "s/@SHA256@/${SHA}/" packaging/aur/stroke-bin/PKGBUILD.in > aur/PKGBUILD cat aur/PKGBUILD echo "skip=false" >> "$GITHUB_OUTPUT" diff --git a/CHANGELOG.md b/CHANGELOG.md index a22b4288..2dc33510 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,483 @@ All notable changes to Stroke are listed here, newest first. --- +## [3.7.5] - 2026-11-23 + +### Bug Fixes +- **Laggy scrolling with a proportional grid font** - With Separate fonts set to a proportional face for the grid (Inter, SF Pro), scrolling sideways dropped to about 50 fps on tables of long text. It holds 60 fps again. + + +## [3.7.4] - 2026-11-22 + +### New Features +- **Shared console** - While sharing a database as a web studio, Open shared console (command palette) gives you one SQL tab that everyone on the link edits together, in the app and in the browser. You see each other's cursors and selections by name, and Run runs the query for whoever presses it. + +### Bug Fixes +- **Skeleton rows on wide tables over a slow link** - On a big table with wide rows (HTML, JSON), the rows you scroll or jump to now show in about a second instead of after several, and scrolling sideways no longer sits on skeletons. The rows on screen are fetched first, and the background copy of the table yields to them. + + +## [3.7.3] - 2026-11-22 + +### Bug Fixes +- **Reconnecting while offline** - With no network, the reconnect on launch no longer dials into nothing and then blames the host. It says you're offline and reconnects by itself when the network is back. A failed connect while offline says so, and repeated failures show one toast instead of a stack. + + +## [3.7.2] - 2026-11-22 + +### New Features +- **Let an AI agent show you the database** - `npx strokedb mcp` is an MCP server for Claude Code and other agents, even ones running on another machine: it reads the database (tables, columns, read-only queries) and its show_table tool gives you a link that opens a table in the web studio or in Stroke. Later calls switch your open studio to the next table. In the app, a `stroke://studio` link opens the shared studio in a window of its own. +- **Separate fonts** - Settings > Appearance > Separate fonts gives the interface, the SQL editor, the data grid, the AI chat and the terminal a font each, with a preview. The list has the bundled fonts and your OS's own, named for it (SF Pro, SF Mono and Menlo on a Mac; Segoe UI, Cascadia Mono and Consolas on Windows), and only the ones your machine has. +- **Font smoothing** - Pick thin grayscale text (Stroke's look) or your OS's default smoothing. + +### Bug Fixes +- **"Superseded by a newer load" after a reload** - When the window reloaded while the app kept running, every table it had open failed with "Superseded by a newer load of this table" until Stroke restarted. Tables load again, and a replaced load is never shown as an error. + + +## [3.7.1] - 2026-11-22 + +### New Features +- **Languages** - Spanish, French, German, Portuguese and Japanese now cover the command palette, menu bar, start screen, new-tab page, table toolbar, SQL console, sidebar, status bar and most of Settings. Pick one under Settings > Appearance > Language. +- **Live cursors on a shared studio** - When you share a database as a web studio (Labs), everyone on the link sees each other: a colored outline and name on the cell each person is on, their pointer, and what they are typing before they save. Saved changes on either side reload the table for everyone else. + + +## [3.7.0] - 2026-11-22 + +### New Features +- **Proxy settings** - Settings > Network sends app requests, AI requests, database connections and tunnels each through its own proxy (HTTP or SOCKS5, with an optional login), or directly. Each has a Test button. + +### Bug Fixes +- **Two tabs of the same table** - In All rows mode, scrolling or closing one no longer blanks the other's rows into skeletons that reload slowly. + + +## [3.6.9] - 2026-11-22 + +### New Features +- **Kubernetes and AWS SSM tunnels** - A connection can go through kubectl port-forward (to a service, pod or deployment) or AWS Session Manager port forwarding, as well as SSH. Pick it under Tunnel in the connection form. + +### Bug Fixes +- **AI chat** - Run on a SQL block in a reply shows the result. It ran, but the result was hidden whenever query cards were turned off. +- **Stopping a large query** - Stop ends the query at once instead of after the row being read (one large JSON value could take seconds), and the next query no longer waits while the stopped one's remaining rows are drained. + +### Changes +- **Select All** - No longer logs a debug line on every press. + + +## [3.6.8] - 2026-11-22 + +### New Features +- **SQL snippets** - Settings > Snippets keeps SQL you reuse, each with a trigger word, fields Tab moves through, and the engines it applies to. The SQL editor offers them as you type, and they import and export as JSON. +- **SQLite and DuckDB files** - "New SQLite database" and "Open a database file" on the start screen and in the command palette create or open a file in one step and connect to it. +- **Display timezone** - Settings > Database shows timestamptz values in UTC, this computer's zone, or any zone you pick, with the offset written out. It applies in the grid and in copied rows; stored values do not change. +- **Export and import** - Save connections, saved queries, settings and SQL snippets to one file and import it on another computer, without an account. Passwords and API keys go in only if you choose, encrypted with a passphrase. Settings > Account & Sync, or the command palette. + +### Bug Fixes +- **JSON viewer** - JSON pasted as one line is laid out at once. In every code editor, text scrolled sideways no longer shows through the line numbers. + + +## [3.6.7] - 2026-11-22 + +### Bug Fixes +- **Changing the page size during a slow load** - Rows per page and the pager stay usable while rows load, and a change stops the load it replaces on the server instead of waiting behind it. "1-1 of" no longer shows before any row has arrived. +- **What's new and the update window** - Changes are grouped under New, Improved and Fixed, each as a title over what changed, and What's new opens on this version's changes. Updating from an older version no longer shows asterisks in the notes. + +### Changes + +#### Performance +- **Tables with large JSON or text** - Values past 8 KB arrive as their first 512 characters and their size, and load in full when the cell is opened or edited. A page of rows holding ~600 KB documents is a third of the size it was, and the grid shows each value's start instead of "[jsonb · 15 KB, truncated]". + + +## [3.6.6] - 2026-11-22 + +### Bug Fixes +- **Elasticsearch and OpenSearch** - "No indices yet? Create one" shows only on a cluster with no indices. +- **New connection** - A pasted http(s) address that doesn't name its engine asks whether it is Elasticsearch, OpenSearch, CouchDB, ClickHouse or libSQL, instead of saying it isn't a connection string. +- **SQL Server values** - decimal, numeric, uniqueidentifier and datetimeoffset columns showed NULL; they show their values, decimals at their exact scale. A datetime shows .997 instead of .996666666. +- **SQL Server types** - Column headers say int, bit and nvarchar instead of int4, intn and bitn. +- **Oracle on Ubuntu 24.04 and later** - When Instant Client won't load because libaio.so.1 is missing, the error says so and gives the link command for this machine, instead of only suggesting the library path. +- **New-tab page** - The Terminal tile names the client it opens for this database (sqlcmd, sqlplus, turso, redis-cli), or the built-in SQL prompt, instead of "psql, mysql or sqlite3" everywhere. + + +## [3.6.5] - 2026-11-22 + +### Bug Fixes +- **Booleans in the record view and row panel** - On SQLite, libSQL and D1 they show true/false like the grid, and the true/false picker starts on the stored value instead of a blank. +- **Escape** - Closes every dialog, including What's new, which ignored it. It also leaves full screen in the ERD and diagram code views and stops a dashboard presentation, which it never reached before. +- **MongoDB filters** - A filter that doesn't parse says what is wrong, such as "it is missing a closing }", instead of a parser diagram that pointed at the wrong place. +- **Redis sidebar** - Says "1 client", not "1 clients". +- **What's new and the update window** - Show each change's title in bold instead of printing its asterisks. +- **Status bar, several databases open** - The other open databases show their engine icon, so a name like "127.0.0.1:18080" no longer reads as this connection's host. + + +## [3.6.4] - 2026-11-22 + +### Bug Fixes +- **Booleans on SQLite, libSQL and D1** - A boolean column shows true/false instead of 1/0, and its toggle starts from the stored value instead of NULL. It still writes 1/0. +- **ClickHouse decimals** - Keep their scale and every digit: a Decimal(10,2) of 12.50 showed 12.5, and a Decimal(38) past a double's precision came back rounded. +- **Opening a connection** - Lands on the database the connection names instead of the first schema alphabetically (INFORMATION_SCHEMA on ClickHouse). +- **Command palette** - Finds the activity log by "logs". +- **MongoDB and Redis** - An empty collection list says "No collections" instead of "No tables · Nothing in this schema yet", the document browser's view picker no longer cuts "Documents" short, and a new Redis connection is named "Redis@host" instead of "0@host". +- **Connecting a saved database again** - "Open it" in the already-saved prompt connects to the saved one when you were connecting. +- **Notebook variables** - A value with an apostrophe (O'Neil) inside `'{{name}}'` no longer breaks the cell or lets the value write SQL: its quotes are doubled inside a string literal. + + +## [3.6.3] - 2026-11-22 + +### Bug Fixes +- **Dropped tables** - Opening or refreshing a table that was dropped or renamed since it was listed says the table no longer exists, instead of "Unknown column: id". + +### Changes + +#### Performance +- **Connect** - The first screen after connecting paints about 25% sooner: the new-tab page no longer renders while last session's tabs are coming back (no flash), and the sidebar's connections list and chats render a frame after the rest. + +#### Code +- **New-tab page** - Shows Cmd/Ctrl+I for AI, its shortcut since 3.6.1. + + +## [3.6.2] - 2026-11-22 + +### Changes + +#### Performance +- **Launch** - The first screen paints about 13% sooner: the AI client and its prompts no longer load with the app. +- **After connecting** - A hidden terminal no longer re-measures itself on every theme or zoom change (it was the largest main-thread cost after a connect), and the sidebar, tab strip and toolbar no longer force the page to lay out in the middle of rendering. The connections list and the tab strip use one right-click menu each instead of one per row. +- **Jumping deep into a large table** - A jump to rows nothing has loaded near shows them in about a third of the time over a remote link: the rows on screen are fetched first, and a deep page ordered by the primary key skips ahead on the key's index instead of reading every row before it. +- **Local copy of large tables** - Fills about four times faster locally and twice as fast over a far link, and waits until the grid is quiet so it never slows the rows on screen. + + +## [3.6.1] - 2026-11-22 + +### Bug Fixes +- **AI chat** - A reply that mentions "a ```sql block" in a sentence no longer turns the rest of the reply into a code block captioned with that sentence. +- **Postgres backup and restore** - Backups record the extensions their tables use (uuid-ossp, citext, PostGIS and others), and leave out what those extensions own. Restoring an older backup into a fresh database adds the extensions its tables need first, instead of failing on `uuid_generate_v4()` and rolling back. +- **Infinite scroll counter** - It counts the rows that have loaded instead of staying at "50 of 100,000". +- **Connection latency** - The first reading waits until the connect settles: a local database no longer flashes a red "958 ms", and one database's reading no longer carries over to the next. +- **Query history** - Errors read as the database wrote them, without "error returned from database:". Runs under a millisecond show "<1ms". +- **Settings search** - Every word matches in any order, so "page size" and "dark mode" find their settings. +- **Find in database** - Counts views as views, and its warning no longer starts with a stray dot or outlives the query. + +#### Large values +- **Cell panel** - A JSON value of a megabyte or more (a jsonb holding a file) no longer goes blank when scrolled sideways. JSON is laid out with short lines at any size: one key per line, runs of numbers or strings packed into lines. +- **Record view** - A value the grid fetched as a size has a Load button, and shows what it loads. +- **Record view and row inspector** - Large values are shown cut and are edited in the cell panel (Space) instead of a field that could not draw them. +- **Text view** - Very long cells are cut in the preview only. Copy and Download keep them whole. +- **Console** - A new result starts at the top instead of where the last one was scrolled. + +### Changes +- **Shortcuts** - The AI panel opens with Cmd/Ctrl+I. The inline AI sidebar moves to Cmd/Ctrl+Shift+E. + +#### Performance +- **Deep scrolling in large tables** - A large table opened with All rows is copied in the background to a local file, in the grid's own order, and windows already copied are read from it instead of asking the database for a deep OFFSET. A jump to row 900,000 no longer waits on the server reading every row before it. +- **Connect** - Background warm-ups (editor chunks, the terminal dock, the CLI lookup) wait until the first screen after a connect has painted, and idle work waits for the main thread to be idle rather than just for no input. +- **Loading pill** - Says "deep in the table, fetching" when the link is fast and the query is what is slow, instead of "slow connection". + + +## [3.6.0] - 2026-11-22 + +### Changes +- Materialized views in the sidebar, palette and diagram; data grid kept mounted between tabs (#363) + + +## [3.5.9] - 2026-11-22 + +### Changes +- View DDL as CREATE VIEW, dark dashboard window, schema picker and diagram details (#362) + + +## [3.5.8] - 2026-11-22 + +### Changes +- Objects page follows the connection; correct run hint; SQL Server Unicode checked live (#361) + + +## [3.5.7] - 2026-11-22 + +### Changes +- Stop kept-alive pages showing the previous database after a switch (#360) + + +## [3.5.6] - 2026-11-22 + +### Changes +- MySQL backups restore with the mysql client; New table on more engines (#359) + + +## [3.5.5] - 2026-11-22 + +### Changes +- Don't overwrite editor tabs, 5x faster result map, terminal input fix (#358) + + +## [3.5.4] - 2026-11-22 + +### Changes +- New table in each engine's own DDL; show what a run did (#357) + + +## [3.5.3] - 2026-11-21 + +### Changes +- Quote ORM runner SQL, keep sidebar counts current, Codegen targets, screenful paging (#356) + + +## [3.5.2] - 2026-11-21 + +### Changes +- Step over completed function parens, empty-result columns for MCP, insights inserts (#355) + + +## [3.5.1] - 2026-11-21 + +### Changes +- Fix the Redis crash after adding a key; correct backslash and Unicode string literals (#354) + + +## [3.5.0] - 2026-11-21 + +### Changes +- Column headers for empty results, readable diagrams without relations, and more (#353) + + +## [3.4.9] - 2026-11-21 + +### Changes +- Fix the crash when choosing a file to import; import from the palette (#352) + + +## [3.4.8] - 2026-11-21 + +### Changes +- Data diff across engines, steady connection list, narrow-pane map and plans, palette export (#351) + + +## [3.4.7] - 2026-11-21 + +### Changes +- Spanner PostgreSQL dialect SQL, hidden-tab menu, narrow results toolbar, and more (#350) + + +## [3.4.6] - 2026-11-21 + +### Changes +- Show DuckDB column types; collapse repeated toasts (#349) + + +## [3.4.5] - 2026-11-21 + +### Changes +- Hide SQLite's own tables, name file databases by file, clearer write messages (#348) + + +## [3.4.4] - 2026-11-21 + +### Changes +- Connect to local libsql:// servers, show libSQL types, Copy as INSERT per engine (#347) + + +## [3.4.3] - 2026-11-21 + +### Changes +- Generate SQL that runs on its own engine: export, Open in SQL editor, upsert (#346) + + +## [3.4.2] - 2026-11-21 + +### Changes +- Write review SQL per dialect, MySQL enum picker, MariaDB insights (#345) + + +## [3.4.1] - 2026-11-21 + +### Changes +- Fix clipped dialogs, the terminal on engines without a CLI, and more (#344) + + +## [3.4.0] - 2026-11-21 + +### Changes +- Send verify-full TLS on connect, keep pasted URL parameters, and more (#343) + + +## [3.3.9] - 2026-11-21 + +### Changes +- Fix platform shortcut hints, menu row sizes, toolbar overflow and more (#342) + + +## [3.3.8] - 2026-11-21 + +### Changes +- Fix Ctrl+Delete, multi-word palette search, and more from another sweep (#341) + + +## [3.3.7] - 2026-11-21 + +### Changes +- Reopen a database's tabs, and fix connection identity and Advisor noise (#340) + + +## [3.3.6] - 2026-11-21 + +### Changes +- Fix console scrolling, stuck icons, and more from a second sweep (#339) + + +## [3.3.5] - 2026-11-21 + +### Changes +- Fix issues found in an app-wide sweep (#338) + + +## [3.3.4] - 2026-11-21 + +### Changes +- Show saves and deletes right away, with a rollback on failure (#337) + + +## [3.3.3] - 2026-11-21 + +### Changes +- Stop the grid bouncing; open objects in one click; no flash after Redis apply (#336) + + +## [3.3.2] - 2026-11-21 + +### Changes +- Make the agent tools work on every engine; Spanner interleave relations; Turso .dump (#335) + + +## [3.3.1] - 2026-11-21 + +### Changes +- Fix Shift+scroll sticking to one axis; zoom-proof layouts; provider re-auth (#334) + + +## [3.3.0] - 2026-11-21 + +### Changes +- Rank the palette by label, and bring readable text to contrast (#333) + + +## [3.2.9] - 2026-11-21 + +### Changes +- Fix blank screens after the AI tab setting; redesign the model picker (#332) + + +## [3.2.8] - 2026-11-21 + +### Changes +- Make the Map page smooth on large layers (#331) + + +## [3.2.7] - 2026-11-21 + +### Changes +- Map spatial query results beside the grid (#330) + + +## [3.2.6] - 2026-11-21 + +### Changes +- Add InfluxDB (beta, read-only) (#329) + + +## [3.2.5] - 2026-11-21 + +### Changes +- Add Neo4j (beta) (#328) + + +## [3.2.4] - 2026-11-21 + +### Changes +- YugabyteDB and AlloyDB (beta) (#327) + + +## [3.2.3] - 2026-11-21 + +### Changes +- Backup, import, transactions and SSH for Spanner, BigQuery, Snowflake and ODBC (#326) + + +## [3.2.2] - 2026-11-21 + +### Changes +- Share any SQL database as a web studio (#325) + + +## [3.2.1] - 2026-11-21 + +### Changes +- Sharp text on external displays, and palette subtitles for hostless engines (#324) + + +## [3.2.0] - 2026-11-21 + +### Changes +- Grid: scroll both axes at once, and a switch for the referenced-by columns (#323) + + +## [3.1.9] - 2026-11-21 + +### Changes +- Snowflake support (beta) (#322) + + +## [3.1.8] - 2026-11-21 + +### Changes +- Drag the window from anywhere on the title bar (#321) + + +## [3.1.7] - 2026-11-21 + +### Changes +- ODBC driver refresh, and nightly updates that pass their signature check (#320) + + +## [3.1.6] - 2026-11-21 + +### Changes +- ODBC bridge with engine presets (beta) (#319) + + +## [3.1.5] - 2026-11-21 + +### Changes +- Google BigQuery support (beta) (#318) + + +## [3.1.4] - 2026-11-21 + +### Changes +- Google Cloud Spanner support (beta) (#317) + + +## [3.1.3] - 2026-11-21 + +### Changes +- Queries tab, steady zoom pill, one switch geometry, access changes reach agents (#315) + + +## [3.1.2] - 2026-11-21 + +### Changes +- Share JSON as a link; one focus edge on search fields (#313) + + +## [3.1.1] - 2026-11-20 + +### Changes +- Real-server tests, streaming and server-side Stop for more engines, plans for document engines (#312) + + +## [3.1.0] - 2026-11-20 + +### Changes +- Handle big plans, clean cancel, 2 GB results, open transactions and lost tunnels on every engine (#311) + + ## [3.0.0] - 2026-11-19 ### New Features diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md index d29d73b9..ebca22c1 100644 --- a/DESIGN_SYSTEM.md +++ b/DESIGN_SYSTEM.md @@ -310,8 +310,9 @@ overrides — if a menu looks off, the primitive is wrong; fix it there. | Part | Recipe | |---|---| | Panel | `rounded-[10px] border border-border/60 bg-popover p-1 elevate-2-rim` | -| Item | `gap-1.5 rounded-sm px-1.5 py-1 text-ui-2xs` (a 25px row) · focus/highlight `bg-accent text-foreground` · disabled `opacity-40` · icons `size-3.5 shrink-0` · **no `transition-colors`** — a colour fade on hover makes highlight tracking feel laggy in a long menu | -| Checkbox/radio/select item | same, with `pl-1.5 pr-7` and the indicator at `right-1.5` | +| Item (dropdown, select) | `min-h-7 gap-2 rounded-sm px-2 py-1 text-ui-xs`: the compact control height, so a menu row matches the button that opened it · focus/highlight `bg-accent text-foreground` · disabled `opacity-40` · icons `size-3.5 shrink-0` · **no `transition-colors`** (a colour fade on hover makes highlight tracking feel laggy in a long menu) | +| Checkbox/radio item, submenu trigger | same, with `pl-2 pr-7` and the indicator at `right-1.5`: one menu often mixes all of them, so they must line up | +| Context menu item | `gap-1.5 rounded-sm px-1.5 py-1 text-ui-2xs` (a 25px row) for the long, dense grid menus | | Group label | `px-1.5 py-1 text-ui-3xs font-medium text-muted-foreground` — **plain case**, never uppercase (uppercase micro-labels are for page/sidebar sections only, §10) | | Separator | `bg-border/60 -mx-1 my-1 h-px` | | Shortcut / trailing hint | `ml-auto shrink-0 pl-3 text-ui-3xs tracking-widest text-muted-foreground` | @@ -347,12 +348,20 @@ secondary line, if any, is `text-ui-2xs text-muted-foreground` in plain words (`Postgres · annapurna`), never a boxed chip; trailing count/timestamp `font-mono text-ui-2xs tabular-nums text-muted-foreground`. -**Sidebar search row** (top of a sidebar): frameless - no field border - with -a `Search size-3.5` icon at `left-2`, placeholder "Search", `text-ui-sm`, a -`bg-sidebar-accent/60` fill only while focused, and a `size-5` clear (×) -button at the right while it has text. Quiet `size-7` icon actions sit on the -same row or the row above. In code: `no-field-frame` on a bare input, or -`border-transparent! bg-transparent!` on the `Input` wrapper. +**Search fields** (sidebar, dialogs, pages, pickers): one component, +`SearchField.svelte`. An outlined box: `h-8 rounded-lg`, a 1px +`border-border/80` outline over a faint `bg-muted/30` fill, no shadow, a +`Search size-3.5` icon at `left-2.5`, and the `/` keycap at the right that +focuses it (a `size-5` clear (×) button replaces the keycap while it has text). +Focus moves the outline to `border-ring/70`. Do not hand-roll a search input; +pass `rank={null}` for a field `/` should not focus. +Where a field keeps its own keyboard handling or toolbar cluster, put +`search-box no-field-frame` on the input (icon positioned over it), or +`search-shell` on a wrapper row that holds icon, input and buttons. Both draw +the same outline. A filter row at the top of a menu or popover list +(`data-slot="menu-search"`) is a `search-shell` inset with `m-1.5` (`h-8`), +so it reads as the same field inside the menu. The command palette's title +row is the one exception: the palette itself is the field. **Prominent pick lists** (provider DB lists, account lists): ``` diff --git a/README.md b/README.md index eac64e0b..04f02b27 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,60 @@
+ + + + Stroke + + + # Stroke -**A fast desktop database client, for people and for their AI tools.** +**A fast, native database client for every database you run.** + +Postgres, MySQL, SQLite, MongoDB, Redis and 18 more engines in one app for macOS, Windows and Linux, plus anything with an ODBC driver.
+Built in Rust, with no Electron and no JVM: it starts in about a second, stays light on memory, and keeps scrolling smoothly through millions of rows. + +[![Release](https://img.shields.io/github/v/release/stroke-app/stroke?label=release&color=ffc107&labelColor=1d1d1f)](https://github.com/stroke-app/stroke/releases/latest) +[![Downloads](https://img.shields.io/github/downloads/stroke-app/stroke/total?color=ffc107&labelColor=1d1d1f)](https://github.com/stroke-app/stroke/releases) +[![Platforms](https://img.shields.io/badge/macOS%20·%20Windows%20·%20Linux-1d1d1f?labelColor=1d1d1f)](#install) +[![License](https://img.shields.io/badge/license-Stroke%20License-1d1d1f?labelColor=1d1d1f)](LICENSE) + +[**Download**](https://stroke.click/download) · [Website](https://stroke.click) · [Features](https://stroke.click/features) · [Changelog](https://stroke.click/changelog) · [Docs](https://stroke.click/docs) + +
-[Download](#install) · [What's inside](#whats-inside) · [Build from source](#build-from-source) · [stroke.click](https://stroke.click) +Stroke with a MongoDB collection open in the data grid, and Postgres, Turso and other connections in the sidebar
-Stroke is a Rust + Svelte app for browsing, editing and querying databases. It stays quick on tables with millions of rows, works from the keyboard, and ships an MCP server so Claude, Cursor and other agents can query the same databases you do. +
+ +## Why Stroke + +Any client can draw a grid. Stroke is built for the moments where most of them fall over. + +- **Huge results don't freeze it.** Rows stream to disk as they arrive, so a 2 GB result fills the grid at once and memory stays flat. +- **Stop means stopped.** Cancelling a query cancels it on the server, on every engine that can, and the connection is ready for the next one. +- **Nothing changes by accident.** Edits are staged in the grid until you press Apply, transactions show how long they've held their locks, and read-only connections refuse every write. +- **Plans you can read.** `EXPLAIN` becomes a tree of steps with their time, the slow one marked, for SQL and document engines alike. +- **Lost tunnels come back.** If SSH drops, Stroke reconnects it on the same port and tells you it happened. +- **Your credentials stay yours.** Stroke connects straight from your machine, and passwords live in your OS keychain. ## Databases -**Engines:** PostgreSQL, MySQL, MariaDB, CockroachDB, SQLite, Turso / libSQL, Cloudflare D1, ClickHouse, DuckDB, SQL Server, Oracle (with Oracle Instant Client installed) and Redis. +| Kind | Engines | +|---|---| +| **Relational** | PostgreSQL · MySQL · MariaDB · SQLite · SQL Server · Oracle · CockroachDB · Turso / libSQL · Cloudflare D1 · Google Spanner (beta) · YugabyteDB (beta) · AlloyDB (beta) | +| **Document** | MongoDB · CouchDB · Firestore · Cassandra · ScyllaDB | +| **Key-value** | Redis · Valkey · DynamoDB | +| **Analytics** | DuckDB · ClickHouse · PostHog · Google BigQuery (beta) · Snowflake (beta) | +| **Search** | Elasticsearch · OpenSearch | +| **Graph** | Neo4j (beta) | +| **Time series** | InfluxDB 1.x, 2.x and 3.x (beta, read-only) | + +Oracle needs [Oracle Instant Client](https://www.oracle.com/database/technologies/instant-client.html) installed. + +**Through ODBC (beta)**, with the database's own ODBC driver installed: IBM Db2, SAP HANA, SAP ASE (Sybase), Informix, Teradata, Vertica, Exasol, Firebird, Amazon Redshift, Databricks, Apache Hive, Trino and Presto, Dremio, InterSystems IRIS, Microsoft Access, and any other database by DSN or connection string. The driver manager is built in. See [ODBC databases](https://stroke.click/docs/odbc). **Sign in and pick a database**, no connection string needed: @@ -22,49 +64,94 @@ Stroke is a Rust + Svelte app for browsing, editing and querying databases. It s | PlanetScale, TiDB Cloud | MySQL | | Turso | libSQL | | Cloudflare D1 | SQLite | -| Upstash | Redis | | Railway | Postgres, MySQL, Redis | -| PostHog | HogQL, read-only | +| Upstash, Xata, SingleStore, PostHog | with an API token | -Stroke also finds databases already running on your machine (Docker containers, local Postgres and MySQL, the SQLite file your ORM points at), so a local connection is usually one click, and a right-click restarts or stops a container. Anything can go through an SSH tunnel. +Stroke also finds databases already running on your machine (Docker containers, local Postgres and MySQL, the SQLite file your ORM points at), so a local connection is usually one click. Any connection can go through an SSH tunnel. ## What's inside -- **Data grid** that paints millions of rows, with filters, multi-column sort, pinned columns, foreign-key jumps and inline editing, including Postgres arrays and JSON -- **SQL console** with schema-aware autocomplete, EXPLAIN plans, history, saved queries and `.sqlnb` notebooks -- **Viewers** for JSON, pgvector embeddings and PostGIS geometry, plus a map view of every spatial layer -- **Schema tools:** ER diagrams, a relation tree, schema timeline, data diff, and Prisma or Drizzle codegen -- **Charts and dashboards** from any query result -- **Backup and restore** as SQL dumps for Postgres, MySQL, SQLite and D1 -- **Read-only mode** for browsing production without the risk -- **AI chat** that runs queries and draws charts, with a free tier, your own key, local models (Ollama, LM Studio) or GitHub Copilot. Destructive statements always ask first -- **MCP server:** start it in Settings, copy the config for your client, done -- **Command palette** on `Cmd/Ctrl+K`, split panes, themes and extensions +**Browse and edit** +- A data grid that paints millions of rows, with filters that write the `WHERE`, multi-column sort, pinned columns and foreign-key jumps +- Inline editing, including Postgres arrays and JSON, staged until you apply it +- Seven views of the same rows: table, JSON, record, text, chart, schema diagram and structure + +**Query** +- A SQL editor with schema-aware autocomplete, a result tab per statement, history, saved queries and `.sqlnb` notebooks +- Explicit transactions on Postgres, MySQL, SQLite, DuckDB, SQL Server and Oracle +- Query plans as readable steps, with the slowest one marked + +**Beyond SQL** +- MongoDB aggregations built stage by stage, Redis keys with a live server overview, DynamoDB with your AWS profile +- Viewers for JSON, pgvector embeddings and PostGIS geometry, plus a map of every spatial layer -Keys and provider tokens live in the OS keychain. +**Schema and data** +- ER diagrams, a relation tree, a schema timeline and data diff +- Prisma and Drizzle codegen +- Backup and restore as SQL dumps, across providers (D1 to Postgres included) + +**Share** +- Rows, charts, JSON, queries or a schema as an end-to-end encrypted link that expires when you say. Mask the sensitive columns first + +**AI and agents** +- An AI chat that runs queries and draws charts: the free tier, your own key, local models (Ollama, LM Studio) or GitHub Copilot +- A built-in **MCP server**, so Claude Code, Codex, Cursor and other agents query the same databases, held to the access level you set per connection. Destructive statements always ask first + +**Everywhere** +- A command palette on `Cmd/Ctrl+K`, split panes, themes and extensions +- Encrypted sync of connections and settings between your computers ## Install -**macOS** ([Homebrew](https://brew.sh)) +**macOS** with [Homebrew](https://brew.sh) ```bash brew install --cask stroke-app/tap/stroke ``` -**Windows** ([Scoop](https://scoop.sh)) +**Windows** with [Scoop](https://scoop.sh) ```powershell scoop bucket add stroke https://github.com/stroke-app/stroke scoop install stroke ``` -Or grab an installer from [Releases](https://github.com/stroke-app/stroke/releases): `.dmg` for macOS (Apple Silicon or Intel), `-setup.exe` for Windows, `.deb` (Ubuntu 22.04+, Debian 12+), `.rpm` (Fedora 41+, RHEL 10) or `.AppImage` (Arch and any distro with glibc 2.35+) for Linux. +**Any system** from a terminal + +```bash +curl -fsSL https://stroke.click/install.sh | sh # macOS and Linux +irm https://stroke.click/install.ps1 | iex # Windows (PowerShell) +``` + +Or download an installer from [Releases](https://github.com/stroke-app/stroke/releases): + +| System | Package | +|---|---| +| macOS | `.dmg` for Apple Silicon or Intel | +| Windows | `-setup.exe` | +| Ubuntu 22.04+, Debian 12+ | `.deb` | +| Fedora 41+, RHEL 10 | `.rpm` | +| Arch and any distro with glibc 2.35+ | `.AppImage` | + +Every feature is free for 30 days. After that, [Stroke Pro](https://stroke.click/pricing) is $9.99 once, with every update included. + +
+Stroke Nightly: try what's coming +
+ +Built every night from the `nightly` branch, it installs as a separate app beside Stroke with its own settings, so you can try new work without risking your setup. It updates itself whenever something lands. [Download the nightly](https://github.com/stroke-app/stroke/releases/tag/nightly). + +
-On Wayland, Stroke runs natively. If a launch can't draw there (some GPU and driver setups), the next one falls back to X11 by itself. `STROKE_X11=1` forces X11; `STROKE_WAYLAND=1` forces Wayland and forgets the fallback. +
+First launch warnings and Linux display notes +
-**Stroke Nightly** is built every night from the `nightly` branch and installs as a separate app beside Stroke, with its own settings, so you can try what's coming without risking your setup: [download the nightly](https://github.com/stroke-app/stroke/releases/tag/nightly). It updates itself every night something lands. +- If macOS blocks the first launch, run `xattr -cr /Applications/Stroke.app`. +- If Windows SmartScreen warns, choose **More info → Run anyway**. [Sponsoring](https://stroke.click/sponsors) pays for the certificates that remove both warnings. +- On Wayland, Stroke runs natively. If a launch can't draw there (some GPU and driver setups), the next one falls back to X11 by itself. `STROKE_X11=1` forces X11; `STROKE_WAYLAND=1` forces Wayland and forgets the fallback. -If macOS blocks the first launch, run `xattr -cr /Applications/Stroke.app`. If Windows SmartScreen warns, choose **More info → Run anyway**. +
## Shortcuts @@ -80,22 +167,26 @@ If macOS blocks the first launch, run `xattr -cr /Applications/Stroke.app`. If W ## Build from source -Needs [Node.js](https://nodejs.org) 20.19+ (CI uses 22) and the [Rust toolchain](https://rustup.rs). +Stroke is a [Tauri](https://tauri.app) app: a Rust core for every database driver, query and stream, and a Svelte interface drawn by the system's own webview. + +You need [Node.js](https://nodejs.org) 20.19+ (CI uses 22) and the [Rust toolchain](https://rustup.rs). ```bash git clone https://github.com/stroke-app/stroke cd stroke npm install -npm run tauri # dev -npm run tauri:build # release build +npm run tauri # run in development +npm run tauri:build # build a release ``` On Arch, `npm run tauri:build:arch` avoids an AppImage linker issue. `npm run tauri:build:mac` and `npm run tauri:build:win` build release installers locally; `scripts/build-local.mjs` lists what each one needs. -## License +## Contributing -Stroke is source-available under the [Stroke License](LICENSE). You can do anything you like with the source code, including reusing it in your own free or paid projects. If you publish a work derived from it, say that it comes from Stroke. If you publish a compiled app built from it, it must not contain malware, must not be called Stroke or look like it, and must keep Stroke's trial and license-key payments intact and free to users, unless it is a substantial improvement in its own right. Stroke is not open source by the OSI definition. A [Stroke Pro](https://stroke.click/pricing) license buys a key for the app and funds development. +Fixes, features and docs are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers the dev setup, including one-command Docker test databases, and the PR checklist. Bugs and ideas go in [issues](https://github.com/stroke-app/stroke/issues), and the [roadmap](https://stroke.click/roadmap) shows what's next. -## Contributing +Stroke is built by one developer. [Sponsors](https://stroke.click/sponsors) keep it signed on macOS and Windows. + +## License -Fixes, features and docs are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers the dev setup, including one-command Docker test databases, and the PR checklist. Bugs and ideas go in [issues](https://github.com/stroke-app/stroke/issues). +Stroke is source-available under the [Stroke License](LICENSE). You can do anything you like with the source code, including reusing it in your own free or paid projects. If you publish a work derived from it, say that it comes from Stroke. If you publish a compiled app built from it, it must not contain malware, must not be called Stroke or look like it, and must keep Stroke's trial and license-key payments intact and free to users, unless it is a substantial improvement in its own right. Stroke is not open source by the OSI definition. A [Stroke Pro](https://stroke.click/pricing) license buys a key for the app and funds development. diff --git a/bucket/stroke.json b/bucket/stroke.json index 93836bab..1534b418 100644 --- a/bucket/stroke.json +++ b/bucket/stroke.json @@ -1,5 +1,5 @@ { - "version": "2.3.0", + "version": "3.0.0", "description": "Fast desktop database client for PostgreSQL, MySQL, SQLite, and Cloudflare D1", "homepage": "https://github.com/stroke-app/stroke", "license": { @@ -8,8 +8,8 @@ }, "architecture": { "64bit": { - "url": "https://github.com/stroke-app/stroke/releases/download/v2.3.0/stroke_2.3.0_x64-setup.exe#/dl.7z", - "hash": "1cc5d0f99a77d1f0945a051622d3941f39ac4147424e9273dadf5a2ce47ebea9" + "url": "https://github.com/stroke-app/stroke/releases/download/v3.0.0/stroke_3.0.0_x64-setup.exe#/dl.7z", + "hash": "e7dcb13618e4ce43a26b25e041451ba017a5febe1c255d23df5aa196636db963" } }, "bin": "Stroke.exe", diff --git a/cli/README.md b/cli/README.md index 08ab24eb..74f35b43 100644 --- a/cli/README.md +++ b/cli/README.md @@ -28,7 +28,9 @@ npx strokedb | `--port ` | Port for the local bridge (default: any free port) | | `--no-open` | Print the studio link instead of opening a browser | | `--share` | (Labs) Also print a link that opens this studio on any device. Read-only. Needs Node 22+ | -| `--write` | With `--share`: let the link edit rows and run any SQL | +| `--write` | With `--share` or `mcp`: allow edits and any SQL (read-only otherwise) | +| `--table ` | Open on this table: `schema.table`, or just its name | +| `--json` | Print the links as one JSON line (`studio`, `share`, `app`); everything else goes to stderr | ## How the web studio is kept private @@ -55,3 +57,32 @@ SQLite in the web studio needs Node 22.5 or newer. - Stop it with Ctrl+C; the link stops working until you share again (a new run makes a new link). The desktop app can share an open connection the same way: turn on Settings → Labs → Share as a web studio, then pick **Share as web studio** in the command palette. + +Everyone on a shared link sees everyone else: the cell each person is on, their pointer, and what they type before saving. A saved change reloads the table for the rest. + +## AI agents + +An AI coding agent can show you the database, even when it runs on another machine (a cloud box, a dev container). Add the MCP server to it once, in the project folder: + +```sh +claude mcp add strokedb -- npx -y strokedb mcp +``` + +It finds the database the same way as above (or pass one: `npx -y strokedb mcp postgres://...`) and offers four tools: + +| Tool | | +| --- | --- | +| `list_tables` | Tables and views, with row counts | +| `describe_table` | A table's columns, types and keys | +| `query` | One read-only statement, up to 100 rows back as JSON | +| `show_table` | Opens a table for you: a web studio link and a `stroke://` link for the app, both starting on that table | + +After the first `show_table`, the agent's next ones switch your open studio to the table it names, with a note saying who opened it. The agent shows up in the studio as a participant. + +It's read-only unless the server runs with `--write`. The links are shares like the ones above: end-to-end encrypted, and alive while the MCP server runs. + +Without MCP, the same in one command: + +```sh +npx strokedb --share --no-open --json --table users +``` diff --git a/cli/package.json b/cli/package.json index 1b38fbb8..41a045f0 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "strokedb", - "version": "0.3.0", + "version": "0.4.0", "description": "Open your project's database in Stroke: the desktop app if it's installed, otherwise the web studio at stroke.click/studio", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click/studio", diff --git a/cli/src/cli.js b/cli/src/cli.js index c5c546f9..69694c21 100644 --- a/cli/src/cli.js +++ b/cli/src/cli.js @@ -11,6 +11,7 @@ const HELP = `strokedb - open your project's database in Stroke Usage npx strokedb [connection] Desktop app if installed, else the web studio npx strokedb --web [connection] Always the web studio + npx strokedb mcp [connection] An MCP server for AI agents (see below) connection A URL (postgres://, mysql://, ...) or a SQLite file. Left out, it's read from ${URL_KEYS.slice(0, 3).join(', ')}, ... in the @@ -26,12 +27,25 @@ Options device, through stroke.click's relay. Read-only: browse and run SELECTs. End-to-end encrypted; the key is only in the link. Needs Node 22+. - --write With --share: let the link edit rows and run any SQL + --write With --share or mcp: allow edits (read-only otherwise) + --table
Open on this table (schema.table or just its name) + --json Print the links as one JSON line, for scripts and agents -h, --help Show this help -v, --version Show the version The web studio talks to a bridge on 127.0.0.1 that only answers the tab this -command opens. It stops when you press Ctrl+C.` +command opens. It stops when you press Ctrl+C. + +AI agents + An agent on another machine (a cloud box, a container) can show you the + database. Add the MCP server to it once: + + claude mcp add strokedb -- npx -y strokedb mcp + + It reads the database (list_tables, describe_table, query) and its + show_table tool hands you a link that opens a table in the web studio or + the Stroke app; later calls switch your open studio to the next table. + Without MCP: npx strokedb --share --no-open --json --table users` /** @param {string[]} argv */ export async function main(argv) { @@ -46,6 +60,8 @@ export async function main(argv) { 'no-open': { type: 'boolean' }, share: { type: 'boolean' }, write: { type: 'boolean' }, + table: { type: 'string' }, + json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, }, @@ -57,15 +73,44 @@ export async function main(argv) { } const cwd = process.cwd() - const found = findConnection({ arg: positionals[0], cwd }) + const mcp = positionals[0] === 'mcp' + const found = findConnection({ arg: positionals[mcp ? 1 : 0], cwd }) + if (mcp) { + // stdout belongs to the protocol: everything else goes to stderr. + if (!found) { + console.error('strokedb mcp: no database found. Pass one (npx strokedb mcp postgres://...), or set DATABASE_URL.') + return 1 + } + const engine = engineOf(found.uri) + if (!engine) { + console.error('strokedb mcp: PostgreSQL, MySQL and SQLite only.') + return 1 + } + quietSqliteWarning() + console.error(`strokedb mcp: ${redact(found.uri)} (from ${found.source})${values.write ? ', writable' : ', read-only'}`) + const { runMcp } = await import('./mcp.js') + await runMcp({ + uri: found.uri, + engine, + name: values.name ?? path.basename(cwd), + write: !!values.write, + studio: process.env.STROKE_STUDIO_URL || `${STUDIO_ORIGIN}/studio`, + }) + return 0 + } if (!found) { console.error(`No database found here.\n\nPass one (npx strokedb postgres://user:pass@host/db), set DATABASE_URL in .env,\nor run this in a folder with a .db or .sqlite file.`) return 1 } const name = values.name ?? path.basename(cwd) - console.log(`Database: ${redact(found.uri)} (from ${found.source})`) + // --json keeps stdout to the one line; the rest goes to stderr. + const say = values.json ? (/** @type {string} */ m) => console.error(m) : (/** @type {string} */ m) => console.log(m) + say(`Database: ${redact(found.uri)} (from ${found.source})`) + const openTable = values.table?.trim() || '' + /** The table to open first, as a fragment parameter. */ + const withTable = (/** @type {string} */ link) => (openTable ? `${link}&${new URLSearchParams({ open: openTable })}` : link) - if (values.write && !values.share) { + if (values.write && !values.share && !mcp) { console.error('--write goes with --share.') return 1 } @@ -106,9 +151,11 @@ export async function main(argv) { origins: [new URL(studio).origin], port: values.port ? Number(values.port) : 0, }) - const link = studioUrl({ studio, port: bridge.port, token: bridge.token }) + const link = withTable(studioUrl({ studio, port: bridge.port, token: bridge.token })) const opened = !values['no-open'] ? await openUrl(link) : false - console.log(`\n${opened ? 'Opened' : 'Open'} the studio${opened ? '' : ' at'}:\n ${link}\n\nThe link is the key to this session; don't share it. Press Ctrl+C to stop.`) + say(`\n${opened ? 'Opened' : 'Open'} the studio${opened ? '' : ' at'}:\n ${link}\n\nThe link is the key to this session; don't share it. Press Ctrl+C to stop.`) + /** @type {Record} */ + const out = { database: redact(found.uri), studio: link } /** @type {{ close(): void } | null} */ let relay = null @@ -124,14 +171,19 @@ export async function main(argv) { routes: makeRoutes({ engine: sharedDb, name, shared: true, write: !!values.write }), ...share, base: new URL(studio).origin, - onStatus: (status, detail) => console.log(status === 'online' ? ' Sharing: online' : ` Sharing: ${detail ?? 'offline'}`), + onStatus: (status, detail) => say(status === 'online' ? ' Sharing: online' : ` Sharing: ${detail ?? 'offline'}`), }) - console.log(`\nShare link (Labs, ${values.write ? 'can edit' : 'read-only'}):\n ${shareUrl({ studio, ...share })}\n\nAnyone with this link can ${values.write ? 'read and change' : 'read'} this database while this runs. It's\nend-to-end encrypted: the key is only in the link, stroke.click sees ciphertext.`) + const shared = withTable(shareUrl({ studio, ...share })) + out.share = shared + out.app = `stroke://studio?${new URLSearchParams({ relay: share.room, key: share.key, ...(openTable ? { open: openTable } : {}) })}` + say(`\nShare link (Labs, ${values.write ? 'can edit' : 'read-only'}):\n ${shared}\n\nIn the Stroke app:\n ${out.app}\n\nAnyone with this link can ${values.write ? 'read and change' : 'read'} this database while this runs. It's\nend-to-end encrypted: the key is only in the link, stroke.click sees ciphertext.`) } catch (e) { console.error(`Could not start sharing: ${e instanceof Error ? e.message : e}`) } } + if (values.json) console.log(JSON.stringify(out)) + await new Promise((resolve) => { const stop = () => resolve(undefined) process.once('SIGINT', stop) diff --git a/cli/src/mcp.js b/cli/src/mcp.js new file mode 100644 index 00000000..72d5f3ae --- /dev/null +++ b/cli/src/mcp.js @@ -0,0 +1,226 @@ +// `strokedb mcp`: an MCP server for AI coding agents (Claude Code, Codex, +// Cursor...). An agent working on a machine somewhere else (a cloud box, a +// container) adds it once and can then show the person the database: it gets +// a shared-studio link that opens a table in their browser or in the Stroke +// app, and switches everyone already on that link to the table it names. +// +// claude mcp add strokedb -- npx -y strokedb mcp +// +// Stdio, newline-delimited JSON-RPC 2.0. stdout carries only protocol +// messages; anything for a human goes to stderr. + +import readline from 'node:readline' +import { openEngine } from './engines.js' +import { makeRoutes, isReadingSql, STUDIO_ORIGIN } from './bridge.js' +import { newShare, shareUrl, startRelayHost, joinPresenceHost } from './relay.js' + +const PROTOCOL = '2025-06-18' +/** Rows a query returns to the agent; the studio is for looking at more. */ +const QUERY_ROWS = 100 +/** Characters of tool output, so one wide table can't flood the agent's context. */ +const MAX_TEXT = 24_000 + +const TOOLS = [ + { + name: 'list_tables', + title: 'List tables', + description: 'List the tables and views in the database, with row counts where known.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true }, + }, + { + name: 'describe_table', + title: 'Describe a table', + description: 'Columns of a table: name, type, nullability, primary key, default.', + inputSchema: { + type: 'object', + properties: { table: { type: 'string', description: 'schema.table, or just the table name' } }, + required: ['table'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true }, + }, + { + name: 'query', + title: 'Run a read-only query', + description: `Run one read-only statement (SELECT, WITH, EXPLAIN, SHOW) and get up to ${QUERY_ROWS} rows back as JSON. Writes are refused.`, + inputSchema: { + type: 'object', + properties: { sql: { type: 'string', description: 'One read-only SQL statement' } }, + required: ['sql'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true }, + }, + { + name: 'show_table', + title: 'Show a table to the person', + description: + 'Open a table for the person in the Stroke studio, wherever they are. Returns a link to the web studio and a stroke:// link for the desktop app, both opening on this table. Anyone who already has the studio open from an earlier link switches to this table at once. Use it when they ask to see data ("show me the users table").', + inputSchema: { + type: 'object', + properties: { table: { type: 'string', description: 'schema.table, or just the table name' } }, + required: ['table'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true, openWorldHint: true }, + }, +] + +/** + * @param {{ + * uri: string, engine: string, name: string, write?: boolean, + * studio?: string, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream, + * log?: (msg: string) => void, + * }} o + */ +export async function runMcp({ uri, engine: engineId, name, write = false, studio = `${STUDIO_ORIGIN}/studio`, input = process.stdin, output = process.stdout, log = (m) => console.error(m) }) { + // Read-only unless --write: the engine itself refuses writes. + const db = await openEngine(engineId, uri, { readOnly: !write }) + /** @type {{ share: ReturnType, relay: { close(): void }, presence: Awaited> } | null} */ + let shared = null + let agentName = 'AI agent' + + /** @param {unknown} msg */ + const reply = (msg) => output.write(`${JSON.stringify(msg)}\n`) + + async function ensureShare() { + if (shared) return shared + const share = newShare() + const base = new URL(studio).origin + const relay = await startRelayHost({ + routes: makeRoutes({ engine: db, name, shared: true, write }), + ...share, + base, + onStatus: (s, d) => log(`strokedb: sharing ${s}${d ? ` (${d})` : ''}`), + }) + const presence = await joinPresenceHost({ room: share.room, key: share.key, base, name: agentName }) + shared = { share, relay, presence } + return shared + } + + /** @param {string} ref */ + async function resolveTable(ref) { + const tables = await db.tables() + const lower = ref.toLowerCase() + return ( + tables.find((t) => `${t.schema}.${t.name}` === ref) ?? + tables.find((t) => t.name === ref) ?? + tables.find((t) => t.name.toLowerCase() === lower || `${t.schema}.${t.name}`.toLowerCase() === lower) + ) + } + + /** @param {string} tool @param {any} args @returns {Promise} */ + async function call(tool, args) { + switch (tool) { + case 'list_tables': { + const tables = await db.tables() + if (!tables.length) return 'No tables.' + return tables + .map((t) => `${t.schema}.${t.name}${t.kind === 'view' ? ' (view)' : ''}${t.rows != null ? ` ${t.rows} rows` : ''}`) + .join('\n') + } + case 'describe_table': { + const t = await resolveTable(String(args?.table ?? '')) + if (!t) throw new Error(`No table called ${args?.table}. Call list_tables to see what there is.`) + const cols = await db.columns(t.schema, t.name) + return `${t.schema}.${t.name}\n${cols + .map((c) => ` ${c.name} ${c.type}${c.primaryKey ? ' PRIMARY KEY' : ''}${c.nullable ? '' : ' NOT NULL'}${c.default != null ? ` DEFAULT ${c.default}` : ''}`) + .join('\n')}` + } + case 'query': { + const sql = String(args?.sql ?? '') + if (!isReadingSql(sql)) throw new Error('Only read-only statements here: SELECT, WITH, EXPLAIN or SHOW.') + const r = await db.query(sql) + const rows = (r.rows ?? []).slice(0, QUERY_ROWS).map((row) => Object.fromEntries((r.columns ?? []).map((c, i) => [c, row[i]]))) + const more = (r.rows?.length ?? 0) > QUERY_ROWS ? `\n(${r.rows.length - QUERY_ROWS} more rows not shown; show_table opens them all for the person.)` : '' + return JSON.stringify(rows, null, 1) + more + } + case 'show_table': { + const t = await resolveTable(String(args?.table ?? '')) + if (!t) throw new Error(`No table called ${args?.table}. Call list_tables to see what there is.`) + const ref = `${t.schema}.${t.name}` + const { share, presence } = await ensureShare() + const watching = presence.here + await presence.openTable(ref) + const web = `${shareUrl({ studio, room: share.room, key: share.key })}&${new URLSearchParams({ open: ref })}` + const app = `stroke://studio?${new URLSearchParams({ relay: share.room, key: share.key, open: ref })}` + return [ + watching + ? `Switched the ${watching === 1 ? 'person' : `${watching} people`} on the studio to ${ref}.` + : `Ready to show ${ref}. Give the person this link:`, + '', + `Web: ${web}`, + `Stroke app: ${app}`, + '', + `The link is the key to a live, end-to-end encrypted view of this database (${write ? 'read and write' : 'read-only'}), working while this MCP server runs. Share it only with the person you're working with. Later show_table calls reuse it and switch their view.`, + ].join('\n') + } + default: + throw new Error(`Unknown tool: ${tool}`) + } + } + + /** @param {any} msg */ + async function handle(msg) { + const { id, method, params } = msg ?? {} + const isRequest = id !== undefined && id !== null + try { + let result + switch (method) { + case 'initialize': { + const client = String(params?.clientInfo?.name ?? '') + agentName = client === 'claude-code' ? 'Claude Code' : client ? client.replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()).slice(0, 40) : 'AI agent' + result = { + protocolVersion: typeof params?.protocolVersion === 'string' ? params.protocolVersion : PROTOCOL, + capabilities: { tools: {} }, + serverInfo: { name: 'strokedb', title: 'Stroke', version: '0.4.0' }, + instructions: `Database: ${name} (${engineId}). Use list_tables, describe_table and query to look at it. When the person wants to see data, call show_table: it returns a link that opens the table for them in the Stroke web studio or desktop app, wherever they are.`, + } + break + } + case 'ping': + result = {} + break + case 'tools/list': + result = { tools: TOOLS } + break + case 'tools/call': { + try { + let text = await call(String(params?.name ?? ''), params?.arguments ?? {}) + if (text.length > MAX_TEXT) text = `${text.slice(0, MAX_TEXT)}\n(cut at ${MAX_TEXT} characters)` + result = { content: [{ type: 'text', text }] } + } catch (e) { + result = { content: [{ type: 'text', text: e instanceof Error ? e.message : String(e) }], isError: true } + } + break + } + default: + if (!isRequest) return // notifications/initialized and friends + return reply({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } }) + } + if (isRequest) reply({ jsonrpc: '2.0', id, result }) + } catch (e) { + if (isRequest) reply({ jsonrpc: '2.0', id, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }) + } + } + + const rl = readline.createInterface({ input, crlfDelay: Infinity }) + /** @type {Promise[]} */ + const pending = [] + rl.on('line', (line) => { + if (!line.trim()) return + let msg + try { + msg = JSON.parse(line) + } catch { + return void reply({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + } + pending.push(handle(msg)) + }) + await new Promise((resolve) => rl.once('close', resolve)) + await Promise.allSettled(pending) + shared?.presence.close() + shared?.relay.close() + await db.close().catch(() => {}) +} diff --git a/cli/src/relay.js b/cli/src/relay.js index 508240b5..342e065a 100644 --- a/cli/src/relay.js +++ b/cli/src/relay.js @@ -138,3 +138,101 @@ export async function startRelayHost({ routes, room, key, secret, base = 'https: }, } } + +/** + * Join a share's presence as its host, so this side can show everyone on the + * link a table (`strokedb mcp`'s show_table, an agent saying "show me users"). + * Same protocol as the studio page (stroke-web src/lib/relay/presence.ts) and + * the desktop app (src/lib/share-presence.js); every message is sealed. + * @param {{ room: string, key: string, base?: string, name: string }} o + */ +export async function joinPresenceHost({ room, key, base = 'https://stroke.click', name }) { + const cryptoKey = await importKey(key) + const url = `${base.replace(/^http/, 'ws')}/api/relay/${room}/presence` + // Violet, so an agent reads as a different kind of participant at a glance. + const me = { name, color: '#8e4ec6', role: 'host' } + /** @type {{ tab: string | null }} */ + const state = { tab: null } + let closed = false + let delay = 1000 + /** @type {WebSocket | null} */ + let ws = null + /** @type {ReturnType | undefined} */ + let ping + /** How many others are on the link right now (by sender id). */ + const here = new Set() + + /** @param {unknown} msg */ + const send = async (msg) => { + const sock = ws + if (!sock || sock.readyState !== 1) return false + sock.send(JSON.stringify(await seal(cryptoKey, msg))) + return true + } + const sendState = () => send({ t: 'state', ...me, tab: state.tab, cell: null, pointer: null, editing: null }) + + const connect = () => { + if (closed) return + const sock = new WebSocket(url) + ws = sock + sock.addEventListener('open', () => { + delay = 1000 + void sendState() + void send({ t: 'hello' }) + clearInterval(ping) + ping = setInterval(() => void sendState(), 20_000) + }) + sock.addEventListener('message', async (ev) => { + let raw + try { + raw = JSON.parse(String(ev.data)) + } catch { + return + } + if (typeof raw?.gone === 'number') return void here.delete(raw.gone) + if (typeof raw?.from !== 'number' || typeof raw.iv !== 'string' || typeof raw.ct !== 'string') return + let msg + try { + msg = await open(cryptoKey, raw) + } catch { + return + } + if (msg?.t === 'state') here.add(raw.from) + if (msg?.t === 'hello') void sendState() + }) + sock.addEventListener('close', () => { + clearInterval(ping) + here.clear() + if (closed || ws !== sock) return + setTimeout(connect, delay) + delay = Math.min(delay * 2, 30_000) + }) + sock.addEventListener('error', () => {}) + } + connect() + + return { + /** People on the link now. */ + get here() { + return here.size + }, + /** + * Show everyone on the link this table (`schema.table` or a bare name). + * @param {string} table + */ + async openTable(table) { + state.tab = table + await sendState() + return send({ t: 'open', table }) + }, + close() { + closed = true + clearInterval(ping) + try { + ws?.close(1000, 'Stopped sharing') + } catch { + // already closed + } + }, + } +} diff --git a/cli/test/cli.test.js b/cli/test/cli.test.js index d1f6460a..527701c9 100644 --- a/cli/test/cli.test.js +++ b/cli/test/cli.test.js @@ -229,3 +229,57 @@ test('sqlite: a read-only engine refuses writes at the file level', async () => await assert.rejects(() => ro.update({ schema: 'main', table: 't', key: { id: 1 }, set: { a: 'z' } }), /read-only/) await ro.close() }) + +test('mcp: initialize, tools, read-only query, and refusals', async () => { + const { runMcp } = await import('../src/mcp.js') + const { PassThrough } = await import('node:stream') + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'strokedb-mcp-')) + const file = path.join(dir, 'app.db') + const seed = await openSqlite(file) + await seed.query('create table users (id integer primary key, email text not null)') + await seed.query("insert into users (email) values ('a@x.io'), ('b@x.io')") + await seed.close() + + const input = new PassThrough() + const output = new PassThrough() + /** @type {any[]} */ + const replies = [] + let buf = '' + output.on('data', (c) => { + buf += c + let i + while ((i = buf.indexOf('\n')) >= 0) { + replies.push(JSON.parse(buf.slice(0, i))) + buf = buf.slice(i + 1) + } + }) + const done = runMcp({ uri: `file:${file}`, engine: 'sqlite', name: 'app', input, output, log: () => {} }) + const send = (/** @type {any} */ m) => input.write(`${JSON.stringify(m)}\n`) + send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', clientInfo: { name: 'claude-code' } } }) + send({ jsonrpc: '2.0', method: 'notifications/initialized' }) + send({ jsonrpc: '2.0', id: 2, method: 'tools/list' }) + send({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'list_tables', arguments: {} } }) + send({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'describe_table', arguments: { table: 'USERS' } } }) + send({ jsonrpc: '2.0', id: 5, method: 'tools/call', params: { name: 'query', arguments: { sql: 'select email from users order by id' } } }) + send({ jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'query', arguments: { sql: 'delete from users' } } }) + send({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'show_table', arguments: { table: 'nope' } } }) + send({ jsonrpc: '2.0', id: 8, method: 'no/such' }) + input.end() + await done + + const byId = Object.fromEntries(replies.map((r) => [r.id, r])) + assert.equal(replies.length, 8, 'a reply per request, none for the notification') + assert.equal(byId[1].result.serverInfo.name, 'strokedb') + assert.deepEqual(byId[2].result.tools.map((t) => t.name), ['list_tables', 'describe_table', 'query', 'show_table']) + assert.match(byId[3].result.content[0].text, /main\.users {2}2 rows/) + assert.match(byId[4].result.content[0].text, /id INTEGER PRIMARY KEY/) + assert.deepEqual(JSON.parse(byId[5].result.content[0].text), [{ email: 'a@x.io' }, { email: 'b@x.io' }]) + assert.equal(byId[6].result.isError, true) + assert.equal(byId[7].result.isError, true) + assert.match(byId[7].result.content[0].text, /No table called nope/) + assert.equal(byId[8].error.code, -32601) + // The refused DELETE changed nothing. + const check = await openSqlite(file) + assert.equal((await check.query('select count(*) n from users')).rows[0][0], 2) + await check.close() +}) diff --git a/docs/accounts-and-sync.md b/docs/accounts-and-sync.md index 20fd33a8..b3486852 100644 --- a/docs/accounts-and-sync.md +++ b/docs/accounts-and-sync.md @@ -239,7 +239,7 @@ Response `200`: - `plan` is `pro` when the user has an active, unrevoked, unexpired license, or a trial still running. The account trial starts on the first `/api/me` and - lasts 17 days (the app's `TRIAL_DAYS`), keyed by user id. + lasts 30 days (the server's `TRIAL_DAYS`), keyed by user id. - `valid_until` = `issued_at` + 7 days: the app may trust a cached, signature- checked entitlement offline until then. - Signing reuses `LICENSE_PRIVATE_KEY_HEX`; the app verifies with the existing diff --git a/package-lock.json b/package-lock.json index 1bea7063..96526864 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "stroke", - "version": "2.19.0", + "version": "3.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "stroke", - "version": "2.19.0", + "version": "3.7.0", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@codemirror/autocomplete": "^6.20.3", @@ -67,7 +67,10 @@ "tailwind-merge": "^3.6.0", "tailwind-variants": "^3.2.2", "tailwindcss": "^4.3.0", - "tw-animate-css": "^1.4.0" + "tw-animate-css": "^1.4.0", + "y-codemirror.next": "^0.3.6", + "y-protocols": "^1.0.7", + "yjs": "^13.6.33" }, "devDependencies": { "@emnapi/core": "^1.10.0", @@ -3809,6 +3812,16 @@ "dev": true, "license": "ISC" }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "license": "MIT", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", @@ -3905,6 +3918,27 @@ "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==", "license": "MIT" }, + "node_modules/lib0": { + "version": "0.2.120", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.120.tgz", + "integrity": "sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==", + "license": "MIT", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/lightningcss": { "version": "1.32.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", @@ -6010,6 +6044,61 @@ "dev": true, "license": "MIT" }, + "node_modules/y-codemirror.next": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/y-codemirror.next/-/y-codemirror.next-0.3.6.tgz", + "integrity": "sha512-GnmVXhTe+UtoFbbaSdwhq6gdAQZdIY9az0Xj6HR2J4PO6Yw4w3xaaSssU+6T72WhXAI0wf9FbuY2s0Ms+WrexA==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.42" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "yjs": "^13.5.6" + } + }, + "node_modules/y-protocols": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.7.tgz", + "integrity": "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.85" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/yjs": { + "version": "13.6.33", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz", + "integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.99" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/zimmerframe": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", diff --git a/package.json b/package.json index 4f996907..09de7092 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "stroke", "private": true, - "version": "3.0.0", + "version": "3.7.5", "description": "Fast, minimal desktop database client for PostgreSQL, MySQL, SQLite, D1, and more", "license": "SEE LICENSE IN LICENSE", "homepage": "https://stroke.click", @@ -113,7 +113,10 @@ "tailwind-merge": "^3.6.0", "tailwind-variants": "^3.2.2", "tailwindcss": "^4.3.0", - "tw-animate-css": "^1.4.0" + "tw-animate-css": "^1.4.0", + "y-codemirror.next": "^0.3.6", + "y-protocols": "^1.0.7", + "yjs": "^13.6.33" }, "overrides": { "dompurify": "^3.4.13", diff --git a/packaging/aur/stroke-bin/PKGBUILD.in b/packaging/aur/stroke-bin/PKGBUILD.in index 8d3dfad5..8d499c42 100644 --- a/packaging/aur/stroke-bin/PKGBUILD.in +++ b/packaging/aur/stroke-bin/PKGBUILD.in @@ -3,7 +3,7 @@ # release, which fills in the version and the .deb checksum. pkgname=stroke-bin pkgver=@VERSION@ -pkgrel=1 +pkgrel=@PKGREL@ pkgdesc="Native database client for PostgreSQL, MySQL, SQLite, MongoDB, Redis and more, with an AI agent and an MCP server" arch=('x86_64') url="https://stroke.click" @@ -20,11 +20,16 @@ sha256sums=('@SHA256@' package() { bsdtar -xf data.tar.gz -C "$pkgdir" - # The .deb names its binary and icon "app"; on Arch that would collide with - # anything else called app, so both become "stroke". - mv "$pkgdir/usr/bin/app" "$pkgdir/usr/bin/stroke" + # Builds before 2.20 name the binary and icon "app"; on Arch that would + # collide with anything else called app, so both become "stroke". Newer + # .debs already ship them as "stroke". + if [[ -e "$pkgdir/usr/bin/app" ]]; then + mv "$pkgdir/usr/bin/app" "$pkgdir/usr/bin/stroke" + fi for icon in "$pkgdir"/usr/share/icons/hicolor/*/apps/app.png; do - mv "$icon" "${icon%/app.png}/stroke.png" + if [[ -e "$icon" ]]; then + mv "$icon" "${icon%/app.png}/stroke.png" + fi done sed -i -e 's/^Exec=app$/Exec=stroke/' \ -e 's/^Icon=app$/Icon=stroke/' \ diff --git a/scripts/design-lint-baseline.json b/scripts/design-lint-baseline.json index 9b033f8f..f1ea11a5 100644 --- a/scripts/design-lint-baseline.json +++ b/scripts/design-lint-baseline.json @@ -1,7 +1,4 @@ { - "src/lib/components/AdvisorPage.svelte": { - "rounded-px": 1 - }, "src/lib/components/AiChat.svelte": { "h-px": 2, "rounded-px": 1 @@ -17,26 +14,15 @@ "rounded-px": 1 }, "src/lib/components/CellEditorPanel.svelte": { - "rounded-px": 4 + "rounded-px": 3 }, "src/lib/components/ChartView.svelte": { "rounded-px": 1 }, - "src/lib/components/ChartsPage.svelte": { - "rounded-px": 2 - }, "src/lib/components/ConnectionModal.svelte": { - "rounded-xl": 5, - "h-px": 1, + "rounded-xl": 4, "rounded-px": 2 }, - "src/lib/components/DangerousActionDialog.svelte": { - "h-px": 1 - }, - "src/lib/components/DashboardPage.svelte": { - "rounded-px": 1, - "h-px": 2 - }, "src/lib/components/DataDiffPage.svelte": { "rounded-px": 3 }, @@ -46,14 +32,10 @@ "src/lib/components/DatabaseSwitcher.svelte": { "rounded-px": 1 }, - "src/lib/components/DropDatabaseDialog.svelte": { - "h-px": 1 - }, "src/lib/components/EntityRelationPage.svelte": { "rounded-px": 7 }, "src/lib/components/ExtensionsPage.svelte": { - "h-px": 2, "rounded-px": 1 }, "src/lib/components/JsonPathSuggest.svelte": { @@ -74,12 +56,9 @@ "src/lib/components/MongoIndexesView.svelte": { "rounded-xl": 1 }, - "src/lib/components/NotebookEditor.svelte": { - "rounded-px": 1 - }, "src/lib/components/Onboarding.svelte": { "h-px": 1, - "rounded-xl": 2 + "rounded-xl": 1 }, "src/lib/components/OrmRunner.svelte": { "rounded-px": 2 @@ -90,15 +69,9 @@ "src/lib/components/RelationTreePage.svelte": { "rounded-px": 2 }, - "src/lib/components/SchemaPage.svelte": { - "rounded-px": 1 - }, "src/lib/components/SchemaTimelinePage.svelte": { "rounded-px": 1 }, - "src/lib/components/SearchPage.svelte": { - "rounded-px": 1 - }, "src/lib/components/SearchableMenu.svelte": { "rounded-px": 1 }, @@ -113,8 +86,7 @@ "rounded-px": 2 }, "src/lib/components/SidebarObjects.svelte": { - "rounded-px": 1, - "h-px": 1 + "rounded-px": 1 }, "src/lib/components/SidebarTree.svelte": { "rounded-px": 1 @@ -128,9 +100,6 @@ "src/lib/components/StructureView.svelte": { "rounded-px": 1 }, - "src/lib/components/StudioShell.svelte": { - "rounded-xl": 1 - }, "src/lib/components/TrialExpiredScreen.svelte": { "h-px": 1 }, diff --git a/scripts/release-notes.mjs b/scripts/release-notes.mjs new file mode 100644 index 00000000..20738dff --- /dev/null +++ b/scripts/release-notes.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node +// Release notes for a version: every CHANGELOG.md section since the previous +// stable tag, merged by heading (src/lib/release-notes.js). +// +// node scripts/release-notes.mjs 3.7.5 # GitHub release body +// node scripts/release-notes.mjs 3.7.5 --plain # latest.json (no bold) +// +// A pre-release version gets its own section only. The previous stable tag +// comes from `git ls-remote --tags origin`; RELEASE_NOTES_SINCE overrides it. +// `.github/release-highlights/.md`, when present, goes on top of the +// GitHub body (not the plain one: the update dialog lists changes, not prose). + +import fs from 'node:fs' +import { execFileSync } from 'node:child_process' +import { collectNotes, previousStable } from '../src/lib/release-notes.js' + +const version = String(process.argv[2] ?? '').replace(/^v/, '') +const plain = process.argv.includes('--plain') +if (!version) { + console.error('usage: release-notes.mjs [--plain]') + process.exit(2) +} + +const changelog = fs.readFileSync('CHANGELOG.md', 'utf8') + +let since = process.env.RELEASE_NOTES_SINCE || null +if (!since && !version.includes('-')) { + try { + const out = execFileSync('git', ['ls-remote', '--tags', '--refs', 'origin'], { encoding: 'utf8' }) + const tags = out.split('\n').map((l) => l.split('refs/tags/')[1]).filter(Boolean) + since = previousStable(tags, version) + } catch (e) { + console.error(`release-notes: could not list tags, using ${version} alone: ${e instanceof Error ? e.message : e}`) + } +} + +let notes = collectNotes(changelog, version, since) +if (plain) { + // Apps before 3.6.5 print markdown bold as asterisks; newer ones read + // `Title - text` without them (changelog.js splitEntry). + notes = notes.replace(/\*\*([^*\n]+)\*\*/g, '$1') +} else { + const highlights = `.github/release-highlights/${version}.md` + if (fs.existsSync(highlights)) notes = `${fs.readFileSync(highlights, 'utf8').trim()}\n\n${notes}` + if (since && notes) notes += `\n\n_Everything since v${since}._` +} +process.stdout.write(notes) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index e722a9bc..7a7260ad 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -195,6 +195,7 @@ dependencies = [ "objc2-app-kit", "objc2-quartz-core", "objc2-web-kit", + "odbc-api", "oracle", "portable-pty", "redis", @@ -367,7 +368,7 @@ dependencies = [ "arrow-ord", "arrow-schema", "arrow-select", - "atoi", + "atoi 2.0.0", "base64 0.22.1", "chrono", "comfy-table", @@ -632,6 +633,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "atoi" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d12c37257553c19e9aee6cba77814fdc9e07844abfc8b3a2c377cd920ee5a993" +dependencies = [ + "num-traits", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -3776,9 +3786,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" dependencies = [ "value-bag", ] @@ -4571,6 +4581,28 @@ dependencies = [ "memchr", ] +[[package]] +name = "odbc-api" +version = "30.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07df20ae00dc7fc31c9ae32451bb0d83fb9d18ddb970e066b26e43d6a76cd9a0" +dependencies = [ + "atoi 3.1.1", + "log", + "odbc-sys", + "thiserror 2.0.18", + "widestring", +] + +[[package]] +name = "odbc-sys" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e3a0f2c6531470f498c7cc5054f6b2a5922b5e82a5151065a257c1eb5ee1cd" +dependencies = [ + "unix-odbc", +] + [[package]] name = "odpic-sys" version = "0.1.1" @@ -6708,7 +6740,7 @@ dependencies = [ name = "sqlx-mysql" version = "0.8.6" dependencies = [ - "atoi", + "atoi 2.0.0", "base64 0.22.1", "bitflags 2.11.1", "byteorder", @@ -6751,7 +6783,7 @@ dependencies = [ name = "sqlx-postgres" version = "0.8.6" dependencies = [ - "atoi", + "atoi 2.0.0", "base64 0.22.1", "bitflags 2.11.1", "byteorder", @@ -6791,7 +6823,7 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" dependencies = [ - "atoi", + "atoi 2.0.0", "chrono", "flume", "futures-channel", @@ -8165,6 +8197,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "unix-odbc" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26bdaf2156eebadc0dbabec5b2c2a6f92bff5cface28f3f0a367d2ee9aeca0e2" +dependencies = [ + "cc", +] + [[package]] name = "untrusted" version = "0.9.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f2dd320f..e586bb28 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -76,6 +76,11 @@ tiberius = { version = "0.13.0", default-features = false, features = ["rustls", # time); the Oracle Client library (Instant Client) is loaded at runtime on the # first Oracle connect, so it is only needed by users who connect to Oracle. oracle = "0.6.3" +# ODBC bridge (src/db/odbc.rs). Windows has its own driver manager (odbc32); +# elsewhere unixODBC is built from source into the app (see the target table +# below), so the app starts without it and only the database's own driver has +# to be installed. +odbc-api = { version = "30", default-features = false, features = ["odbc_version_3_80"] } # Pinned as a direct dependency only to pick the TLS crypto provider at # startup (see `run`): tiberius 0.13 enables aws-lc-rs next to the ring the # other drivers use, and rustls then has no default of its own. @@ -111,6 +116,9 @@ objc2-web-kit = { version = "0.3", features = ["WKWebView"] } webview2-com = "0.39" windows-core = "0.62" +[target.'cfg(not(windows))'.dependencies] +odbc-api = { version = "30", default-features = false, features = ["odbc_version_3_80", "vendored-unix-odbc"] } + [target.'cfg(target_os = "linux")'.dependencies] webkit2gtk = { version = "=2.0.2", features = ["v2_38"] } gdk = "0.18" diff --git a/src-tauri/src/account.rs b/src-tauri/src/account.rs index a9755472..0f57baa9 100644 --- a/src-tauri/src/account.rs +++ b/src-tauri/src/account.rs @@ -366,7 +366,7 @@ pub fn license_status(dir: &Path) -> LicenseStatus { pub(crate) fn http() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::App) .timeout(Duration::from_secs(15)) .build() .unwrap_or_default() diff --git a/src-tauri/src/cloud_backup.rs b/src-tauri/src/cloud_backup.rs index b61437ef..344af799 100644 --- a/src-tauri/src/cloud_backup.rs +++ b/src-tauri/src/cloud_backup.rs @@ -251,6 +251,8 @@ async fn dump_and_upload( }; let result = async { + // Through the saved connection's SSH tunnel, held until the dump is done. + let (config, _tunnel) = crate::db::connection::tunnel_any(config).await?; let conn = open(config).await?; crate::db::backup::reset_cancel(); let rep = crate::db::backup::Reporter::silent(); diff --git a/src-tauri/src/cloudflare.rs b/src-tauri/src/cloudflare.rs index 4a49d67e..97d2a1fd 100644 --- a/src-tauri/src/cloudflare.rs +++ b/src-tauri/src/cloudflare.rs @@ -69,7 +69,7 @@ static CF_CLIENT: OnceLock = OnceLock::new(); fn http() -> &'static reqwest::Client { CF_CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::App) .user_agent("stroke/1.0") .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(4) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 4783573e..600f60a2 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -6,17 +6,26 @@ use tauri::Emitter; // One client for the whole process lifetime. reqwest maintains an internal // connection pool, so subsequent requests to the same host reuse the TLS // session and avoid the ~300-700 ms handshake on every call. -static AI_CLIENT: OnceLock = OnceLock::new(); - -fn ai_http_client() -> &'static reqwest::Client { - AI_CLIENT.get_or_init(|| { - reqwest::Client::builder() - .tcp_keepalive(std::time::Duration::from_secs(60)) - .pool_max_idle_per_host(4) - .pool_idle_timeout(std::time::Duration::from_secs(90)) - .build() - .expect("failed to build AI HTTP client") - }) +/// The AI client and the proxy-settings generation it was built for: a change +/// in Settings > Network rebuilds it on the next request. +static AI_CLIENT: std::sync::Mutex> = std::sync::Mutex::new(None); + +fn ai_http_client() -> reqwest::Client { + let generation = crate::proxy::generation(); + let mut guard = AI_CLIENT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((g, c)) = guard.as_ref() { + if *g == generation { + return c.clone(); + } + } + let client = crate::proxy::http_builder(crate::proxy::Kind::Ai) + .tcp_keepalive(std::time::Duration::from_secs(60)) + .pool_max_idle_per_host(4) + .pool_idle_timeout(std::time::Duration::from_secs(90)) + .build() + .expect("failed to build AI HTTP client"); + *guard = Some((generation, client.clone())); + client } // ── Streaming cancellation ──────────────────────────────────────────────────── @@ -417,7 +426,7 @@ use crate::db::{ SqlResult, SqliteConfig, TableInfo, TableRowCount, TableRows, TriggerInfo, SequenceInfo, ColumnStructureRow, TableColumnStructure, IncomingForeignKey, InsertRowResult, TunnelState, apply_table_changes, ApplyChangesResult, RowUpdate, - explain_pg, explain_mysql, explain_sqlite, explain_from_text_lines, explain_from_sqlite_plan, + explain_mysql, explain_sqlite, explain_from_text_lines, explain_from_sqlite_plan, }; use crate::db::connection::{require_conn, ClickhouseConfig, DuckdbConfig, MssqlConfig, MysqlConfig, OracleConfig, RedisConfig}; use crate::db::ActiveConnection; @@ -522,8 +531,8 @@ pub async fn test_clickhouse(config: ClickhouseConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_clickhouse_db(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> { - connect_clickhouse(state, config).await +pub async fn connect_clickhouse_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: ClickhouseConfig) -> Result<(), String> { + connect_clickhouse(state, tunnel_state, config).await } // ── Redis ───────────────────────────────────────────────────────────────────── @@ -534,8 +543,8 @@ pub async fn test_redis(config: RedisConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_redis_db(state: Db<'_>, config: RedisConfig) -> Result<(), String> { - connect_redis(state, config).await +pub async fn connect_redis_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: RedisConfig) -> Result<(), String> { + connect_redis(state, tunnel_state, config).await } /// Non-blocking keyspace iteration for the active Redis connection. Returns one @@ -675,12 +684,13 @@ pub async fn dynamodb_request( #[tauri::command] pub async fn test_couchdb(config: crate::db::couchdb::CouchConfig) -> Result<(), String> { + let (config, _tunnel) = crate::db::connection::resolve_couch_ssh(config).await?; crate::db::couchdb::ping(&config).await } #[tauri::command] -pub async fn connect_couchdb_db(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { - crate::db::connection::connect_couchdb(state, config).await +pub async fn connect_couchdb_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { + crate::db::connection::connect_couchdb(state, tunnel_state, config).await } /// One CouchDB HTTP call (path allowlisted) on the active connection. @@ -703,12 +713,13 @@ pub async fn couchdb_request( /// Connection test; answers which engine and version the server is. #[tauri::command] pub async fn test_elastic(config: crate::db::elastic::EsConfig) -> Result { + let (config, _tunnel) = crate::db::connection::resolve_elastic_ssh(config).await?; crate::db::elastic::ping(&config).await } #[tauri::command] -pub async fn connect_elastic_db(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> { - crate::db::connection::connect_elastic(state, config).await +pub async fn connect_elastic_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::elastic::EsConfig) -> Result<(), String> { + crate::db::connection::connect_elastic(state, tunnel_state, config).await } /// One REST call (path allowlisted) on the active connection. @@ -746,12 +757,13 @@ pub async fn elastic_import( #[tauri::command] pub async fn test_mongo(config: crate::db::mongo::MongoConfig) -> Result<(), String> { + let (config, _tunnel) = crate::db::connection::resolve_mongo_ssh(config).await?; crate::db::mongo::connect(&config).await.map(|_| ()) } #[tauri::command] -pub async fn connect_mongo_db(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { - crate::db::connection::connect_mongo(state, config).await +pub async fn connect_mongo_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { + crate::db::connection::connect_mongo(state, tunnel_state, config).await } fn require_mongo(state: &Db<'_>) -> Result { @@ -923,6 +935,147 @@ pub async fn connect_firestore_db(state: Db<'_>, config: crate::db::firestore::F crate::db::connection::connect_firestore(state, config).await } +/// Google Cloud Spanner (beta): the database answers, with these credentials. +#[tauri::command] +pub async fn test_spanner(config: crate::db::spanner::SpannerConfig) -> Result<(), String> { + let h = crate::db::spanner::connect(&config).await?; + crate::db::spanner::ping(&h).await +} + +#[tauri::command] +pub async fn connect_spanner_db(state: Db<'_>, config: crate::db::spanner::SpannerConfig) -> Result { + crate::db::connection::connect_spanner(state, config).await +} + +/// Google BigQuery (beta): the project answers, with these credentials. +#[tauri::command] +pub async fn test_bigquery(config: crate::db::bigquery::BigQueryConfig) -> Result<(), String> { + let h = crate::db::bigquery::connect(&config).await?; + crate::db::bigquery::ping(&h).await +} + +#[tauri::command] +pub async fn connect_bigquery_db(state: Db<'_>, config: crate::db::bigquery::BigQueryConfig) -> Result<(), String> { + crate::db::connection::connect_bigquery(state, config).await +} + +/// A database through ODBC (beta): the driver connects and the link is alive. +/// Returns what the driver reports itself as (`DB2/LINUXX8664`, `HDB`, ...). +#[tauri::command] +pub async fn test_odbc(config: crate::db::odbc::OdbcConfig) -> Result { + let (config, _tunnel) = crate::db::connection::resolve_odbc_ssh(config).await?; + let h = crate::db::odbc::connect(&config).await?; + crate::db::odbc::ping(&h).await?; + Ok(h.info.dbms.clone()) +} + +#[tauri::command] +pub async fn connect_odbc_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::odbc::OdbcConfig) -> Result { + crate::db::connection::connect_odbc(state, tunnel_state, config).await +} + +/// The ODBC drivers installed on this machine. +#[tauri::command] +pub async fn odbc_drivers() -> Result, String> { + crate::db::odbc::drivers().await +} + +/// The ODBC data sources (DSNs) configured on this machine. +#[tauri::command] +pub async fn odbc_data_sources() -> Result, String> { + crate::db::odbc::data_sources().await +} + +/// Snowflake (beta): signs in and the warehouse answers. +#[tauri::command] +pub async fn test_snowflake(config: crate::db::snowflake::SnowflakeConfig) -> Result<(), String> { + crate::db::snowflake::connect(&config).await.map(|_| ()) +} + +#[tauri::command] +pub async fn connect_snowflake_db(state: Db<'_>, config: crate::db::snowflake::SnowflakeConfig) -> Result<(), String> { + crate::db::connection::connect_snowflake(state, config).await +} + +// ── Neo4j (beta) ────────────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn test_neo4j(config: crate::db::neo4j::Neo4jConfig) -> Result<(), String> { + crate::db::neo4j::connect(&config).await.map(|_| ()) +} + +#[tauri::command] +pub async fn connect_neo4j_db(state: Db<'_>, config: crate::db::neo4j::Neo4jConfig) -> Result<(), String> { + crate::db::connection::connect_neo4j(state, config).await +} + +fn require_neo4j(state: &Db<'_>) -> Result { + match require_conn(state)? { + ActiveConnection::Doc(crate::db::docdb::DocConn::Neo4j(cfg)) => Ok(cfg), + _ => Err("Not connected to Neo4j".into()), + } +} + +/// Node labels with their node counts. +#[tauri::command] +pub async fn neo4j_labels(state: Db<'_>) -> Result, String> { + crate::db::neo4j::labels(&require_neo4j(&state)?).await +} + +#[tauri::command] +pub async fn neo4j_describe(state: Db<'_>, label: String) -> Result { + crate::db::neo4j::describe(&require_neo4j(&state)?, &label).await +} + +#[tauri::command] +pub async fn neo4j_page(state: Db<'_>, label: String, filter: Option, skip: i64, limit: i64) -> Result { + crate::db::neo4j::page(&require_neo4j(&state)?, &label, filter.as_deref().unwrap_or(""), skip, limit).await +} + +#[tauri::command] +pub async fn neo4j_save(state: Db<'_>, label: String, doc: serde_json::Value) -> Result { + crate::db::neo4j::save(&require_neo4j(&state)?, &label, &doc).await +} + +#[tauri::command] +pub async fn neo4j_delete(state: Db<'_>, id: String) -> Result<(), String> { + crate::db::neo4j::remove(&require_neo4j(&state)?, &id).await +} + +// ── InfluxDB (beta) ─────────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn test_influx(config: crate::db::influx::InfluxConfig) -> Result<(), String> { + crate::db::influx::connect(&config).await.map(|_| ()) +} + +#[tauri::command] +pub async fn connect_influx_db(state: Db<'_>, config: crate::db::influx::InfluxConfig) -> Result<(), String> { + crate::db::connection::connect_influx(state, config).await +} + +fn require_influx(state: &Db<'_>) -> Result { + match require_conn(state)? { + ActiveConnection::Doc(crate::db::docdb::DocConn::Influx(cfg)) => Ok(cfg), + _ => Err("Not connected to InfluxDB".into()), + } +} + +#[tauri::command] +pub async fn influx_measurements(state: Db<'_>) -> Result, String> { + crate::db::influx::measurements(&require_influx(&state)?).await +} + +#[tauri::command] +pub async fn influx_describe(state: Db<'_>, measurement: String) -> Result { + crate::db::influx::describe(&require_influx(&state)?, &measurement).await +} + +#[tauri::command] +pub async fn influx_page(state: Db<'_>, measurement: String, filter: Option, skip: i64, limit: i64) -> Result { + crate::db::influx::page(&require_influx(&state)?, &measurement, filter.as_deref().unwrap_or(""), skip, limit).await +} + /// One Firestore REST call (document paths of this database only). #[tauri::command] pub async fn firestore_request( @@ -942,12 +1095,13 @@ pub async fn firestore_request( #[tauri::command] pub async fn test_cassandra(config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { + let (config, _tunnel) = crate::db::connection::resolve_cassandra_ssh(config).await?; crate::db::cassandra::connect(&config).await.map(|_| ()) } #[tauri::command] -pub async fn connect_cassandra_db(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { - crate::db::connection::connect_cassandra(state, config).await +pub async fn connect_cassandra_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { + crate::db::connection::connect_cassandra(state, tunnel_state, config).await } fn require_cassandra(state: &Db<'_>) -> Result { @@ -1018,8 +1172,8 @@ pub async fn test_mssql(config: MssqlConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_mssql_db(state: Db<'_>, config: MssqlConfig) -> Result<(), String> { - connect_mssql(state, config).await +pub async fn connect_mssql_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: MssqlConfig) -> Result<(), String> { + connect_mssql(state, tunnel_state, config).await } // ── Oracle ────────────────────────────────────────────────────────────────────── @@ -1030,8 +1184,8 @@ pub async fn test_oracle(config: OracleConfig) -> Result<(), String> { } #[tauri::command] -pub async fn connect_oracle_db(state: Db<'_>, config: OracleConfig) -> Result<(), String> { - connect_oracle(state, config).await +pub async fn connect_oracle_db(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: OracleConfig) -> Result<(), String> { + connect_oracle(state, tunnel_state, config).await } /// The Oracle container the active connection is in (FREEPDB1, CDB$ROOT). @@ -1144,9 +1298,18 @@ pub async fn pg_explain_sql( state: Db<'_>, sql: String, analyze: Option, + // Names the run for `cancel_query`, like a console run's queryId. + query_id: Option, ) -> Result { match require_conn(&state)? { - ActiveConnection::Postgres(pool) => explain_pg(&pool, &sql, analyze.unwrap_or(true)).await, + ActiveConnection::Postgres(pool) => { + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let key = query_id.unwrap_or_else(|| "default".to_string()); + crate::db::connection::register_cancel(&state, &key, tx); + let r = crate::db::explain::explain_pg_stoppable(&pool, &sql, analyze.unwrap_or(true), Some(rx)).await; + crate::db::connection::unregister_cancel(&state, &key); + r + } ActiveConnection::Mysql(pool) => explain_mysql(&pool, &sql).await, ActiveConnection::Sqlite(pool) => explain_sqlite(&pool, &sql).await, ActiveConnection::Duckdb(h) => { @@ -1221,7 +1384,56 @@ pub async fn pg_explain_sql( let lines = crate::db::oracle::explain_lines(&h, &sql).await?; Ok(explain_from_text_lines(lines, "oracle")) } - _ => Err("EXPLAIN isn't supported for this engine yet".into()), + ActiveConnection::LibSql(cfg) => { + // libSQL is SQLite: the same (id, parent, notused, detail) rows. + let res = crate::db::libsql::query(&cfg, &format!("EXPLAIN QUERY PLAN {sql}"), vec![]).await?; + Ok(explain_from_sqlite_plan(&res, "libsql")) + } + ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(m)) => Ok(ExplainResult { + plan: crate::db::mongo::explain_plan(&m, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "mongodb".into(), + }), + ActiveConnection::Doc(crate::db::docdb::DocConn::Elastic(cfg)) => Ok(ExplainResult { + plan: crate::db::elastic::explain_plan(&cfg, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "elasticsearch".into(), + }), + ActiveConnection::Doc(crate::db::docdb::DocConn::Couch(cfg)) => Ok(ExplainResult { + plan: crate::db::couchdb::explain_plan(&cfg, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "couchdb".into(), + }), + ActiveConnection::Doc(crate::db::docdb::DocConn::Neo4j(cfg)) => Ok(ExplainResult { + plan: crate::db::neo4j::explain_plan(&cfg, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "neo4j".into(), + }), + // Redis, DynamoDB, Firestore, Cassandra/ScyllaDB and PostHog's HogQL + // API expose no query plan. + ActiveConnection::Spanner(h) => Ok(ExplainResult { + plan: crate::db::spanner::explain_plan(&h, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "spanner".into(), + }), + ActiveConnection::Bigquery(h) => Ok(ExplainResult { + plan: crate::db::bigquery::explain_plan(&h, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "bigquery".into(), + }), + ActiveConnection::Snowflake(h) => Ok(ExplainResult { + plan: crate::db::snowflake::explain_plan(&h, &sql).await?, + planning_time: 0.0, + execution_time: 0.0, + driver: "snowflake".into(), + }), + _ => Err("This engine doesn't expose a query plan".into()), } } @@ -1461,7 +1673,10 @@ pub async fn pg_get_table_rows( // like every other column, which is what the app did before and what the // setting turns back on for anyone who wants it. preview_wide: Option, + // The grid view this fetch is for; a newer load of the tab cancels it. + fetch_tag: Option, ) -> Result { + let _foreground = ForegroundFetch::begin(); get_table_rows( state, schema, @@ -1480,6 +1695,7 @@ pub async fn pg_get_table_rows( keyset, nulls_order, preview_wide.unwrap_or(true), + fetch_tag, ) .await } @@ -1726,6 +1942,190 @@ pub async fn pg_execute_sql_stream( result } +/// The key a table mirror walks by: the same seek the grid's windows use +/// (`seekKeyFor` in src/lib/keyset.js), plus where it sits in a row. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[allow(dead_code)] // The view's key; its presence is what makes paging by offset exact. +pub struct MirrorSeek { + column: String, + sql_type: String, + desc: bool, + index: usize, +} + +/// Rows per page while a table mirror streams. Large enough that a far link +/// is not all round trips, small enough that a page in flight holds up a +/// window the user asks for by well under a second. +const MIRROR_PAGE: i64 = 5_000; + +/// Mirror pages in flight at once. +const MIRROR_PARALLEL: usize = 2; + +/// How long the grid must have been quiet (no row fetch running or just +/// finished) before a mirror page starts. Opening a table or jumping fires +/// several window fetches in a row; a copy page squeezed in between them +/// shared the link with the next one and made the rows on screen slower. +const MIRROR_QUIET: std::time::Duration = std::time::Duration::from_millis(750); + +/// When the last grid row fetch finished, as ms since the first one (0 = never). +static FOREGROUND_LAST_END_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FOREGROUND_EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + +fn foreground_now_ms() -> u64 { + FOREGROUND_EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// Wait until no grid fetch is running and none has for MIRROR_QUIET. +async fn wait_for_quiet_grid() { + loop { + let busy = FOREGROUND_ROW_FETCHES.load(std::sync::atomic::Ordering::SeqCst) > 0; + let last = FOREGROUND_LAST_END_MS.load(std::sync::atomic::Ordering::SeqCst); + let since = foreground_now_ms().saturating_sub(last); + if !busy && (last == 0 || since >= MIRROR_QUIET.as_millis() as u64) { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } +} + +/// Grid row fetches in flight (`pg_get_table_rows`). A table mirror is +/// background work sharing the same link and pool: it waits while any is +/// running, so the rows on screen never queue behind the copy. +static FOREGROUND_ROW_FETCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Counts one foreground fetch for as long as it lives. +struct ForegroundFetch; +impl ForegroundFetch { + fn begin() -> Self { + FOREGROUND_ROW_FETCHES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + ForegroundFetch + } +} +impl Drop for ForegroundFetch { + fn drop(&mut self) { + FOREGROUND_LAST_END_MS.store(foreground_now_ms().max(1), std::sync::atomic::Ordering::SeqCst); + FOREGROUND_ROW_FETCHES.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } +} + +/// Copy a windowed table view into the result store, in its own order, so the +/// grid can read any window locally. +/// +/// Scrolled deep into a large table, every window was a remote `OFFSET n`: +/// the server reads and throws away n rows first, so row 196,000 of a remote +/// table took seconds and the grid sat on skeletons labelled "slow +/// connection". This reads the same query once, a few pages at a time, and +/// spools the rows under `id` in order. The window reads whatever has landed +/// with `result_window` and fetches the rest as before. Same rows, same shape +/// (wide-column previews included): it is the grid's query, not the console's. +/// +/// Returns the number of rows mirrored. Stops quietly once `id` is dropped (a +/// reload, a sort or filter change, an edit, the tab closing) or at `max_rows`. +#[tauri::command] +#[allow(clippy::too_many_arguments)] +pub async fn table_mirror( + state: Db<'_>, + store: State<'_, crate::db::result_store::ResultStore>, + id: String, + schema: String, + table: String, + search: Option, + search_is_regex: Option, + search_case_sensitive: Option, + sort_column: Option, + sort_direction: Option, + sorts: Option>, + filters: Option>, + nulls_order: Option, + preview_wide: Option, + seek: MirrorSeek, + max_rows: usize, + page_rows: Option, + parallel: Option, +) -> Result { + use futures::StreamExt; + let mut writer = store.create(&id)?; + // Sized by the grid from the row width (pickMirrorPage): a page in flight + // is what a scroll waits behind, so it is kept to a few hundred KB. + let page_limit = page_rows.unwrap_or(MIRROR_PAGE).clamp(100, MIRROR_PAGE); + let page_rows = page_limit as usize; + let parallel = parallel.unwrap_or(MIRROR_PARALLEL).clamp(1, MIRROR_PARALLEL); + let chunks = max_rows.div_ceil(page_rows).max(1); + // Every page is addressed by its offset, which on a single-column primary + // key is an index skip (see get_table_rows), so pages need not wait on the + // one before them for a key: MIRROR_PARALLEL are in flight at once and + // written in order. A far link is then bandwidth-bound instead of a round + // trip per page. The view's order is a unique key (the mirror only starts + // with a seek), so page k is exactly rows k*page..(k+1)*page. + let _ = &seek; + let fetch_page = |k: usize| { + let state = state.clone(); + let (store, id) = (store.clone(), id.clone()); + let (schema, table) = (schema.clone(), table.clone()); + let (search, sort_column, sort_direction) = (search.clone(), sort_column.clone(), sort_direction.clone()); + let (filters, sorts, nulls_order) = (filters.clone(), sorts.clone().unwrap_or_default(), nulls_order.clone()); + async move { + // Rows on screen first: start only once the grid has been quiet. + wait_for_quiet_grid().await; + // Dropped by the window: the view it mirrors is gone. + if store.get(&id).is_none() { + return Ok(None); + } + get_table_rows( + state, + schema, + table, + page_limit, + (k * page_rows) as i64, + search, + search_is_regex.unwrap_or(false), + search_case_sensitive.unwrap_or(false), + sort_column, + sort_direction, + filters, + k == 0, + false, + sorts, + None, + nulls_order, + preview_wide.unwrap_or(true), + None, + ) + .await + .map(Some) + } + }; + let mut pages = futures::stream::iter(0..chunks).map(fetch_page).buffered(parallel); + let mut total = 0usize; + let mut first = true; + while let Some(res) = pages.next().await { + let page = match res { + Ok(Some(p)) => p, + Ok(None) => return Ok(total), + Err(e) => { + store.drop_result(&id); + return Err(e); + } + }; + if first { + writer.start(page.columns.clone())?; + first = false; + } + let take = page.rows.len().min(max_rows.saturating_sub(total)); + for row in &page.rows[..take] { + writer.push(row)?; + } + total += take; + writer.flush()?; + if page.rows.len() < page_rows || total >= max_rows { + break; + } + } + writer.finish()?; + Ok(total) +} + /// Rows `[start, start + count)` of a stored result, in its current order, as /// a JSON array of row arrays (sent as stored, never re-encoded). #[tauri::command] @@ -1879,6 +2279,7 @@ pub async fn cancel_query( state: Db<'_>, query_id: Option, ) -> Result<(), String> { + log::info!("cancel_query: {}", query_id.as_deref().unwrap_or("(all)")); if let Ok(mut map) = state.cancels.lock() { match query_id { Some(id) => { diff --git a/src-tauri/src/copilot.rs b/src-tauri/src/copilot.rs index 7fc021e1..f763a50d 100644 --- a/src-tauri/src/copilot.rs +++ b/src-tauri/src/copilot.rs @@ -12,7 +12,7 @@ static COPILOT_CLIENT: OnceLock = OnceLock::new(); fn http_client() -> &'static reqwest::Client { COPILOT_CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Ai) .user_agent("stroke/1.0") .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(4) diff --git a/src-tauri/src/db/admin.rs b/src-tauri/src/db/admin.rs index 5dc88b74..09068dc6 100644 --- a/src-tauri/src/db/admin.rs +++ b/src-tauri/src/db/admin.rs @@ -37,7 +37,7 @@ impl Dialect { ActiveConnection::Mssql(_) => Some(Self::Mssql), ActiveConnection::Oracle(_) => Some(Self::Oracle), ActiveConnection::Clickhouse(_) => Some(Self::Clickhouse), - ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => None, + ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => None, } } @@ -139,6 +139,10 @@ pub(crate) async fn run_statement(conn: &ActiveConnection, sql: &str) -> Result< ActiveConnection::Mssql(h) => super::mssql::execute_sql(h, sql).await.map(|_| ()), ActiveConnection::Oracle(h) => super::oracle::execute_sql(h, sql).await.map(|_| ()), ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(cfg, sql).await.map(|_| ()), + ActiveConnection::Spanner(h) => super::spanner::query(h, sql).await.map(|_| ()), + ActiveConnection::Bigquery(h) => super::bigquery::query(h, sql).await.map(|_| ()), + ActiveConnection::Snowflake(h) => super::snowflake::query(h, sql).await.map(|_| ()), + ActiveConnection::Odbc(h) => super::odbc::query(h, sql).await.map(|_| ()), ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Err("This connection does not run DDL statements".into()), } } @@ -877,7 +881,7 @@ mod admin_live { #[ignore] async fn clickhouse_copies_and_drops() { let port = std::env::var("STROKE_CH_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(58123); - let cfg = ClickhouseConfig { + let cfg = ClickhouseConfig { ssh: None, via: None, name: "test".into(), host: "127.0.0.1".into(), port, @@ -928,7 +932,7 @@ mod admin_live { #[tokio::test] #[ignore] async fn mssql_copies_and_drops() { - let cfg = super::super::connection::MssqlConfig { + let cfg = super::super::connection::MssqlConfig { ssh: None, via: None, name: "test".into(), host: "127.0.0.1".into(), port: 51433, diff --git a/src-tauri/src/db/advisor.rs b/src-tauri/src/db/advisor.rs index 2d3cb710..de073456 100644 --- a/src-tauri/src/db/advisor.rs +++ b/src-tauri/src/db/advisor.rs @@ -65,6 +65,18 @@ pub struct AdvisorReport { /// Schemas no advice applies to. const SYSTEM_SCHEMAS: &str = "'pg_catalog','information_schema','pg_toast'"; +/// Objects an extension created (PostGIS's spatial_ref_sys, postgis_topology's +/// layer table): changing them is lost when the extension updates, so the +/// design checks leave them out, as pg_dump does. +const EXT_REL_C: &str = "NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend dx WHERE dx.classid = 'pg_catalog.pg_class'::regclass AND dx.objid = c.oid AND dx.deptype = 'e')"; +const EXT_REL_T: &str = "NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend dx WHERE dx.classid = 'pg_catalog.pg_class'::regclass AND dx.objid = t.oid AND dx.deptype = 'e')"; +const EXT_PROC_P: &str = "NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend dx WHERE dx.classid = 'pg_catalog.pg_proc'::regclass AND dx.objid = p.oid AND dx.deptype = 'e')"; + +/// A planner row estimate as text. reltuples is -1 until the table is first +/// vacuumed or analyzed, which read as "~-1 rows". +fn approx_rows(n: i64) -> String { + if n < 0 { "not analyzed yet".into() } else { format!("~{n} rows") } +} fn bytes_pretty(bytes: f64) -> String { const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; @@ -108,6 +120,7 @@ async fn check_rls_disabled(pool: &PgPool) -> Result, String AND NOT c.relrowsecurity AND NOT EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid) AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} AND n.nspname NOT LIKE 'pg\\_temp%' ORDER BY 1, 2" ); @@ -154,6 +167,7 @@ async fn check_policies_ignored(pool: &PgPool) -> Result, St JOIN pg_policy p ON p.polrelid = c.oid WHERE c.relkind IN ('r','p') AND NOT c.relrowsecurity AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} GROUP BY 1, 2 ORDER BY 1, 2" ); let rows = sqlx::query(&sql).fetch_all(pool).await.map_err(|e| e.to_string())?; @@ -185,6 +199,7 @@ async fn check_rls_no_policy(pool: &PgPool) -> Result, Strin WHERE c.relkind IN ('r','p') AND c.relrowsecurity AND NOT EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid) AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} ORDER BY 1, 2" ); let rows = sqlx::query(&sql).fetch_all(pool).await.map_err(|e| e.to_string())?; @@ -215,6 +230,7 @@ async fn check_definer_search_path(pool: &PgPool) -> Result, JOIN pg_namespace n ON n.oid = p.pronamespace WHERE p.prosecdef AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_PROC_P} AND NOT EXISTS (SELECT 1 FROM unnest(coalesce(p.proconfig, '{{}}'::text[])) c WHERE c LIKE 'search\\_path=%') ORDER BY 1, 2" ); @@ -253,6 +269,7 @@ async fn check_duplicate_index(pool: &PgPool) -> Result, Str JOIN pg_class t ON t.oid = x1.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_T} ORDER BY 5 DESC" ); let rows = sqlx::query(&sql).fetch_all(pool).await.map_err(|e| e.to_string())?; @@ -358,6 +375,7 @@ async fn check_unindexed_fk(pool: &PgPool) -> Result, String JOIN pg_namespace n ON n.oid = c.relnamespace WHERE con.contype = 'f' AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} AND NOT EXISTS ( SELECT 1 FROM pg_index i WHERE i.indrelid = con.conrelid @@ -385,7 +403,7 @@ async fn check_unindexed_fk(pool: &PgPool) -> Result, String entity: format!("{schema}.{table} ({name})"), entity_kind: "constraint".into(), description: "Postgres indexes the referenced side of a foreign key, never the referencing side. Joins across it, and the check behind every parent DELETE or UPDATE, scan this table end to end.".into(), - detail: Some(format!("{def} · ~{tuples} rows")), + detail: Some(format!("{def} · {}", approx_rows(tuples))), remediation: Some(format!( "CREATE INDEX CONCURRENTLY ON \"{schema}\".\"{table}\" ({cols});" )), @@ -465,6 +483,7 @@ async fn check_no_primary_key(pool: &PgPool) -> Result, Stri JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} AND n.nspname NOT LIKE 'pg\\_temp%' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary) ORDER BY c.reltuples DESC NULLS LAST" @@ -484,7 +503,7 @@ async fn check_no_primary_key(pool: &PgPool) -> Result, Stri entity: format!("{schema}.{table}"), entity_kind: "table".into(), description: "Nothing identifies a row here: duplicates can accumulate unnoticed, logical replication cannot carry updates, and tools that page by key - including this one - fall back to less stable ordering.".into(), - detail: Some(format!("~{tuples} rows")), + detail: Some(approx_rows(tuples)), remediation: Some(format!( "-- pick the column(s) that already identify a row:\nALTER TABLE \"{schema}\".\"{table}\" ADD PRIMARY KEY (id);\n-- or add a surrogate key:\n-- ALTER TABLE \"{schema}\".\"{table}\" ADD COLUMN id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY;" )), @@ -555,6 +574,7 @@ async fn check_wide_rows(pool: &PgPool) -> Result, String> { JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT IN ({SYSTEM_SCHEMAS}) + AND {EXT_REL_C} AND c.reltuples > 100 AND (pg_table_size(c.oid) / GREATEST(c.reltuples, 1)) > 1024 ORDER BY 5 DESC" @@ -699,4 +719,38 @@ mod tests { assert_eq!(bytes_pretty(17_064.0), "16.7 KB"); assert_eq!(bytes_pretty(203_603_968.0), "194.2 MB"); } + + #[test] + fn an_unanalyzed_table_has_no_negative_estimate() { + assert_eq!(super::approx_rows(-1), "not analyzed yet"); + assert_eq!(super::approx_rows(0), "~0 rows"); + assert_eq!(super::approx_rows(42), "~42 rows"); + } + + /// Against PostGIS (STROKE_TEST_POSTGIS) with postgis_topology installed: + /// the extensions' own tables (spatial_ref_sys, topology.layer, ...) are + /// not the user's to fix, so no design finding names them. + #[tokio::test] + async fn live_skips_extension_objects() { + let Ok(url) = std::env::var("STROKE_TEST_POSTGIS") else { return }; + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + let ext: Vec = sqlx::query_scalar( + "SELECT n.nspname || '.' || c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e' + WHERE c.relkind = 'r'", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert!(!ext.is_empty(), "the test database needs an extension with tables"); + let report = super::scan(&super::super::connection::ActiveConnection::Postgres(pool)).await.unwrap(); + for f in &report.findings { + if matches!(f.check_id.as_str(), "stale_stats" | "dead_tuples" | "unused_index" | "sequence_exhaustion") { + continue; + } + let table = f.entity.split(" (").next().unwrap_or(&f.entity); + assert!(!ext.iter().any(|e| e == table), "{} names an extension table: {}", f.check_id, f.entity); + assert!(!f.detail.as_deref().unwrap_or("").contains("~-"), "{}: {:?}", f.check_id, f.detail); + } + } } diff --git a/src-tauri/src/db/backup.rs b/src-tauri/src/db/backup.rs index a7b79fa8..2cfc8900 100644 --- a/src-tauri/src/db/backup.rs +++ b/src-tauri/src/db/backup.rs @@ -487,6 +487,24 @@ impl InsertBatcher { /// Double-quoted identifier (Postgres / SQLite). fn qi(s: &str) -> String { format!("\"{}\"", s.replace('"', "\"\"")) } + +/// `CREATE EXTENSION` that cannot sink a restore: inside its own block, so a +/// target without the extension (or a role not allowed to add it) logs a +/// warning and the script goes on. CASCADE brings what it requires. +fn pg_create_extension_guarded(name: &str, schema: Option<&str>) -> String { + let in_schema = match schema { + Some(s) if s != "public" => format!("CREATE SCHEMA IF NOT EXISTS {}; ", qi(s)), + _ => String::new(), + }; + let with = schema.map(|s| format!(" WITH SCHEMA {}", qi(s))).unwrap_or_default(); + format!( + "DO $$ BEGIN {in_schema}CREATE EXTENSION IF NOT EXISTS {}{with} CASCADE; \ + EXCEPTION WHEN OTHERS THEN RAISE WARNING 'extension {} was not created: %', SQLERRM; END $$;\n", + qi(name), + name.replace('\'', "''"), + ) +} + /// Schema-qualified double-quoted name. fn qn(schema: &str, name: &str) -> String { format!("{}.{}", qi(schema), qi(name)) } /// Backtick identifier (MySQL). @@ -639,6 +657,10 @@ async fn export_into( ActiveConnection::LibSql(cfg) => export_d1(rep, Remote::LibSql(&cfg), tables.as_deref(), opts, out).await, ActiveConnection::Clickhouse(_) => Err("Backup export is not supported for ClickHouse connections".to_string()), ActiveConnection::Posthog(_) => Err("Backup is not supported for PostHog".to_string()), + c @ (ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_)) => { + let eng = SqlEngine::of(&c).ok_or("Not an API engine")?; + export_api_sql(rep, &eng, schema.as_deref(), tables.as_deref(), opts, out).await + } ActiveConnection::Redis(_) => Err("Backup is not supported on Redis".to_string()), ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Err("Backup is not supported on DynamoDB".to_string()), ActiveConnection::Duckdb(h) => export_duckdb(rep, &h, out).await, @@ -672,6 +694,10 @@ pub async fn backup_import( ActiveConnection::LibSql(cfg) => import_d1(&rep, Remote::LibSql(&cfg), &script).await, ActiveConnection::Clickhouse(_) => Err("Backup import is not supported for ClickHouse connections".to_string()), ActiveConnection::Posthog(_) => Err("Backup is not supported for PostHog".to_string()), + c @ (ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_)) => { + let eng = SqlEngine::of(&c).ok_or("Not an API engine")?; + import_api_sql(&rep, &eng, &script).await + } ActiveConnection::Redis(_) => Err("Backup is not supported on Redis".to_string()), ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Err("Backup is not supported on DynamoDB".to_string()), ActiveConnection::Duckdb(h) => import_duckdb(&rep, &h, &script).await, @@ -1525,6 +1551,28 @@ async fn export_postgres( } out.push('\n'); + // ── Extensions ── Before anything that uses them: a column defaulting to + // uuid_generate_v4() needs uuid-ossp, a geometry column needs PostGIS. + // Without these a restore into a fresh database (an RDS instance, say) + // failed on every such table and rolled back. Each is guarded, so one the + // target cannot install is a warning, not a failed restore; the objects + // the extension owns are left out below, since it brings them itself. + let res = sqlx::query_as::<_, (String, String)>( + "SELECT e.extname::text, n.nspname::text \ + FROM pg_catalog.pg_extension e \ + JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace \ + WHERE e.extname <> 'plpgsql' ORDER BY e.oid" + ) + .fetch_all(pool).await; + let exts = catalog_or_warn(res, rep, out, "extensions"); + if !exts.is_empty() { + out.push_str("-- Extensions\n"); + for (name, schema) in &exts { + out.push_str(&pg_create_extension_guarded(name, Some(schema))); + } + out.push('\n'); + } + // ── Catalog: one query per object kind for every schema at once. Per-table // lookups cost three round trips a table, which on a far host is seconds. let tables = pg_load_tables(pool, &schemas, table_filter).await?; @@ -1540,6 +1588,7 @@ async fn export_postgres( JOIN pg_catalog.pg_enum e ON e.enumtypid = t.oid \ JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace \ WHERE n.nspname = ANY($1) \ + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.classid = 'pg_catalog.pg_type'::regclass AND d.objid = t.oid AND d.deptype = 'e') \ GROUP BY n.nspname, t.typname ORDER BY 1, 2" ) .bind(&schemas).fetch_all(pool).await; @@ -1575,6 +1624,8 @@ async fn export_postgres( LEFT JOIN pg_catalog.pg_namespace dn ON dn.oid = dt.relnamespace LEFT JOIN pg_catalog.pg_attribute da ON da.attrelid = d.refobjid AND da.attnum = d.refobjsubid WHERE s.schemaname = ANY($1) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend xd + WHERE xd.classid = 'pg_catalog.pg_class'::regclass AND xd.objid = sc.oid AND xd.deptype = 'e') ORDER BY 1, 2 "#, ) @@ -1690,6 +1741,7 @@ async fn export_postgres( FROM pg_catalog.pg_class c \ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \ WHERE n.nspname = ANY($1) AND c.relkind = 'v' \ + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') \ ORDER BY 1, 2" ) .bind(&schemas).fetch_all(pool).await; @@ -1762,6 +1814,7 @@ async fn pg_load_tables(pool: &sqlx::PgPool, schemas: &[String], filter: Option< FROM pg_catalog.pg_class c \ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \ WHERE n.nspname = ANY($1) AND c.relkind = 'r' AND NOT c.relispartition \ + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') \ ORDER BY 1, 2" ) .bind(schemas).fetch_all(pool).await.map_err(|e| e.to_string())?; @@ -2019,6 +2072,77 @@ fn pg_batchable(low: &str) -> bool { && !(low.starts_with("create unique index concurrently")) } +/// What a script's DDL calls or declares, and the extension that provides it. +/// Matched against lowercased DDL only, never row data. +const SCRIPT_EXTENSIONS: &[(&str, &[&str])] = &[ + ("uuid-ossp", &["uuid_generate_v1", "uuid_generate_v3", "uuid_generate_v4", "uuid_generate_v5", "uuid_nil()"]), + ("pgcrypto", &["gen_salt(", "pgp_sym_encrypt", "pgp_sym_decrypt", "hmac("]), + ("citext", &[" citext", ".citext", "\"citext\""]), + ("hstore", &[" hstore", ".hstore", "\"hstore\""]), + ("postgis", &["geometry(", "geography(", ".geometry", ".geography", " geometry,", " geometry\n", " geometry not null", " geography,"]), + ("pg_trgm", &["gin_trgm_ops", "gist_trgm_ops"]), + ("vector", &[" vector(", ".vector(", "vector_cosine_ops", "vector_l2_ops", "vector_ip_ops"]), + ("ltree", &[" ltree", ".ltree"]), + ("unaccent", &["unaccent("]), +]; + +/// Most a script's head is scanned for DDL when it has no COPY block to stop at. +const EXT_SCAN_MAX: usize = 64 * 1024 * 1024; + +/// Extensions a backup relies on, created before it runs when the target +/// lacks them. +/// +/// A backup made before Stroke wrote extensions into its scripts (or by a +/// tool that leaves them out) restored into a fresh database - a new RDS +/// database, say - failed on every table defaulting to uuid_generate_v4(): +/// "function uuid_generate_v4() does not exist", 93 failures, rolled back. +/// The DDL says which extensions it needs, so this reads it (the part before +/// the first COPY block and after the last; the rows in between are never +/// scanned) and adds what is missing. Each in a savepoint: one the server or +/// the role will not allow is a warning naming the fix, and the restore goes +/// on to report the real failures. +async fn pg_ensure_script_extensions(conn: &mut sqlx::PgConnection, sql: &str, rep: &Reporter) { + let floor = |i: usize| { let mut i = i.min(sql.len()); while !sql.is_char_boundary(i) { i -= 1; } i }; + let head_end = sql.find("\nCOPY ").unwrap_or_else(|| floor(EXT_SCAN_MAX)); + let mut ddl = sql[..head_end].to_ascii_lowercase(); + if let Some(i) = sql.rfind("\n\\.\n") { + if i > head_end { + let start = floor(i.max(sql.len().saturating_sub(EXT_SCAN_MAX))); + ddl.push_str(&sql[start..].to_ascii_lowercase()); + } + } + let mut wanted: Vec<&str> = SCRIPT_EXTENSIONS + .iter() + .filter(|(_, needles)| needles.iter().any(|n| ddl.contains(n))) + .map(|(name, _)| *name) + .collect(); + // Built into Postgres 13 and later; from pgcrypto before that. + if ddl.contains("gen_random_uuid") { + let builtin: Option = sqlx::Executor::fetch_one(&mut *conn, "SELECT to_regproc('gen_random_uuid') IS NOT NULL") + .await.ok().and_then(|r| r.try_get::(0).ok()); + if builtin == Some(false) && !wanted.contains(&"pgcrypto") { wanted.push("pgcrypto"); } + } + for name in wanted { + // A name from SCRIPT_EXTENSIONS, quoted as a literal: no bind needed. + let probe = format!("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_extension WHERE extname = {})", ql(name)); + let have: Option = sqlx::Executor::fetch_one(&mut *conn, probe.as_str()) + .await.ok().and_then(|r| r.try_get::(0).ok()); + if have != Some(false) { continue; } + let create = format!("SAVEPOINT stroke_ext; CREATE EXTENSION IF NOT EXISTS {} CASCADE; RELEASE SAVEPOINT stroke_ext", qi(name)); + match sqlx::Executor::execute(&mut *conn, create.as_str()).await { + Ok(_) => rep.log("info", format!("Added the {name} extension, which this backup's tables use.")), + Err(e) => { + let _ = sqlx::Executor::execute(&mut *conn, "ROLLBACK TO SAVEPOINT stroke_ext; RELEASE SAVEPOINT stroke_ext").await; + let msg = e.to_string(); + let msg = msg.strip_prefix("error returned from database: ").unwrap_or(&msg); + rep.log("warn", format!( + "This backup uses the {name} extension, which could not be added ({msg}). An admin can run CREATE EXTENSION \"{name}\"; on the target, then restore again." + )); + } + } + } +} + async fn import_postgres(rep: &Reporter, pool: &sqlx::PgPool, sql: &str) -> Result { let started = Instant::now(); rep.log("info", "Starting restore…"); @@ -2036,6 +2160,7 @@ async fn import_postgres(rep: &Reporter, pool: &sqlx::PgPool, sql: &str) -> Resu { (&mut *conn).execute("ROLLBACK TO SAVEPOINT stroke_rr; RELEASE SAVEPOINT stroke_rr").await.ok(); } + pg_ensure_script_extensions(&mut conn, sql, rep).await; let mut run = Runner::new(rep, sql.len()); let mut sp = Splitter::new(sql, Escapes::Standard); @@ -2177,6 +2302,9 @@ async fn export_mysql( out.push_str(&backup_header("MySQL", schema_filter)); out.push_str("SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\nSET UNIQUE_CHECKS=0;\nSET AUTOCOMMIT=0;\n\n"); + // SHOW CREATE for views, routines and triggers on a connection with + // ANSI_QUOTES off, so the dump uses backticks (see backtick_conn). + let mut ddl_conn = super::mysql::backtick_conn(pool).await?; // Every table up front, for the progress plan. let mut by_schema: Vec<(String, Vec<(String, Option)>)> = Vec::new(); @@ -2238,7 +2366,7 @@ async fn export_mysql( if !view_names.is_empty() { out.push_str("-- Views\n"); for view in &view_names { - if let Ok(row) = sqlx::query(&format!("SHOW CREATE VIEW {}.{}", qb(schema), qb(view))).fetch_one(pool).await { + if let Ok(row) = sqlx::query(&format!("SHOW CREATE VIEW {}.{}", qb(schema), qb(view))).fetch_one(&mut ddl_conn).await { let create = super::mysql::my_text(&row, 1).unwrap_or_default(); out.push_str(&create.replacen("CREATE ", "CREATE OR REPLACE ", 1)); out.push_str(";\n"); @@ -2260,7 +2388,7 @@ async fn export_mysql( out.push_str("-- Functions & Procedures\nDELIMITER //\n"); for (name, rtype) in &routines { let keyword = if rtype == "FUNCTION" { "FUNCTION" } else { "PROCEDURE" }; - if let Ok(row) = sqlx::query(&format!("SHOW CREATE {keyword} {}.{}", qb(schema), qb(name))).fetch_one(pool).await { + if let Ok(row) = sqlx::query(&format!("SHOW CREATE {keyword} {}.{}", qb(schema), qb(name))).fetch_one(&mut ddl_conn).await { let create = super::mysql::my_text(&row, 2).unwrap_or_default(); out.push_str(&create); out.push_str("//\n\n"); @@ -2283,7 +2411,7 @@ async fn export_mysql( if !triggers.is_empty() { out.push_str("-- Triggers\nDELIMITER //\n"); for (trig, _) in &triggers { - if let Ok(row) = sqlx::query(&format!("SHOW CREATE TRIGGER {}.{}", qb(schema), qb(trig))).fetch_one(pool).await { + if let Ok(row) = sqlx::query(&format!("SHOW CREATE TRIGGER {}.{}", qb(schema), qb(trig))).fetch_one(&mut ddl_conn).await { let create = super::mysql::my_text(&row, 2).unwrap_or_default(); out.push_str(&create); out.push_str("//\n\n"); @@ -2380,8 +2508,10 @@ async fn my_dump_table( let mut conn = pool.acquire().await.map_err(|e| e.to_string())?; if opts.include_schema { + // Backticks, whatever the pool's ANSI_QUOTES (see backtick_conn). + let mut ddl = super::mysql::backtick_conn(pool).await?; let row = sqlx::query(&format!("SHOW CREATE TABLE {}.{}", qb(schema), qb(table))) - .fetch_one(&mut *conn).await + .fetch_one(&mut ddl).await .map_err(|e| format!("SHOW CREATE TABLE failed: {e}"))?; let create_sql = super::mysql::my_text(&row, 1).unwrap_or_default(); chunk.put_str(&create_sql.replacen("CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ", 1)); @@ -2924,10 +3054,577 @@ async fn import_mssql( Ok(finish_import(rep, run.total, run.ok, run.errors, started)) } +// ── Spanner, BigQuery, Snowflake and ODBC ────────────────────────────────── +// +// These answer over an API or a driver rather than a wire protocol with a dump +// tool, so the backup is built from what every driver already has: the table +// list, each table's own DDL, and its rows read page by page through the grid's +// reader (for BigQuery that is tabledata.list, which runs no query and bills +// nothing). Rows are written as INSERTs in the engine's own literal syntax, and +// a restore runs the script back statement by statement through the driver. + +/// How an engine writes a literal. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum LitStyle { + /// Standard SQL: '' inside strings. + Ansi, + /// Standard SQL, but 1 and 0 for booleans (SQL Server, Oracle, Sybase ...). + AnsiNumericBool, + /// GoogleSQL (Spanner, BigQuery): backslash escapes, typed JSON and arrays. + GoogleSql, + /// Snowflake: semi-structured values through PARSE_JSON. + Snowflake, + /// MySQL and MariaDB through ODBC: a backslash in a string is an escape. + MySql, +} + +pub(crate) enum SqlEngine { + Spanner(super::spanner::SpannerHandle), + Bigquery(super::bigquery::BigQueryHandle), + Snowflake(super::snowflake::SnowflakeHandle), + Odbc(super::odbc::OdbcHandle), +} + +impl SqlEngine { + pub(crate) fn of(conn: &ActiveConnection) -> Option { + Some(match conn { + ActiveConnection::Spanner(h) => Self::Spanner(h.clone()), + ActiveConnection::Bigquery(h) => Self::Bigquery(h.clone()), + ActiveConnection::Snowflake(h) => Self::Snowflake(h.clone()), + ActiveConnection::Odbc(h) => Self::Odbc(h.clone()), + _ => return None, + }) + } + + pub(crate) fn label(&self) -> String { + match self { + Self::Spanner(_) => "Spanner".into(), + Self::Bigquery(_) => "BigQuery".into(), + Self::Snowflake(_) => "Snowflake".into(), + Self::Odbc(h) => format!("ODBC ({})", h.info.dbms), + } + } + + pub(crate) fn style(&self) -> LitStyle { + match self { + Self::Spanner(h) if h.dialect == super::spanner::Dialect::Postgres => LitStyle::Ansi, + Self::Spanner(_) | Self::Bigquery(_) => LitStyle::GoogleSql, + Self::Snowflake(_) => LitStyle::Snowflake, + Self::Odbc(h) => { + let d = h.info.dbms.to_ascii_lowercase(); + if d.contains("mysql") || d.contains("mariadb") { + return LitStyle::MySql; + } + if ["sql server", "oracle", "sybase", "adaptive server", "informix", "teradata", "access"].iter().any(|w| d.contains(w)) { + LitStyle::AnsiNumericBool + } else { + LitStyle::Ansi + } + } + } + } + + pub(crate) fn quote(&self, id: &str) -> String { + match self { + Self::Spanner(h) => super::spanner::quote_ident(h, id), + Self::Bigquery(_) => qb(id), + Self::Snowflake(_) => super::snowflake::quote(id), + Self::Odbc(h) => super::odbc::quote(&h.info, id), + } + } + + /// The table as a restore writes it: without the project or database, so + /// the script loads into whichever one it is run against. + pub(crate) fn table_ref(&self, schema: &str, table: &str) -> String { + match self { + Self::Spanner(h) => super::spanner::table_ref(h, schema, table), + Self::Bigquery(_) => format!("{}.{}", qb(schema), qb(table)), + Self::Snowflake(_) => format!("{}.{}", super::snowflake::quote(schema), super::snowflake::quote(table)), + Self::Odbc(h) => super::odbc::table_ref(&h.info, schema, table), + } + } + + pub(crate) async fn schemas(&self) -> Result, String> { + match self { + Self::Spanner(h) => super::spanner::list_schemas(h).await, + Self::Bigquery(h) => super::bigquery::list_schemas(h).await, + Self::Snowflake(h) => super::snowflake::list_schemas(h).await, + Self::Odbc(h) => super::odbc::list_schemas(h).await, + } + } + + async fn tables(&self, schema: &str) -> Result, String> { + match self { + Self::Spanner(h) => super::spanner::list_tables(h, schema).await, + Self::Bigquery(h) => super::bigquery::list_tables(h, schema).await, + Self::Snowflake(h) => super::snowflake::list_tables(h, schema).await, + Self::Odbc(h) => super::odbc::list_tables(h, schema).await, + } + } + + pub(crate) async fn columns(&self, schema: &str, table: &str) -> Result, String> { + match self { + Self::Spanner(h) => super::spanner::get_column_structure(h, schema, table).await, + Self::Bigquery(h) => super::bigquery::get_column_structure(h, schema, table).await, + Self::Snowflake(h) => super::snowflake::get_column_structure(h, schema, table).await, + Self::Odbc(h) => super::odbc::get_column_structure(h, schema, table).await, + } + } + + async fn ddl(&self, schema: &str, table: &str) -> Result { + let ddl = match self { + Self::Spanner(h) => super::spanner::get_ddl(h, schema, table).await?, + Self::Bigquery(h) => { + // INFORMATION_SCHEMA writes `project.dataset.table`: drop the + // project so the script restores into any project. + let p = h.project_id.trim(); + super::bigquery::get_ddl(h, schema, table).await?.replace(&format!("`{p}`."), "").replace(&format!("`{p}."), "`") + } + Self::Snowflake(h) => super::snowflake::get_ddl(h, schema, table).await?, + Self::Odbc(h) => super::odbc::get_ddl(h, schema, table).await?, + }; + Ok(ddl) + } + + async fn page(&self, schema: &str, table: &str, limit: i64, offset: i64) -> Result { + match self { + Self::Spanner(h) => super::spanner::get_table_rows(h, schema, table, limit, offset, None, None, None, None).await, + Self::Bigquery(h) => super::bigquery::get_table_rows(h, schema, table, limit, offset, None, None, None, None).await, + Self::Snowflake(h) => super::snowflake::get_table_rows(h, schema, table, limit, offset, None, None, None, None).await, + Self::Odbc(h) => super::odbc::get_table_rows(h, schema, table, limit, offset, None, None, None, None).await, + } + } + + pub(crate) async fn exec(&self, sql: &str) -> Result<(), String> { + match self { + Self::Spanner(h) => super::spanner::query(h, sql).await.map(|_| ()), + Self::Bigquery(h) => super::bigquery::query(h, sql).await.map(|_| ()), + Self::Snowflake(h) => super::snowflake::query(h, sql).await.map(|_| ()), + Self::Odbc(h) => super::odbc::query(h, sql).await.map(|_| ()), + } + } + + /// Whether this engine's grid pages are ordered (by primary key, or by + /// BigQuery's storage order) so that reading page after page never skips + /// or repeats a row. + fn pages_are_stable(&self, has_key: bool) -> bool { + matches!(self, Self::Bigquery(_) | Self::Spanner(_)) || has_key + } +} + +fn base_type_of(ty: &str) -> String { + ty.trim().to_ascii_uppercase().split(['(', '<', ' ']).next().unwrap_or("").to_string() +} + +/// A string literal in the engine's syntax. +fn str_lit(s: &str, style: LitStyle) -> String { + match style { + LitStyle::GoogleSql => { + let mut out = String::with_capacity(s.len() + 2); + out.push('\''); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\'' => out.push_str("\\'"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } + out.push('\''); + out + } + LitStyle::Snowflake | LitStyle::MySql => format!("'{}'", s.replace('\\', "\\\\").replace('\'', "''")), + _ => ql(s), + } +} + +/// Field names of a `STRUCT` type, top level only. +fn struct_fields(ty: &str) -> Vec { + let Some(inner) = ty.trim().strip_prefix("STRUCT<").and_then(|r| r.strip_suffix('>')) else { return vec![] }; + let mut out = Vec::new(); + let mut depth = 0; + let mut cur = String::new(); + for c in inner.chars() { + match c { + '<' | '(' => { depth += 1; cur.push(c) } + '>' | ')' => { depth -= 1; cur.push(c) } + ',' if depth == 0 => { out.push(std::mem::take(&mut cur)) } + c => cur.push(c), + } + } + if !cur.trim().is_empty() { out.push(cur) } + out.into_iter().filter_map(|f| f.split_whitespace().next().map(String::from)).collect() +} + +fn is_text_type(base: &str) -> bool { + base.is_empty() || ["CHAR", "TEXT", "STRING", "CLOB", "NCHAR", "NVARCHAR", "VARCHAR", "NTEXT", "LONGVARCHAR", "CHARACTER", "VARIANT", "JSON"].iter().any(|t| base.contains(t)) +} + +fn is_number_type(base: &str) -> bool { + ["INT", "NUMBER", "NUMERIC", "DECIMAL", "FLOAT", "DOUBLE", "REAL", "BIGINT", "SMALLINT", "TINYINT"].iter().any(|t| base.contains(t)) + && !base.contains("INTERVAL") + && !base.contains("POINT") +} + +fn parse_bool(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "true" | "t" | "1" | "yes" | "y" => Some(true), + "false" | "f" | "0" | "no" | "n" => Some(false), + _ => None, + } +} + +/// A grid value as a literal for a column of type `ty`. +pub(crate) fn value_lit(v: &serde_json::Value, ty: &str, style: LitStyle) -> String { + use serde_json::Value; + let base = base_type_of(ty); + match v { + Value::Null => "NULL".into(), + Value::Bool(b) => match style { + LitStyle::AnsiNumericBool => if *b { "1" } else { "0" }.into(), + _ => if *b { "TRUE" } else { "FALSE" }.into(), + }, + Value::Number(n) => n.to_string(), + // Text into a typed column (a CSV cell, a grid's formatted timestamp): + // empty is NULL, numbers and booleans go in bare, and GoogleSQL dates + // and times as typed literals. BigQuery will not cast '123' into INT64. + Value::String(s) if s.is_empty() && !is_text_type(&base) => "NULL".into(), + Value::String(s) if is_number_type(&base) && s.trim().parse::().is_ok_and(f64::is_finite) && !(style == LitStyle::GoogleSql && matches!(base.as_str(), "NUMERIC" | "BIGNUMERIC")) => { + s.trim().to_string() + } + Value::String(s) if matches!(base.as_str(), "BOOL" | "BOOLEAN" | "BIT") && parse_bool(s).is_some() => { + value_lit(&Value::Bool(parse_bool(s).unwrap_or(false)), ty, style) + } + Value::String(s) if style == LitStyle::GoogleSql && matches!(base.as_str(), "DATE" | "DATETIME" | "TIMESTAMP" | "TIME") => { + format!("{base} {}", str_lit(s, style)) + } + Value::String(s) => match (style, base.as_str()) { + (LitStyle::GoogleSql, "BYTES") => format!("FROM_BASE64({})", str_lit(s, style)), + (LitStyle::GoogleSql, "JSON") => format!("JSON {}", str_lit(s, style)), + (LitStyle::GoogleSql, "NUMERIC" | "BIGNUMERIC") => format!("NUMERIC {}", str_lit(s, style)), + (LitStyle::Snowflake, "VARIANT" | "OBJECT" | "ARRAY") => format!("PARSE_JSON({})", str_lit(s, style)), + (LitStyle::Snowflake, "BINARY" | "VARBINARY") => format!("TO_BINARY({}, 'HEX')", str_lit(s, style)), + _ => str_lit(s, style), + }, + Value::Array(items) => match style { + LitStyle::GoogleSql => { + // ARRAY: the element type from inside the brackets. + let elem = ty.trim().strip_prefix("ARRAY<").and_then(|r| r.strip_suffix('>')).unwrap_or(""); + format!("[{}]", items.iter().map(|x| value_lit(x, elem, style)).collect::>().join(", ")) + } + LitStyle::Snowflake => format!("PARSE_JSON({})", str_lit(&v.to_string(), style)), + _ => str_lit(&v.to_string(), style), + }, + Value::Object(map) => match (style, base.as_str()) { + (LitStyle::GoogleSql, "STRUCT") => { + let names = struct_fields(ty); + let parts: Vec = map + .iter() + .enumerate() + .map(|(i, (_, x))| value_lit(x, "", style) + &names.get(i).map(|n| format!(" AS {}", qb(n))).unwrap_or_default()) + .collect(); + format!("STRUCT({})", parts.join(", ")) + } + (LitStyle::GoogleSql, _) => format!("JSON {}", str_lit(&v.to_string(), style)), + (LitStyle::Snowflake, _) => format!("PARSE_JSON({})", str_lit(&v.to_string(), style)), + _ => str_lit(&v.to_string(), style), + }, + } +} + +/// Rows written per INSERT statement: small enough for every engine's limits +/// (Spanner's mutations, BigQuery's statement size). +const API_BATCH_ROWS: usize = 200; +/// Rows read per page. +const API_PAGE_ROWS: i64 = 1000; + +/// One INSERT for a batch of rows. Snowflake takes PARSE_JSON only in a +/// SELECT, so it gets INSERT ... SELECT ... UNION ALL SELECT ... +pub(crate) fn insert_stmt(target: &str, cols: &str, rows: &[String], style: LitStyle) -> String { + if style == LitStyle::Snowflake { + let selects: Vec = rows.iter().map(|r| format!("SELECT {r}")).collect(); + format!("INSERT INTO {target} ({cols})\n{};\n", selects.join("\nUNION ALL ")) + } else { + let values: Vec = rows.iter().map(|r| format!("({r})")).collect(); + format!("INSERT INTO {target} ({cols}) VALUES\n{};\n", values.join(",\n")) + } +} + +async fn export_api_sql( + rep: &Reporter, + eng: &SqlEngine, + schema: Option<&str>, + filter: Option<&[String]>, + opts: &ExportOptions, + out: &mut Out, +) -> Result { + let label = eng.label(); + rep.log("info", format!("Starting {label} export…")); + let schema = match schema.map(str::trim).filter(|s| !s.is_empty()) { + Some(s) => s.to_string(), + None => eng.schemas().await?.into_iter().next().ok_or("This database has no schemas to export")?, + }; + out.push_str(&backup_header(&label, Some(&schema))); + let style = eng.style(); + let all = eng.tables(&schema).await?; + let in_filter = |t: &str| filter.map_or(true, |f| f.iter().any(|x| x == t)); + let tables: Vec<&super::schema::TableInfo> = all.iter().filter(|t| t.kind == "table" && in_filter(&t.name)).collect(); + let views: Vec<&super::schema::TableInfo> = all.iter().filter(|t| t.kind == "view" && in_filter(&t.name)).collect(); + rep.plan( + tables + .iter() + .map(|t| PlanEntry { schema: Some(schema.clone()), name: t.name.clone(), est_rows: (t.row_count >= 0).then_some(t.row_count) }) + .collect(), + ); + + let mut stats = Stats { tables: tables.len(), ..Stats::default() }; + for t in &tables { + if is_cancelled() { break; } + let name = &t.name; + rep.table(Some(&schema), name, "running", 0, None); + if opts.include_schema { + match eng.ddl(&schema, name).await { + Ok(ddl) if !ddl.trim().is_empty() => { + let ddl = ddl.trim(); + out.push_str(&format!("\n{ddl}{}\n", if ddl.ends_with(';') { "" } else { ";" })); + } + Ok(_) => out.push_str(&format!("\n-- No DDL available for {name}\n")), + Err(e) => { + out.push_str(&format!("\n-- ERROR reading the DDL of {name}: {e}\n")); + rep.log("warn", format!("{name}: no DDL ({e})")); + } + } + } + if !opts.include_data { + rep.table(Some(&schema), name, "done", 0, None); + continue; + } + let cols = match eng.columns(&schema, name).await { + Ok(c) => c, + Err(e) => { + out.push_str(&format!("-- ERROR exporting {name}: {e}\n")); + rep.table(Some(&schema), name, "error", 0, Some(e.clone())); + stats.failed += 1; + continue; + } + }; + let has_key = cols.iter().any(|c| c.is_primary_key); + if !eng.pages_are_stable(has_key) { + rep.log("warn", format!("{name} has no primary key: its rows are read in pages without a fixed order, so a table that changes during the backup may come out with rows missing or doubled")); + } + let target = eng.table_ref(&schema, name); + let col_list = cols.iter().map(|c| eng.quote(&c.name)).collect::>().join(", "); + let mut chunk = Chunk::new(); + let mut batch: Vec = Vec::new(); + let mut n = 0u64; + let mut offset = 0i64; + let mut failed: Option = None; + loop { + if is_cancelled() { break; } + let page = match eng.page(&schema, name, API_PAGE_ROWS, offset).await { + Ok(p) => p, + Err(e) => { failed = Some(e); break; } + }; + // The page's own columns, matched to the table's by name. + let idx: Vec> = cols.iter().map(|c| page.columns.iter().position(|pc| pc.name == c.name)).collect(); + let got = page.rows.len(); + for row in &page.rows { + let lits: Vec = cols + .iter() + .zip(&idx) + .map(|(c, i)| i.and_then(|i| row.get(i)).map_or("NULL".into(), |v| value_lit(v, &c.data_type, style))) + .collect(); + batch.push(lits.join(", ")); + if batch.len() >= API_BATCH_ROWS { + chunk.put_str(&insert_stmt(&target, &col_list, &batch, style)); + batch.clear(); + } + } + n += got as u64; + offset += got as i64; + rep.table(Some(&schema), name, "running", n, None); + if (got as i64) < API_PAGE_ROWS { break; } + } + if !batch.is_empty() { + chunk.put_str(&insert_stmt(&target, &col_list, &batch, style)); + } + out.append(chunk)?; + stats.rows += n as usize; + match failed { + Some(e) => { + out.push_str(&format!("-- ERROR exporting {name} after {n} rows: {e}\n")); + rep.table(Some(&schema), name, "error", n, Some(e.clone())); + rep.log("error", format!("{name}: {e}")); + stats.failed += 1; + } + None => rep.table(Some(&schema), name, "done", n, None), + } + } + if opts.include_views { + for v in &views { + if let Ok(ddl) = eng.ddl(&schema, &v.name).await { + let ddl = ddl.trim(); + if !ddl.is_empty() { + out.push_str(&format!("\n{ddl}{}\n", if ddl.ends_with(';') { "" } else { ";" })); + } + } + } + } + out.check()?; + Ok(stats) +} + +async fn import_api_sql(rep: &Reporter, eng: &SqlEngine, sql: &str) -> Result { + let started = Instant::now(); + rep.log("info", format!("Starting {} restore…", eng.label())); + // GoogleSQL, Snowflake and MySQL read a backslash in a string as an escape. + let esc = if matches!(eng.style(), LitStyle::GoogleSql | LitStyle::Snowflake | LitStyle::MySql) { Escapes::Backslash } else { Escapes::Standard }; + let mut run = Runner::new(rep, sql.len()); + let mut sp = Splitter::new(sql, esc); + while let Some(stmt) = sp.next() { + let Stmt::Sql(s) = stmt else { continue }; + run.total += 1; + match eng.exec(&s).await { + Ok(()) => run.ok += 1, + Err(e) => run.fail(stmt_error(e, &s)), + } + run.meter.tick(sp.position(), run.ok, run.errors.len(), false); + if is_cancelled() { run.total += sp.count(); break; } + } + Ok(finish_import(rep, run.total, run.ok, run.errors, started)) +} + // ── Tests ─────────────────────────────────────────────────────────────────── #[cfg(test)] mod tests { + // ── Spanner, BigQuery, Snowflake and ODBC ──────────────────────────────── + + #[test] + fn api_literals_follow_each_dialect() { + use serde_json::json; + assert_eq!(value_lit(&json!("it's \\ \n"), "STRING", LitStyle::GoogleSql), "'it\\'s \\\\ \\n'"); + assert_eq!(value_lit(&json!("it's"), "VARCHAR", LitStyle::Ansi), "'it''s'"); + assert_eq!(value_lit(&json!("a\\b'c"), "VARCHAR", LitStyle::MySql), "'a\\\\b''c'"); + assert_eq!(value_lit(&json!(true), "BIT", LitStyle::AnsiNumericBool), "1"); + assert_eq!(value_lit(&json!(["a", "b"]), "ARRAY", LitStyle::GoogleSql), "['a', 'b']"); + assert_eq!(value_lit(&json!({ "a": 1, "b": "x" }), "STRUCT", LitStyle::GoogleSql), "STRUCT(1 AS `a`, 'x' AS `b`)"); + assert_eq!(value_lit(&json!({ "k": 1 }), "JSON", LitStyle::GoogleSql), "JSON '{\"k\":1}'"); + assert_eq!(value_lit(&json!("aGk="), "BYTES", LitStyle::GoogleSql), "FROM_BASE64('aGk=')"); + assert_eq!(value_lit(&json!({ "k": 1 }), "VARIANT", LitStyle::Snowflake), "PARSE_JSON('{\"k\":1}')"); + assert_eq!(value_lit(&serde_json::Value::Null, "INT64", LitStyle::GoogleSql), "NULL"); + assert_eq!(value_lit(&json!("42"), "INT64", LitStyle::GoogleSql), "42"); + assert_eq!(value_lit(&json!(""), "INT64", LitStyle::GoogleSql), "NULL"); + assert_eq!(value_lit(&json!(""), "STRING", LitStyle::GoogleSql), "''"); + assert_eq!(value_lit(&json!("yes"), "BOOL", LitStyle::GoogleSql), "TRUE"); + assert_eq!(value_lit(&json!("2026-11-21"), "DATE", LitStyle::GoogleSql), "DATE '2026-11-21'"); + assert_eq!(value_lit(&json!("12.5"), "NUMERIC", LitStyle::GoogleSql), "NUMERIC '12.5'"); + assert_eq!(value_lit(&json!("abc"), "INT64", LitStyle::GoogleSql), "'abc'"); + assert_eq!(struct_fields("STRUCT, c ARRAY>"), vec!["a", "b", "c"]); + } + + #[test] + fn api_inserts_batch_rows() { + assert_eq!(insert_stmt("t", "a, b", &["1, 'x'".into(), "2, 'y'".into()], LitStyle::Ansi), "INSERT INTO t (a, b) VALUES\n(1, 'x'),\n(2, 'y');\n"); + assert_eq!( + insert_stmt("t", "a", &["PARSE_JSON('1')".into(), "PARSE_JSON('2')".into()], LitStyle::Snowflake), + "INSERT INTO t (a)\nSELECT PARSE_JSON('1')\nUNION ALL SELECT PARSE_JSON('2');\n" + ); + } + + /// Dump a table, drop it, restore the dump, and read it back: through a + /// real ODBC driver (STROKE_TEST_ODBC), the BigQuery emulator + /// (STROKE_TEST_BIGQUERY) and the Spanner emulator (STROKE_TEST_SPANNER). + #[tokio::test] + async fn live_api_engines_round_trip() { + use serde_json::json; + let tid = format!("stroke_bk_{}", std::process::id()); + if let Ok(cs) = std::env::var("STROKE_TEST_ODBC") { + let cfg = super::super::odbc::OdbcConfig { name: "t".into(), preset: None, dsn: None, connection_string: Some(cs), user: None, password: None, ssh: None, target_host: None, target_port: None }; + let h = super::super::odbc::connect(&cfg).await.unwrap(); + let schema = match h.info.namespace { + super::super::odbc::Namespace::Schema => "public".to_string(), + super::super::odbc::Namespace::Catalog => h.info.catalog.clone(), + super::super::odbc::Namespace::Flat => super::super::odbc::FLAT_SCHEMA.to_string(), + }; + let tref = super::super::odbc::table_ref(&h.info, &schema, &tid); + super::super::odbc::query(&h, &format!("CREATE TABLE {tref} (id INTEGER NOT NULL PRIMARY KEY, label VARCHAR(40), ok BOOLEAN)")).await.unwrap(); + super::super::odbc::query(&h, &format!("INSERT INTO {tref} VALUES (1, 'it''s a \\ test', TRUE), (2, NULL, FALSE)")).await.unwrap(); + let eng = SqlEngine::Odbc(h.clone()); + // What the database stored (MySQL reads `\ ` in a literal as an escape). + let before = super::super::odbc::query(&h, &format!("SELECT id, label, ok FROM {tref} ORDER BY id")).await.unwrap().rows; + let res = run_export(&Reporter::silent(), ActiveConnection::Odbc(h.clone()), Some(schema.clone()), Some(vec![tid.clone()]), &ExportOptions::default(), None).await.unwrap(); + assert_eq!(res.row_count, 2, "{}", res.sql); + super::super::odbc::query(&h, &format!("DROP TABLE {tref}")).await.unwrap(); + let r = import_api_sql(&Reporter::silent(), &eng, &res.sql).await.unwrap(); + assert!(r.errors.is_empty(), "{:?}\n{}", r.errors, res.sql); + let back = super::super::odbc::query(&h, &format!("SELECT id, label, ok FROM {tref} ORDER BY id")).await.unwrap(); + assert_eq!(back.rows, before); + assert!(back.rows[0][1].as_str().unwrap().starts_with("it's a")); + super::super::odbc::query(&h, &format!("DROP TABLE {tref}")).await.unwrap(); + } + if let Ok(spec) = std::env::var("STROKE_TEST_BIGQUERY") { + let mut parts = spec.splitn(3, '/'); + let (host, project, dataset) = (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = super::super::bigquery::BigQueryConfig { + name: "t".into(), project_id: project.into(), dataset: Some(dataset.into()), location: None, + auth: "emulator".into(), key_file: None, emulator_host: Some(host.into()), + }; + let h = super::super::bigquery::connect(&cfg).await.unwrap(); + super::super::bigquery::query(&h, &format!("CREATE TABLE {dataset}.{tid} (id INT64, label STRING, tags ARRAY, seen TIMESTAMP)")).await.unwrap(); + super::super::bigquery::query(&h, &format!("INSERT INTO {dataset}.{tid} (id, label, tags, seen) VALUES (1, 'it\\'s \\\\ x', ['a', 'b'], TIMESTAMP '2026-11-21 05:00:00 UTC'), (2, NULL, [], NULL)")).await.unwrap(); + let eng = SqlEngine::Bigquery(h.clone()); + let res = run_export(&Reporter::silent(), ActiveConnection::Bigquery(h.clone()), Some(dataset.into()), Some(vec![tid.clone()]), &ExportOptions::default(), None).await.unwrap(); + assert_eq!(res.row_count, 2, "{}", res.sql); + assert!(!res.sql.contains(&format!("`{project}`.")), "the dump names no project:\n{}", res.sql); + super::super::bigquery::query(&h, &format!("DROP TABLE {dataset}.{tid}")).await.unwrap(); + let r = import_api_sql(&Reporter::silent(), &eng, &res.sql).await.unwrap(); + assert!(r.errors.is_empty(), "{:?}\n{}", r.errors, res.sql); + let back = super::super::bigquery::query(&h, &format!("SELECT id, label, tags, seen FROM {dataset}.{tid} ORDER BY id")).await.unwrap(); + assert_eq!(back.rows.len(), 2); + assert_eq!(back.rows[0][1], json!("it's \\ x")); + assert_eq!(back.rows[0][2], json!(["a", "b"])); + assert_eq!(back.rows[0][3], json!("2026-11-21T05:00:00Z")); + // An import's rows: every value text, as a CSV gives them, typed + // by the table's columns (BigQuery won't cast '3' into INT64). + let cols = eng.columns(dataset, &tid).await.unwrap(); + let names = ["id", "label", "seen"]; + let types: Vec = names.iter().map(|n| cols.iter().find(|c| c.name == *n).unwrap().data_type.clone()).collect(); + let csv = [json!("3"), json!("from csv"), json!("2026-11-22 10:00:00")]; + let lits: Vec = csv.iter().zip(&types).map(|(v, t)| value_lit(v, t, eng.style())).collect(); + let target = eng.table_ref(dataset, &tid); + let cl = names.iter().map(|n| eng.quote(n)).collect::>().join(", "); + eng.exec(&insert_stmt(&target, &cl, &[lits.join(", ")], eng.style())).await.unwrap(); + let r = super::super::bigquery::query(&h, &format!("SELECT label, seen FROM {dataset}.{tid} WHERE id = 3")).await.unwrap(); + assert_eq!(r.rows[0], vec![json!("from csv"), json!("2026-11-22T10:00:00Z")]); + super::super::bigquery::query(&h, &format!("DROP TABLE {dataset}.{tid}")).await.unwrap(); + } + if let Ok(spec) = std::env::var("STROKE_TEST_SPANNER") { + let mut parts = spec.splitn(4, '/'); + let (host, project, instance, database) = (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = super::super::spanner::SpannerConfig { + name: "t".into(), project_id: project.into(), instance_id: instance.into(), database_id: database.into(), + auth: "emulator".into(), key_file: None, emulator_host: Some(host.into()), + }; + let h = super::super::spanner::connect(&cfg).await.unwrap(); + super::super::spanner::query(&h, &format!("CREATE TABLE {tid} (id INT64 NOT NULL, label STRING(MAX), tags ARRAY, ok BOOL) PRIMARY KEY (id)")).await.unwrap(); + super::super::spanner::query(&h, &format!("INSERT INTO {tid} (id, label, tags, ok) VALUES (1, 'it\\'s', ['x'], TRUE), (2, NULL, NULL, FALSE)")).await.unwrap(); + let eng = SqlEngine::Spanner(h.clone()); + let res = run_export(&Reporter::silent(), ActiveConnection::Spanner(h.clone()), Some("default".into()), Some(vec![tid.clone()]), &ExportOptions::default(), None).await.unwrap(); + assert_eq!(res.row_count, 2, "{}", res.sql); + super::super::spanner::query(&h, &format!("DROP TABLE {tid}")).await.unwrap(); + let r = import_api_sql(&Reporter::silent(), &eng, &res.sql).await.unwrap(); + assert!(r.errors.is_empty(), "{:?}\n{}", r.errors, res.sql); + let back = super::super::spanner::query(&h, &format!("SELECT id, label, tags, ok FROM {tid} ORDER BY id")).await.unwrap(); + assert_eq!(back.rows[0][1], json!("it's")); + assert_eq!(back.rows[0][2], json!(["x"])); + assert_eq!(back.rows[1][3], json!(false)); + super::super::spanner::query(&h, &format!("DROP TABLE {tid}")).await.unwrap(); + } + } + use super::*; /// Most dialects we export to use standard string rules. @@ -3315,6 +4012,73 @@ mod tests { // // Each creates and drops its own databases (stroke_bk_*) on that server. + /// A database whose tables lean on extensions (uuid_generate_v4() defaults, + /// citext, PostGIS) restores into a fresh database: the dump creates its + /// extensions and leaves out what they own, and an older dump without them + /// gets them added from its DDL before it runs. + #[tokio::test(flavor = "multi_thread")] + #[ignore] + async fn live_postgres_restore_brings_its_extensions() { + let Ok(base) = std::env::var("STROKE_TEST_PG_URL") else { return }; + let admin = sqlx::PgPool::connect(&format!("{base}/postgres")).await.unwrap(); + for db in ["stroke_bk_ext_src", "stroke_bk_ext_dst", "stroke_bk_ext_old"] { + sqlx::query(&format!("DROP DATABASE IF EXISTS {db} WITH (FORCE)")).execute(&admin).await.unwrap(); + sqlx::query(&format!("CREATE DATABASE {db}")).execute(&admin).await.unwrap(); + } + let src = sqlx::postgres::PgPoolOptions::new().max_connections(4).connect(&format!("{base}/stroke_bk_ext_src")).await.unwrap(); + let postgis: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_available_extensions WHERE name = 'postgis')").fetch_one(&src).await.unwrap(); + sqlx::raw_sql( + r#"CREATE EXTENSION "uuid-ossp"; CREATE EXTENSION citext; + CREATE TABLE job (id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), email citext NOT NULL); + INSERT INTO job (email) SELECT 'U' || g || '@x.io' FROM generate_series(1, 25) g;"#, + ).execute(&src).await.unwrap(); + if postgis { + sqlx::raw_sql( + "CREATE EXTENSION postgis; + CREATE TABLE place (id serial PRIMARY KEY, geom geometry(Point, 4326)); + INSERT INTO place (geom) SELECT ST_SetSRID(ST_MakePoint(g, g), 4326) FROM generate_series(1, 5) g;", + ).execute(&src).await.unwrap(); + } + + let rep = Reporter::silent(); + let mut out = Out::memory(); + export_postgres(&rep, &src, Some("public"), None, &ExportOptions::default(), &mut out).await.unwrap(); + let dump = String::from_utf8(out.finish().unwrap().0).unwrap(); + assert!(dump.contains(r#"CREATE EXTENSION IF NOT EXISTS "uuid-ossp""#), "no uuid-ossp in dump"); + assert!(dump.contains(r#"CREATE EXTENSION IF NOT EXISTS "citext""#), "no citext in dump"); + if postgis { + assert!(!dump.contains("spatial_ref_sys"), "an extension's own table was dumped"); + assert!(!dump.contains("geometry_columns"), "an extension's own view was dumped"); + } + + // A new dump restores as is. + let dst = sqlx::postgres::PgPoolOptions::new().max_connections(4).connect(&format!("{base}/stroke_bk_ext_dst")).await.unwrap(); + let res = import_postgres(&rep, &dst, &dump).await.unwrap(); + assert!(res.errors.is_empty(), "restore errors: {:?}", res.errors); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM job WHERE email = 'u7@X.IO'").fetch_one(&dst).await.unwrap(); + assert_eq!(n, 1, "citext lost its case-insensitivity"); + sqlx::query("INSERT INTO job (email) VALUES ('new@x.io')").execute(&dst).await.unwrap(); + if postgis { + let p: i64 = sqlx::query_scalar("SELECT count(*) FROM place WHERE ST_X(geom) > 2").fetch_one(&dst).await.unwrap(); + assert_eq!(p, 3); + } + + // An older dump, made before extensions were written into it. + let old: String = dump.lines().filter(|l| !l.contains("CREATE EXTENSION")).collect::>().join("\n"); + let dst_old = sqlx::postgres::PgPoolOptions::new().max_connections(4).connect(&format!("{base}/stroke_bk_ext_old")).await.unwrap(); + let res = import_postgres(&rep, &dst_old, &old).await.unwrap(); + assert!(res.errors.is_empty(), "old dump restore errors: {:?}", res.errors); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM job").fetch_one(&dst_old).await.unwrap(); + assert_eq!(n, 25); + + src.close().await; + dst.close().await; + dst_old.close().await; + for db in ["stroke_bk_ext_src", "stroke_bk_ext_dst", "stroke_bk_ext_old"] { + sqlx::query(&format!("DROP DATABASE IF EXISTS {db} WITH (FORCE)")).execute(&admin).await.ok(); + } + } + #[tokio::test(flavor = "multi_thread")] #[ignore] async fn live_postgres_dump_restores_with_its_foreign_keys() { @@ -3429,6 +4193,37 @@ mod tests { } } + /// The app's MySQL pool runs with ANSI_QUOTES (connection.rs), which made + /// SHOW CREATE write double quotes into the dump, and the mysql client then + /// rejected CREATE TABLE "t". The dump's DDL must use backticks regardless. + #[tokio::test(flavor = "multi_thread")] + async fn live_mysql_dump_ddl_uses_backticks_under_ansi_quotes() { + let Ok(base) = std::env::var("STROKE_TEST_MYSQL_URL") else { return }; + let base = base.trim_end_matches('/').rsplit_once('/').map(|(b, _)| b.to_string()).unwrap_or(base); + let admin = sqlx::mysql::MySqlPoolOptions::new().max_connections(1).connect(&base).await.unwrap(); + sqlx::query("DROP DATABASE IF EXISTS stroke_bk_ansi").execute(&admin).await.unwrap(); + sqlx::query("CREATE DATABASE stroke_bk_ansi").execute(&admin).await.unwrap(); + let pool = sqlx::mysql::MySqlPoolOptions::new() + .max_connections(3) + .after_connect(|conn, _| Box::pin(async move { + sqlx::query("SET sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')").execute(&mut *conn).await?; + Ok(()) + })) + .connect(&format!("{base}/stroke_bk_ansi")).await.unwrap(); + sqlx::raw_sql("CREATE TABLE t_ansi (id INT PRIMARY KEY, note VARCHAR(20)); CREATE VIEW v_ansi AS SELECT id FROM t_ansi;") + .execute(&pool).await.unwrap(); + let mut out = Out::memory(); + export_mysql(&Reporter::silent(), &pool, Some("stroke_bk_ansi"), None, &ExportOptions::default(), &mut out).await.unwrap(); + let dump = String::from_utf8(out.finish().unwrap().0).unwrap(); + assert!(dump.contains("CREATE TABLE IF NOT EXISTS `t_ansi`"), "{dump}"); + assert!(!dump.contains("\"t_ansi\"") && !dump.contains("\"note\""), "double quotes in the dump:\n{dump}"); + // The pool itself kept ANSI_QUOTES: the changed mode stayed on the detached connection. + let mode: String = sqlx::query_scalar("SELECT @@SESSION.sql_mode").fetch_one(&pool).await.unwrap(); + assert!(mode.contains("ANSI_QUOTES"), "{mode}"); + pool.close().await; + sqlx::query("DROP DATABASE IF EXISTS stroke_bk_ansi").execute(&admin).await.ok(); + } + // ── Benchmark (ignored) ─────────────────────────────────────────────────── // // STROKE_BENCH_DIR= diff --git a/src-tauri/src/db/bigquery.rs b/src-tauri/src/db/bigquery.rs new file mode 100644 index 00000000..f11eae90 --- /dev/null +++ b/src-tauri/src/db/bigquery.rs @@ -0,0 +1,1256 @@ +//! Google BigQuery over its REST API (v2). Beta. +//! +//! Sign-in comes from `google_auth`: a service account key, the gcloud login, +//! or a local emulator (no auth). +//! +//! BigQuery bills by bytes scanned, so the app is careful with what it runs: +//! +//! - Browsing a table with no filter, search or sort reads it through +//! `tabledata.list`, which is free. A `SELECT * ... LIMIT` would scan (and +//! bill) every column of the whole table to show fifty rows. +//! - Row counts come from table metadata, also free. +//! - Plans are dry runs: they say how many bytes the query would read +//! without running it. +//! +//! Every query is a job with an id made here, so Stop can cancel it on the +//! server (`jobs.cancel`) rather than leave it running and billing. +//! +//! Datasets are the schemas. Tables have no row identity in BigQuery, so the +//! grid edits rows only where the table declares a primary key (BigQuery keeps +//! it unenforced, as metadata); without one, edits go through the SQL console. + +use super::query::{ColumnInfo, ForeignKeyInfo, RowFilter, SqlResult, TableRows}; +use super::schema::{ColumnStructureRow, TableInfo}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BigQueryConfig { + pub name: String, + /// The project queries run (and bill) in, and whose datasets are listed. + pub project_id: String, + /// The dataset an unqualified table name means in the SQL console. + #[serde(default)] + pub dataset: Option, + /// Where jobs run (`US`, `EU`, `europe-west2`, ...). BigQuery picks it + /// from the tables when blank. + #[serde(default)] + pub location: Option, + /// "serviceAccount", "gcloud" or "emulator". + #[serde(default = "default_auth")] + pub auth: String, + #[serde(default)] + pub key_file: Option, + /// The emulator's REST address, `localhost:9050` when blank. + #[serde(default)] + pub emulator_host: Option, +} + +fn default_auth() -> String { + "gcloud".into() +} + +pub type BigQueryHandle = Arc; + +/// Rows one console statement returns when it does not stream. +const MAX_ROWS: usize = 100_000; +/// Rows per `getQueryResults` page. +const PAGE_ROWS: usize = 10_000; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .timeout(Duration::from_secs(300)) + .connect_timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default() + }) +} + +fn opt(s: &Option) -> Option<&str> { + s.as_deref().map(str::trim).filter(|s| !s.is_empty()) +} + +fn base_url(cfg: &BigQueryConfig) -> String { + if cfg.auth == "emulator" { + let h = opt(&cfg.emulator_host).unwrap_or("localhost:9050").trim_end_matches('/'); + if h.contains("://") { format!("{h}/bigquery/v2") } else { format!("http://{h}/bigquery/v2") } + } else { + "https://bigquery.googleapis.com/bigquery/v2".into() + } +} + +fn project(cfg: &BigQueryConfig) -> &str { + cfg.project_id.trim() +} + +/// One REST call. `path` is relative to `/bigquery/v2/projects/{project}`. +async fn call(cfg: &BigQueryConfig, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result { + let url = format!( + "{}/projects/{}/{}", + base_url(cfg), + urlencoding::encode(project(cfg)), + path.trim_start_matches('/') + ); + let token = super::google_auth::token(&cfg.auth, cfg.key_file.as_deref(), super::google_auth::SCOPE_CLOUD_PLATFORM).await?; + let build = || { + let mut req = client().request(method.clone(), &url).bearer_auth(&token); + if let Some(b) = body { + req = req.json(b); + } + req + }; + // One retry when the request never got an answer (a dropped keep-alive + // connection). Safe: reads are reads, and a job insert carries its own id, + // so a second one is refused as a duplicate rather than run twice. + let sent = match build().send().await { + Err(e) if e.is_request() || e.is_connect() => { + tokio::time::sleep(Duration::from_millis(150)).await; + build().send().await + } + other => other, + }; + let resp = sent.map_err(|e| { + if e.is_connect() && cfg.auth == "emulator" { + format!("Could not reach the BigQuery emulator at {}: is it running?", base_url(cfg)) + } else { + format!("BigQuery request failed: {e}") + } + })?; + let status = resp.status(); + let text = resp.text().await.map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if !status.is_success() || v.get("error").is_some() { + return Err(error_text(status.as_u16(), &v, &text)); + } + Ok(v) +} + +fn error_text(status: u16, v: &Value, raw: &str) -> String { + let e = v.get("error").unwrap_or(v); + let msg = e.get("message").and_then(|m| m.as_str()).unwrap_or(""); + if msg.is_empty() { + let raw = raw.trim(); + return if raw.is_empty() { + format!("BigQuery answered HTTP {status}") + } else { + format!("BigQuery answered HTTP {status}: {}", raw.chars().take(300).collect::()) + }; + } + match status { + 401 => format!("BigQuery refused the credentials: {msg}"), + 403 => format!("No permission: {msg}"), + 404 => format!("Not found: {msg}"), + _ => msg.to_string(), + } +} + +/// Connect: the project answers and lists its datasets. +pub async fn connect(cfg: &BigQueryConfig) -> Result { + if project(cfg).is_empty() { + return Err("Enter the Google Cloud project ID".into()); + } + call(cfg, reqwest::Method::GET, "datasets?maxResults=1", None).await?; + Ok(Arc::new(cfg.clone())) +} + +pub async fn ping(h: &BigQueryConfig) -> Result<(), String> { + call(h, reqwest::Method::GET, "datasets?maxResults=1", None).await.map(|_| ()) +} + +// ── Values ──────────────────────────────────────────────────────────────────── + +/// BigQuery's legacy type names (what the REST API sends) as GoogleSQL's. +fn standard_type(t: &str) -> String { + match t.to_ascii_uppercase().as_str() { + "INTEGER" => "INT64".into(), + "FLOAT" => "FLOAT64".into(), + "BOOLEAN" => "BOOL".into(), + "RECORD" => "STRUCT".into(), + other => other.to_string(), + } +} + +/// A schema field's type as GoogleSQL writes it: `ARRAY`, +/// `STRUCT`. +fn type_label(f: &Value) -> String { + let base = standard_type(f.get("type").and_then(|t| t.as_str()).unwrap_or("STRING")); + let inner = if base == "STRUCT" { + let parts: Vec = f["fields"] + .as_array() + .into_iter() + .flatten() + .map(|sub| format!("{} {}", sub["name"].as_str().unwrap_or(""), type_label(sub))) + .collect(); + format!("STRUCT<{}>", parts.join(", ")) + } else { + base + }; + if f.get("mode").and_then(|m| m.as_str()) == Some("REPEATED") { + format!("ARRAY<{inner}>") + } else { + inner + } +} + +/// A TIMESTAMP cell: microseconds since the epoch (`useInt64Timestamp`), or +/// seconds as a float (what an emulator sends), as RFC 3339 in UTC. +fn timestamp(s: &str) -> Option { + let micros = if s.contains(['.', 'e', 'E']) { + (s.parse::().ok()? * 1_000_000.0).round() as i64 + } else { + s.parse::().ok()? + }; + let dt = chrono::DateTime::from_timestamp_micros(micros)?; + Some(dt.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)) +} + +/// One cell (`{"v": ...}`'s value) as the grid shows it. +fn cell(f: &Value, v: Value) -> Value { + if v.is_null() { + return v; + } + if f.get("mode").and_then(|m| m.as_str()) == Some("REPEATED") { + let mut one = f.clone(); + if let Some(o) = one.as_object_mut() { + o.insert("mode".into(), json!("NULLABLE")); + } + return match v { + Value::Array(items) => Value::Array(items.into_iter().map(|x| cell(&one, x.get("v").cloned().unwrap_or(Value::Null))).collect()), + other => other, + }; + } + let ty = standard_type(f.get("type").and_then(|t| t.as_str()).unwrap_or("")); + match ty.as_str() { + "STRUCT" => { + let subs = f["fields"].as_array().cloned().unwrap_or_default(); + let vals = v["f"].as_array().cloned().unwrap_or_default(); + let mut out = serde_json::Map::new(); + for (sub, val) in subs.iter().zip(vals) { + let name = sub["name"].as_str().unwrap_or("").to_string(); + out.insert(name, cell(sub, val.get("v").cloned().unwrap_or(Value::Null))); + } + Value::Object(out) + } + "INT64" => match v.as_str().and_then(|s| s.parse::().ok()) { + Some(n) if n.unsigned_abs() <= (1u64 << 53) => json!(n), + _ => v, + }, + "FLOAT64" => match v.as_str().and_then(|s| s.parse::().ok()) { + Some(x) if x.is_finite() => json!(x), + _ => v, + }, + "BOOL" => match v.as_str() { + Some("true") => json!(true), + Some("false") => json!(false), + _ => v, + }, + "TIMESTAMP" => v.as_str().and_then(timestamp).map(Value::String).unwrap_or(v), + "JSON" => v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(v), + _ => v, + } +} + +fn columns_of(fields: &[Value]) -> Vec { + fields + .iter() + .enumerate() + .map(|(i, f)| { + let name = f["name"].as_str().filter(|n| !n.is_empty()).map(String::from).unwrap_or_else(|| format!("f{i}_")); + ColumnInfo::new(name, type_label(f)) + }) + .collect() +} + +fn row_values(fields: &[Value], row: &Value) -> Vec { + row["f"] + .as_array() + .map(|cells| { + cells + .iter() + .zip(fields.iter()) + .map(|(c, f)| super::sql_util::cap_json_value("text", cell(f, c.get("v").cloned().unwrap_or(Value::Null)))) + .collect() + }) + .unwrap_or_default() +} + +fn plural(n: i64) -> &'static str { + if n == 1 { "" } else { "s" } +} + +// ── Jobs ────────────────────────────────────────────────────────────────────── + +/// A query job this app started: its id and where it runs. +#[derive(Debug, Clone)] +struct Job { + id: String, + location: Option, +} + +fn fresh_job_id() -> String { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + format!( + "stroke_{:x}_{:x}_{:x}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ) +} + +/// One of this app's job ids (`stroke__"); + } + + #[test] + fn cells_come_back_as_the_grid_shows_them() { + assert_eq!(cell(&field("a", "INTEGER", "NULLABLE"), json!("42")), json!(42)); + assert_eq!(cell(&field("a", "INTEGER", "NULLABLE"), json!("9007199254740993")), json!("9007199254740993")); + assert_eq!(cell(&field("a", "FLOAT", "NULLABLE"), json!("9.5")), json!(9.5)); + assert_eq!(cell(&field("a", "BOOLEAN", "NULLABLE"), json!("false")), json!(false)); + assert_eq!(cell(&field("a", "TIMESTAMP", "NULLABLE"), json!("1795237200.000000")), json!("2026-11-21T05:00:00Z")); + assert_eq!(cell(&field("a", "TIMESTAMP", "NULLABLE"), json!("1795237200123456")), json!("2026-11-21T05:00:00.123456Z")); + assert_eq!(cell(&field("a", "STRING", "REPEATED"), json!([{ "v": "x" }, { "v": "y" }])), json!(["x", "y"])); + let rec = json!({ "name": "m", "type": "RECORD", "mode": "NULLABLE", + "fields": [field("a", "INTEGER", "NULLABLE"), field("b", "STRING", "NULLABLE")] }); + assert_eq!(cell(&rec, json!({ "f": [{ "v": "1" }, { "v": "x" }] })), json!({ "a": 1, "b": "x" })); + assert_eq!(cell(&field("a", "JSON", "NULLABLE"), json!("{\"k\":1}")), json!({ "k": 1 })); + assert_eq!(cell(&field("a", "STRING", "NULLABLE"), Value::Null), Value::Null); + } + + #[test] + fn grid_values_bind_as_typed_parameters() { + let mut p = Params::default(); + assert_eq!(eq("`id`", "INT64", &json!(7), &mut p).unwrap(), "`id` = @p1"); + assert_eq!(eq("`ok`", "BOOL", &json!("yes"), &mut p).unwrap(), "`ok` = @p2"); + assert_eq!(eq("`x`", "STRING", &Value::Null, &mut p).unwrap(), "`x` IS NULL"); + assert_eq!(p.0[0]["parameterType"]["type"], "INT64"); + assert_eq!(p.0[0]["parameterValue"]["value"], "7"); + assert_eq!(p.0[1]["parameterValue"]["value"], "true"); + assert!(param_text("ARRAY", &json!("x")).is_err()); + } + + #[test] + fn only_reads_count_as_reads() { + assert!(reads("SELECT 1")); + assert!(reads(" with t as (select 1) select * from t")); + assert!(!reads("DELETE FROM t WHERE true")); + assert!(!reads("CREATE TABLE t (a INT64)")); + } + + #[test] + fn job_ids_are_recognised() { + assert!(is_job_id(&fresh_job_id())); + assert!(!is_job_id("stroke_sales")); + assert!(!is_job_id("analytics")); + } + + #[test] + fn byte_counts_read_well() { + assert_eq!(bytes_label(10), "10 B"); + assert_eq!(bytes_label(1536), "1.5 KB"); + assert_eq!(bytes_label(5 * 1024 * 1024 * 1024), "5.0 GB"); + } + + /// Against the BigQuery emulator, when STROKE_TEST_BIGQUERY is + /// `host:port/project/dataset`, e.g. + /// `docker run -p 9050:9050 ghcr.io/goccy/bigquery-emulator --project=test --dataset=shop` + /// then `STROKE_TEST_BIGQUERY=localhost:9050/test/shop`. + #[tokio::test] + async fn live_emulator_round_trip() { + let Ok(spec) = std::env::var("STROKE_TEST_BIGQUERY") else { return }; + let mut parts = spec.splitn(3, '/'); + let (host, project, dataset) = (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = BigQueryConfig { + name: "t".into(), + project_id: project.into(), + dataset: Some(dataset.into()), + location: None, + auth: "emulator".into(), + key_file: None, + emulator_host: Some(host.into()), + }; + let h = connect(&cfg).await.unwrap(); + assert!(list_schemas(&h).await.unwrap().contains(&dataset.to_string())); + + // A table with a primary key, made over REST (constraints included). + let tid = format!("stroke_t_{}", std::process::id()); + let body = json!({ + "tableReference": { "projectId": project, "datasetId": dataset, "tableId": tid }, + "schema": { "fields": [ + { "name": "id", "type": "INTEGER", "mode": "REQUIRED" }, + { "name": "label", "type": "STRING" }, + { "name": "price", "type": "FLOAT" }, + { "name": "seen", "type": "TIMESTAMP" }, + { "name": "tags", "type": "STRING", "mode": "REPEATED" }, + ] }, + "tableConstraints": { "primaryKey": { "columns": ["id"] } }, + }); + call(&h, reqwest::Method::POST, &format!("datasets/{dataset}/tables"), Some(&body)).await.unwrap(); + query(&h, &format!("INSERT INTO {tid} (id, label, price, seen, tags) VALUES (1, 'pen', 2.5, TIMESTAMP '2026-11-21 05:00:00 UTC', ['a']), (2, 'cup', 4.0, NULL, [])")) + .await + .unwrap(); + + let tables = list_tables(&h, dataset).await.unwrap(); + assert!(tables.iter().any(|t| t.name == tid && t.kind == "table")); + let cols = get_column_structure(&h, dataset, &tid).await.unwrap(); + assert_eq!(cols[0].data_type, "INT64"); + assert!(cols[0].is_primary_key && !cols[0].is_nullable); + assert_eq!(cols[4].data_type, "ARRAY"); + + // Plain page: tabledata.list, no query. + let page = get_table_rows(&h, dataset, &tid, 1, 1, None, None, None, None).await.unwrap(); + assert_eq!(page.rows.len(), 1); + assert!(page.sql.contains("tabledata.list")); + assert_eq!(page.primary_key, vec!["id".to_string()]); + + // Filtered and sorted: a query with parameters. + let page = get_table_rows( + &h, dataset, &tid, 50, 0, None, Some("price".into()), Some("desc".into()), + Some(vec![RowFilter { column: "id".into(), op: ">=".into(), value: Some("1".into()), conjunct: None, data_type: None }]), + ) + .await + .unwrap(); + assert_eq!(page.total, 2); + assert_eq!(page.rows[0][1], json!("cup")); + assert_eq!(page.rows[1][3], json!("2026-11-21T05:00:00Z")); + assert_eq!(page.rows[1][4], json!(["a"])); + let page = get_table_rows(&h, dataset, &tid, 50, 0, Some("PEN".into()), None, None, None).await.unwrap(); + assert_eq!(page.rows.len(), 1); + + // Edits by primary key. + update_table_cell(&h, dataset, &tid, HashMap::from([("id".to_string(), json!(1))]), "label", &json!("pencil")).await.unwrap(); + update_table_cell(&h, dataset, &tid, HashMap::from([("id".to_string(), json!(2))]), "price", &Value::Null).await.unwrap(); + insert_table_row(&h, dataset, &tid, HashMap::from([("id".to_string(), json!(3)), ("label".to_string(), json!("ink"))])).await.unwrap(); + let r = query(&h, &format!("SELECT id, label, price FROM {tid} ORDER BY id")).await.unwrap(); + assert_eq!(r.rows.len(), 3); + assert_eq!(r.rows[0][1], json!("pencil")); + assert_eq!(r.rows[1][2], Value::Null); + delete_table_rows(&h, dataset, &tid, vec![HashMap::from([("id".to_string(), json!(3))])]).await.unwrap(); + let r = query(&h, &format!("SELECT COUNT(*) FROM {tid}")).await.unwrap(); + assert_eq!(r.rows[0][0], json!(2)); + + assert!(get_ddl(&h, dataset, &tid).await.unwrap().contains("PRIMARY KEY (`id`) NOT ENFORCED")); + let plan = explain_plan(&h, &format!("SELECT label FROM {tid}")).await.unwrap(); + assert!(plan["Node Type"].as_str().unwrap().contains("dry run"), "{plan}"); + assert!(explain_plan(&h, &format!("DELETE FROM {tid} WHERE true")).await.is_err()); + // Hidden and per-job datasets stay out of the schema list. + assert!(list_schemas(&h).await.unwrap().iter().all(|d| !is_job_id(d))); + assert!(query(&h, "SELECT nope FROM no_such_table").await.is_err()); + // Qualified: the emulator resolves DROP against the project, not the default dataset. + query(&h, &format!("DROP TABLE {dataset}.{tid}")).await.unwrap(); + assert!(!list_tables(&h, dataset).await.unwrap().iter().any(|t| t.name == tid)); + } +} diff --git a/src-tauri/src/db/cassandra.rs b/src-tauri/src/db/cassandra.rs index 089718eb..08c2c65d 100644 --- a/src-tauri/src/db/cassandra.rs +++ b/src-tauri/src/db/cassandra.rs @@ -31,6 +31,10 @@ pub struct CassandraConfig { /// Default keyspace for unqualified table names in the console. #[serde(default)] pub keyspace: Option, + /// Reach the server through an SSH tunnel (connection::tunnel_to and friends). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + } pub type CassandraHandle = Arc; @@ -535,7 +539,7 @@ mod tests { #[test] fn contact_points_default_port() { - let cfg = CassandraConfig { name: "t".into(), hosts: "a, b:9142 ,,10.0.0.1".into(), user: None, password: None, keyspace: None }; + let cfg = CassandraConfig { ssh: None, name: "t".into(), hosts: "a, b:9142 ,,10.0.0.1".into(), user: None, password: None, keyspace: None }; assert_eq!(contact_points(&cfg), ["a:9042", "b:9142", "10.0.0.1:9042"]); } @@ -553,7 +557,7 @@ mod tests { #[tokio::test] #[ignore] async fn cassandra_live() { - let cfg = CassandraConfig { name: "t".into(), hosts: "127.0.0.1".into(), user: None, password: None, keyspace: None }; + let cfg = CassandraConfig { ssh: None, name: "t".into(), hosts: "127.0.0.1".into(), user: None, password: None, keyspace: None }; let s = connect(&cfg).await.unwrap(); let tables = list_tables(&s).await.unwrap(); assert!(tables.iter().any(|t| t.starts_with("shop.")), "{tables:?}"); diff --git a/src-tauri/src/db/clickhouse.rs b/src-tauri/src/db/clickhouse.rs index 537581ab..d79b7926 100644 --- a/src-tauri/src/db/clickhouse.rs +++ b/src-tauri/src/db/clickhouse.rs @@ -12,9 +12,36 @@ use std::time::Instant; static CH_CLIENT: OnceLock = OnceLock::new(); +/// The HTTP client for a config. Through an SSH tunnel it resolves the +/// server's name to the tunnel's local end: the URL (and so TLS) keeps the real +/// name, and only the TCP connection goes to the tunnel. One per tunnel, kept. +fn client_for(config: &ClickhouseConfig) -> reqwest::Client { + static VIA: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + let Some(via) = config.via else { return client().clone() }; + let key = (config.host.clone(), via); + let mut map = VIA.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(c) = map.get(&key) { + return c.clone(); + } + let c = builder().resolve(&config.host, via).build().unwrap_or_else(|_| client().clone()); + map.insert(key, c.clone()); + c +} + +fn builder() -> reqwest::ClientBuilder { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .tcp_keepalive(std::time::Duration::from_secs(60)) + .pool_max_idle_per_host(10) + .pool_idle_timeout(std::time::Duration::from_secs(90)) + // Bounded, but generously: this carries queries, not just metadata. + .connect_timeout(std::time::Duration::from_secs(10)) + .timeout(std::time::Duration::from_secs(120)) +} + fn client() -> &'static reqwest::Client { CH_CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(10) .pool_idle_timeout(std::time::Duration::from_secs(90)) @@ -88,18 +115,223 @@ pub async fn query_in( query_in_with(config, database, sql, false).await } -/// `query` with ClickHouse's own `readonly=1` setting on the request: the -/// server itself refuses any write, DDL or settings change. For read-only -/// callers (the MCP server at "Read only"). +/// `query` with ClickHouse's own `readonly` setting on the request: the +/// server itself refuses any write or DDL. Level 2, which still lets the +/// request carry output settings (see DECIMAL_OUTPUT). For read-only callers +/// (the MCP server at "Read only"). pub async fn query_readonly(config: &ClickhouseConfig, sql: &str) -> Result { query_in_with(config, &config.database, sql, true).await } +/// `query`, stoppable. The request carries a query_id, and Stop asks the +/// server to `KILL QUERY` it: dropping the HTTP request alone leaves a write +/// (or any query, unless the server cancels on disconnect) running. +pub async fn query_cancellable( + config: &ClickhouseConfig, + sql: &str, + cancel: tokio::sync::oneshot::Receiver<()>, +) -> Result { + let id = fresh_query_id(); + let run = query_in_full(config, &config.database, sql, false, Some(&id)); + tokio::pin!(run); + tokio::select! { + r = &mut run => r, + _ = async { let _ = cancel.await; } => { + // Users may always kill their own queries. SYNC waits for it to end. + let kill = format!("KILL QUERY WHERE query_id = '{id}' SYNC"); + let _ = tokio::time::timeout(std::time::Duration::from_secs(10), query_in_full(config, &config.database, &kill, false, None)).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +fn fresh_query_id() -> String { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + format!( + "stroke-{:x}-{:x}-{:x}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ) +} + +/// Whether `stream_into` takes this statement (it returns rows). +pub(crate) fn reads(sql: &str) -> bool { + is_read_query(sql.trim().trim_end_matches(';')) +} + +/// A read, streamed into `sink` row by row as the server sends it. +/// +/// `FORMAT JSONCompact` is one JSON document, so a 2 GB result had to arrive +/// whole (and be parsed whole) before the grid saw a row. The EachRow format +/// sends one JSON array per line, after a line of names and one of types, so +/// rows reach the grid (or the result store) while the server is still +/// producing them and memory stays flat. Stop kills the query by id. +pub async fn stream_into( + config: &ClickhouseConfig, + sql: &str, + sink: &mut super::query::RowSink, + stop: &super::stop::Stop, +) -> Result { + let id = fresh_query_id(); + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(stream_rows(config, sql, sink, &id)); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + drop(run); + let kill = format!("KILL QUERY WHERE query_id = '{id}' SYNC"); + let _ = tokio::time::timeout(std::time::Duration::from_secs(10), query_in_full(config, &config.database, &kill, false, None)).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +async fn stream_rows( + config: &ClickhouseConfig, + sql: &str, + sink: &mut super::query::RowSink, + query_id: &str, +) -> Result { + use futures::StreamExt; + let trimmed = sql.trim().trim_end_matches(';'); + let url = format!( + "{}/?database={}&query_id={}{DECIMAL_OUTPUT}", + config.base_url(), + urlencoding::encode(&config.database), + urlencoding::encode(query_id) + ); + let t0 = Instant::now(); + let res = client_for(config) + .post(&url) + .header("X-ClickHouse-User", &config.user) + .header("X-ClickHouse-Key", &config.password) + .header("Content-Type", "text/plain; charset=utf-8") + .body(format!("{trimmed}\nFORMAT JSONCompactEachRowWithNamesAndTypes")) + .send() + .await + .map_err(|e| format!("ClickHouse request failed: {e}"))?; + if !res.status().is_success() { + let msg = res.text().await.unwrap_or_default(); + return Err(format!("ClickHouse error: {}", msg.trim().chars().take(500).collect::())); + } + + let mut lines = EachRowLines::default(); + let mut body = res.bytes_stream(); + while let Some(chunk) = body.next().await { + let chunk = chunk.map_err(|e| format!("ClickHouse response was cut off: {e}"))?; + for line in lines.feed(&chunk) { + lines.take(&line, sink)?; + } + } + if let Some(rest) = lines.rest() { + lines.take(&rest, sink)?; + } + if lines.rows > 0 { + sink.finish()?; + } + Ok(SqlResult { + columns: lines.columns(), + rows: vec![], + row_count: Some(lines.rows as i64), + message: None, + query_ms: t0.elapsed().as_millis() as u64, + sql: sql.to_string(), + }) +} + +/// The JSONCompactEachRowWithNamesAndTypes body, a line at a time: names, +/// types, then one JSON array per row. A line that is not JSON is the +/// server's own error text, which it writes into the body when a query fails +/// after the first rows went out. +#[derive(Default)] +struct EachRowLines { + pending: Vec, + names: Option>, + types: Option>, + rows: usize, +} + +impl EachRowLines { + fn feed(&mut self, chunk: &[u8]) -> Vec> { + self.pending.extend_from_slice(chunk); + let mut out = Vec::new(); + let mut start = 0; + while let Some(i) = self.pending[start..].iter().position(|b| *b == b'\n') { + out.push(self.pending[start..start + i].to_vec()); + start += i + 1; + } + self.pending.drain(..start); + out + } + + fn rest(&mut self) -> Option> { + let rest = std::mem::take(&mut self.pending); + (!rest.iter().all(u8::is_ascii_whitespace)).then_some(rest) + } + + fn columns(&self) -> Vec { + let names = self.names.clone().unwrap_or_default(); + let types = self.types.clone().unwrap_or_default(); + names + .into_iter() + .enumerate() + .map(|(i, n)| { + let ty = types.get(i).cloned().unwrap_or_default(); + let mut c = ColumnInfo::new(n, ch_type_label(&ty)); + c.nullable = ty.starts_with("Nullable("); + c + }) + .collect() + } + + fn take(&mut self, line: &[u8], sink: &mut super::query::RowSink) -> Result<(), String> { + if line.iter().all(u8::is_ascii_whitespace) { + return Ok(()); + } + let parsed: Result, _> = serde_json::from_slice(line); + let Ok(values) = parsed else { + let text = String::from_utf8_lossy(line); + return Err(format!("ClickHouse error: {}", text.trim().chars().take(500).collect::())); + }; + let strings = || values.iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect::>(); + if self.names.is_none() { + self.names = Some(strings()); + return Ok(()); + } + if self.types.is_none() { + self.types = Some(strings()); + return Ok(()); + } + if self.rows == 0 { + sink.start(self.columns())?; + } + self.rows += 1; + sink.push(values.into_iter().map(|v| super::sql_util::cap_json_value("text", v)).collect()) + } +} + async fn query_in_with( config: &ClickhouseConfig, database: &str, sql: &str, readonly: bool, +) -> Result { + query_in_full(config, database, sql, readonly, None).await +} + +/// Decimals as text with their scale: as JSON numbers they lost trailing zeros +/// (a Decimal(10,2) of 12.50 showed 12.5) and, past 15-17 digits, precision, +/// since a Decimal(38) does not fit in the double the number parses into. +const DECIMAL_OUTPUT: &str = "&output_format_json_quote_decimals=1&output_format_decimal_trailing_zeros=1"; + +async fn query_in_full( + config: &ClickhouseConfig, + database: &str, + sql: &str, + readonly: bool, + query_id: Option<&str>, ) -> Result { let trimmed = sql.trim().trim_end_matches(';'); let read = is_read_query(trimmed); @@ -110,13 +342,17 @@ async fn query_in_with( }; let url = format!( - "{}/?database={}{}", + "{}/?database={}{}{}{}", config.base_url(), urlencoding::encode(database), - if readonly { "&readonly=1" } else { "" } + // 2, not 1: still no writes, but the settings below may be set (1 + // refuses any setting in the request). + if readonly { "&readonly=2" } else { "" }, + query_id.map(|id| format!("&query_id={}", urlencoding::encode(id))).unwrap_or_default(), + if read { DECIMAL_OUTPUT } else { "" } ); let t0 = Instant::now(); - let res = client() + let res = client_for(config) .post(&url) .header("X-ClickHouse-User", &config.user) .header("X-ClickHouse-Key", &config.password) @@ -559,3 +795,28 @@ mod tree_tests { assert_eq!(idx[2].index_type, "bloom_filter"); } } + +#[cfg(test)] +mod via_tests { + // As redis::via_tests: an unresolvable name, reached through `via`, and + // the server sees that name in the Host header (and so in TLS SNI). + // STROKE_TEST_FAKE_HTTP=127.0.0.1:18123 cargo test --lib clickhouse::via_tests + #[tokio::test] + async fn dials_the_tunnel_and_keeps_the_name() { + let Ok(addr) = std::env::var("STROKE_TEST_FAKE_HTTP") else { return }; + let via: std::net::SocketAddr = addr.parse().unwrap(); + let cfg = crate::db::connection::ClickhouseConfig { + name: "t".into(), + host: "ch.stroke.test".into(), + port: 8443, + database: "default".into(), + user: "default".into(), + password: String::new(), + secure: false, + ssh: None, + via: Some(via), + }; + let r = super::query(&cfg, "SELECT 1").await.expect("query through the tunnel address"); + assert_eq!(r.rows[0][0], serde_json::json!(format!("ch.stroke.test:{}", via.port()))); + } +} diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index 2ce51837..4500235b 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -34,10 +34,39 @@ pub struct PgConfig { pub ssl_root_cert: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ssh: Option, + /// Where to dial instead of `host`, through an SSH tunnel (with `port` + /// set to the tunnel's). `host` stays the server's real name so TLS checks + /// the certificate against it. Set by the tunnel resolver, never saved. + #[serde(skip)] + pub via: Option, /// Session time zone applied on every pooled connection (IANA name, e.g. /// "America/New_York"). `None`/"SYSTEM" leaves the server default in place. #[serde(default, skip_serializing_if = "Option::is_none")] pub timezone: Option, + /// The rest of a connection URL's query, as written (`application_name=x& + /// options=endpoint%3Dep-1`): what a pasted URL carried beyond the fields. + /// TLS keys are the fields' to set and are skipped here. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, +} + +/// Extra query parameters that can be appended to a Postgres URL: `key=value` +/// pairs, minus the ones the form owns, and nothing that would end the query +/// or start a fragment. +fn extra_pg_params(raw: Option<&str>) -> Vec { + const OWNED: [&str; 3] = ["sslmode", "sslrootcert", "ssl"]; + raw.unwrap_or("") + .trim() + .trim_start_matches('?') + .split('&') + .map(str::trim) + .filter(|p| !p.is_empty() && !p.contains(['#', ' ', '?'])) + .filter(|p| { + let key = p.split('=').next().unwrap_or("").to_ascii_lowercase(); + !key.is_empty() && !OWNED.contains(&key.as_str()) + }) + .map(String::from) + .collect() } impl PgConfig { @@ -62,6 +91,7 @@ impl PgConfig { params.push(format!("sslrootcert={}", urlencoding::encode(ca))); } } + params.extend(extra_pg_params(self.params.as_deref())); let ssl = if params.is_empty() { String::new() } else { @@ -115,6 +145,11 @@ pub struct MysqlConfig { pub ssl_root_cert: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ssh: Option, + /// Where to dial instead of `host`, through an SSH tunnel (with `port` + /// set to the tunnel's). `host` stays the server's real name so TLS checks + /// the certificate against it. Set by the tunnel resolver, never saved. + #[serde(skip)] + pub via: Option, /// Session time zone applied on connect (`SET time_zone`). `None`/"SYSTEM" /// leaves the server default in place. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -187,13 +222,28 @@ pub struct ClickhouseConfig { /// Use HTTPS (port 8443) instead of plain HTTP (port 8123). #[serde(default)] pub secure: bool, + /// Reach the server through an SSH tunnel (see `tunnel_to`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + /// Where to dial instead of `host:port`: the tunnel's local end. `host` + /// stays the server's real name, so TLS checks the certificate against + /// it rather than against 127.0.0.1. Set by `tunnel_via`, never saved. + #[serde(skip)] + pub via: Option, } impl ClickhouseConfig { /// Base HTTP(S) URL for the ClickHouse HTTP interface, no trailing slash. pub fn base_url(&self) -> String { let scheme = if self.secure { "https" } else { "http" }; - format!("{scheme}://{}:{}", self.host, self.port) + match self.via { + // Through a tunnel: the real name (TLS checks it, and the HTTP + // client resolves it to the tunnel), at the tunnel's port. An IP + // address has no name to keep, so it is replaced outright. + Some(via) if self.host.parse::().is_ok() => format!("{scheme}://{via}"), + Some(via) => format!("{scheme}://{}:{}", self.host, via.port()), + None => format!("{scheme}://{}:{}", self.host, self.port), + } } } @@ -239,6 +289,14 @@ pub struct RedisConfig { /// Use TLS (rediss://) instead of plain TCP (redis://). #[serde(default)] pub tls: bool, + /// Reach the server through an SSH tunnel (see `tunnel_to`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + /// Where to dial instead of `host:port`: the tunnel's local end. `host` + /// stays the server's real name, so TLS checks the certificate against + /// it rather than against 127.0.0.1. Set by `tunnel_via`, never saved. + #[serde(skip)] + pub via: Option, } // ── DuckDB ──────────────────────────────────────────────────────────────────── @@ -273,6 +331,14 @@ pub struct MssqlConfig { /// Skip TLS certificate validation (self-signed dev servers). #[serde(default)] pub trust_cert: bool, + /// Reach the server through an SSH tunnel (see `tunnel_to`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + /// Where to dial instead of `host:port`: the tunnel's local end. `host` + /// stays the server's real name, so TLS checks the certificate against + /// it rather than against 127.0.0.1. Set by `tunnel_via`, never saved. + #[serde(skip)] + pub via: Option, } /// tiberius `Client` is async and not clonable; share it behind an async mutex. @@ -306,6 +372,9 @@ pub struct OracleConfig { /// finds by itself. #[serde(default)] pub client_lib_dir: String, + /// Reach the server through an SSH tunnel (see `tunnel_to`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, } fn default_oracle_port() -> u16 { @@ -374,6 +443,14 @@ pub enum ActiveConnection { Mssql(MssqlHandle), Oracle(OracleHandle), Posthog(PosthogConfig), + /// Google Cloud Spanner (beta), over its REST API. + Spanner(crate::db::spanner::SpannerHandle), + /// Google BigQuery (beta), over its REST API. + Bigquery(crate::db::bigquery::BigQueryHandle), + /// Any database through its ODBC driver (beta). + Odbc(crate::db::odbc::OdbcHandle), + /// Snowflake (beta), over its SQL REST API. + Snowflake(crate::db::snowflake::SnowflakeHandle), } impl ActiveConnection { @@ -392,6 +469,10 @@ impl ActiveConnection { Self::Mssql(_) => "mssql", Self::Oracle(_) => "oracle", Self::Posthog(_) => "posthog", + Self::Spanner(_) => "spanner", + Self::Bigquery(_) => "bigquery", + Self::Odbc(_) => "odbc", + Self::Snowflake(_) => "snowflake", } } } @@ -544,6 +625,8 @@ pub fn update_d1_token(token: &str) { } fn set_conn(state: &Db<'_>, conn: Option) -> Result<(), String> { + // Open transactions belong to the connection being replaced. + super::tx::connection_changed(); *state.conn.lock().map_err(|e| e.to_string())? = conn; // A fresh pool: the page names its key once it knows it (set_active_conn_key). *state.active_key.lock().map_err(|e| e.to_string())? = None; @@ -551,6 +634,10 @@ fn set_conn(state: &Db<'_>, conn: Option) -> Result<(), String } async fn close_existing(state: &Db<'_>) { + super::tx::connection_changed(); + // The tunnel under the closing connection goes with it. Connects that + // tunnel set their new one after this. + super::ssh_tunnel::drop_active(); let old = state.conn.lock().ok().and_then(|mut g| g.take()); let Some(conn) = old else { return }; close_in_background(conn); @@ -1074,6 +1161,10 @@ fn pg_pool_builder() -> PgPoolOptions { // first table open's six queries for the same ten slots. The row counts // lost that race, which is exactly what "pool timed out while waiting for // an open connection" was in the log. + // A connection a stopped run or a superseded fetch left mid-result is + // closed rather than reused: reusing it first drains the rest of the + // abandoned result over the link (query.rs `discard_connection`). + .after_release(|conn, _meta| Box::pin(async move { Ok(!super::query::take_discard(conn.backend_process_id())) })) .min_connections(2) // 20s, not 10: a single handshake to a proxied serverless host measured // 5.7s, so a query queued behind two of them blew a 10s ceiling and failed @@ -1267,6 +1358,10 @@ pub(crate) async fn open_pg(config: &PgConfig) -> Result { .connection_url() .parse() .map_err(|e| format!("Connection failed: {e}"))?; + let opts = match config.via { + Some(via) => opts.hostaddr(&via.ip().to_string()), + None => opts, + }; // The hostname is deliberately kept rather than swapped for the probed IP: // the driver needs it for TLS SNI (managed Postgres behind a proxy routes on // it) and the OS resolver caches the lookup anyway. @@ -1334,7 +1429,8 @@ connect_pg_pool( } }; - connect_racing_probe(&config.host, config.port, Some(&tcp_ok), connect).await + let (probe_host, probe_port) = probe_target(&config.host, config.port, config.via); + connect_racing_probe(&probe_host, probe_port, Some(&tcp_ok), connect).await } pub async fn test_connection(config: PgConfig) -> Result<(), String> { @@ -1353,7 +1449,6 @@ pub async fn connect( tunnel_state: State<'_, TunnelState>, config: PgConfig, ) -> Result<(), String> { - tunnel_state.clear(); let (effective, tunnel) = resolve_pg_ssh(config).await?; let pool = open_pg(&effective).await?; close_existing(&state).await; @@ -1365,14 +1460,164 @@ pub async fn connect( Ok(()) } +/// Open `ssh`, when set, to `host:port`, and say where to dial instead: the +/// tunnel's local end. The tunnel must outlive every connection made through it. +pub(crate) async fn tunnel_to( + ssh: &Option, + host: &str, + port: u16, +) -> Result<(String, u16, Option), String> { + let Some(ssh) = crate::db::ssh_tunnel::effective(ssh) else { return Ok((host.to_string(), port, None)) }; + let tunnel = SshTunnel::establish(&ssh, host, port).await?; + Ok(("127.0.0.1".into(), tunnel.local_port, Some(tunnel))) +} + +/// Open `ssh`, when set, and return the address its local end listens on, for +/// a driver that dials one address while TLS checks another name. +pub(crate) async fn tunnel_via( + ssh: &Option, + host: &str, + port: u16, +) -> Result<(Option, Option), String> { + let Some(ssh) = crate::db::ssh_tunnel::effective(ssh) else { return Ok((None, None)) }; + let tunnel = SshTunnel::establish(&ssh, host, port).await?; + Ok((Some(std::net::SocketAddr::from(([127, 0, 0, 1], tunnel.local_port))), Some(tunnel))) +} + +/// The address a probe should race: the tunnel's local end when there is one. +pub(crate) fn probe_target(host: &str, port: u16, via: Option) -> (String, u16) { + match via { + Some(a) => (a.ip().to_string(), a.port()), + None => (host.to_string(), port), + } +} + +pub(crate) async fn resolve_clickhouse_ssh(mut c: ClickhouseConfig) -> Result<(ClickhouseConfig, Option), String> { + let (via, t) = tunnel_via(&c.ssh, &c.host, c.port).await?; + c.via = via; + Ok((c, t)) +} + +pub(crate) async fn resolve_redis_ssh(mut c: RedisConfig) -> Result<(RedisConfig, Option), String> { + let (via, t) = tunnel_via(&c.ssh, &c.host, c.port).await?; + c.via = via; + Ok((c, t)) +} + +pub(crate) async fn resolve_mssql_ssh(mut c: MssqlConfig) -> Result<(MssqlConfig, Option), String> { + let (via, t) = tunnel_via(&c.ssh, &c.host, c.port).await?; + c.via = via; + Ok((c, t)) +} + +pub(crate) async fn resolve_oracle_ssh(mut c: OracleConfig) -> Result<(OracleConfig, Option), String> { + if c.ssh.is_some() && !c.connect_string.trim().is_empty() { + return Err("An SSH tunnel needs the host and port fields, not a connect string: the tunnel has to know where to forward to.".into()); + } + let (host, port, t) = tunnel_to(&c.ssh, &c.host, c.port).await?; + (c.host, c.port) = (host, port); + Ok((c, t)) +} + +pub(crate) async fn resolve_mongo_ssh(mut c: crate::db::mongo::MongoConfig) -> Result<(crate::db::mongo::MongoConfig, Option), String> { + let Some(ssh) = crate::db::ssh_tunnel::effective(&c.ssh) else { return Ok((c, None)) }; + // Refuse what the tunnel can't carry before opening it. + crate::db::ssh_tunnel::mongo_uri_via(&c.uri, 0)?; + let (host, port) = crate::db::ssh_tunnel::mongo_first_host(&c.uri).ok_or("No host in the connection string")?; + let tunnel = SshTunnel::establish(&ssh, &host, port).await?; + c.uri = crate::db::ssh_tunnel::mongo_uri_via(&c.uri, tunnel.local_port)?; + Ok((c, Some(tunnel))) +} + +pub(crate) async fn resolve_cassandra_ssh(mut c: crate::db::cassandra::CassandraConfig) -> Result<(crate::db::cassandra::CassandraConfig, Option), String> { + let Some(ssh) = crate::db::ssh_tunnel::effective(&c.ssh) else { return Ok((c, None)) }; + // One contact point is enough: the driver reaches every node through it. + let first = c.hosts.split(',').map(str::trim).find(|h| !h.is_empty()).ok_or("Enter at least one host")?.to_string(); + let (host, port) = match first.rsplit_once(':') { + Some((h, p)) if p.parse::().is_ok() => (h.trim_matches(['[', ']']).to_string(), p.parse::().unwrap_or(9042)), + _ => (first.clone(), 9042), + }; + let tunnel = SshTunnel::establish(&ssh, &host, port).await?; + c.hosts = format!("127.0.0.1:{}", tunnel.local_port); + Ok((c, Some(tunnel))) +} + +pub(crate) async fn resolve_couch_ssh(mut c: crate::db::couchdb::CouchConfig) -> Result<(crate::db::couchdb::CouchConfig, Option), String> { + let Some(ssh) = c.ssh.clone() else { return Ok((c, None)) }; + let (host, port) = crate::db::ssh_tunnel::url_target(&c.url)?; + let (via, t) = tunnel_via(&Some(ssh), &host, port).await?; + c.via = via; + Ok((c, t)) +} + +pub(crate) async fn resolve_elastic_ssh(mut c: crate::db::elastic::EsConfig) -> Result<(crate::db::elastic::EsConfig, Option), String> { + let Some(ssh) = c.ssh.clone() else { return Ok((c, None)) }; + let (host, port) = crate::db::ssh_tunnel::url_target(&c.url)?; + let (via, t) = tunnel_via(&Some(ssh), &host, port).await?; + c.via = via; + Ok((c, t)) +} + +/// Open the SSH tunnel a saved connection asks for, whatever its engine, and +/// return the config pointed through it. Hold the tunnel for as long as +/// anything opened from the config is in use: dropping it closes ssh. +/// +/// For the paths that open a connection of their own beside the open one +/// (Data Diff, schema compare, scheduled backups). They dialed the server +/// directly, so a database only reachable through a bastion failed there +/// while it worked everywhere else. +pub(crate) async fn tunnel_any(config: AnyConnectionConfig) -> Result<(AnyConnectionConfig, Option), String> { + Ok(match config { + AnyConnectionConfig::Postgres(c) => { + let (c, t) = resolve_pg_ssh(c).await?; + (AnyConnectionConfig::Postgres(c), t) + } + AnyConnectionConfig::Mysql(c) => { + let (c, t) = resolve_mysql_ssh(c).await?; + (AnyConnectionConfig::Mysql(c), t) + } + AnyConnectionConfig::Mssql(c) => { + let (c, t) = resolve_mssql_ssh(c).await?; + (AnyConnectionConfig::Mssql(c), t) + } + AnyConnectionConfig::Oracle(c) => { + let (c, t) = resolve_oracle_ssh(c).await?; + (AnyConnectionConfig::Oracle(c), t) + } + AnyConnectionConfig::Clickhouse(c) => { + let (c, t) = resolve_clickhouse_ssh(c).await?; + (AnyConnectionConfig::Clickhouse(c), t) + } + AnyConnectionConfig::Redis(c) => { + let (c, t) = resolve_redis_ssh(c).await?; + (AnyConnectionConfig::Redis(c), t) + } + AnyConnectionConfig::Mongodb(c) => { + let (c, t) = resolve_mongo_ssh(c).await?; + (AnyConnectionConfig::Mongodb(c), t) + } + AnyConnectionConfig::Couchdb(c) => { + let (c, t) = resolve_couch_ssh(c).await?; + (AnyConnectionConfig::Couchdb(c), t) + } + AnyConnectionConfig::Elasticsearch(c) => { + let (c, t) = resolve_elastic_ssh(c).await?; + (AnyConnectionConfig::Elasticsearch(c), t) + } + other => (other, None), + }) +} + /// Establish an SSH tunnel if `config.ssh` is set, return a direct config pointing /// at the local forwarded port. The tunnel's lifetime must outlive the connection. pub(crate) async fn resolve_pg_ssh(config: PgConfig) -> Result<(PgConfig, Option), String> { - if let Some(ref ssh_cfg) = config.ssh { + if let Some(ref ssh_cfg) = crate::db::ssh_tunnel::effective(&config.ssh) { let tunnel = SshTunnel::establish(ssh_cfg, &config.host, config.port).await?; let local_port = tunnel.local_port; let mut direct = config.clone(); - direct.host = "127.0.0.1".to_string(); + // Dial the tunnel, keep the name: TLS (verify-full, VERIFY_IDENTITY) + // checks the certificate against the real host, not 127.0.0.1. + direct.via = Some(std::net::SocketAddr::from(([127, 0, 0, 1], local_port))); direct.port = local_port; direct.ssh = None; Ok((direct, Some(tunnel))) @@ -1440,6 +1685,10 @@ pub(crate) async fn open_mysql(config: &MysqlConfig) -> Result opts.hostaddr(&via.ip().to_string()), + None => opts, + }; let opts = opts.log_slow_statements(LevelFilter::Debug, Duration::from_secs(5)); // Optional session time zone (Settings → Database), applied per connection @@ -1507,9 +1756,10 @@ pub(crate) async fn open_mysql(config: &MysqlConfig) -> Result(pool) }; + let (probe_host, probe_port) = probe_target(&config.host, config.port, config.via); connect_racing_probe( - &config.host, - config.port, + &probe_host, + probe_port, None, async { connect.await.map_err(|e| format!("Connection failed: {e}")) }, ) @@ -1532,7 +1782,6 @@ pub async fn connect_mysql( tunnel_state: State<'_, TunnelState>, config: MysqlConfig, ) -> Result<(), String> { - tunnel_state.clear(); let (effective, tunnel) = resolve_mysql_ssh(config).await?; let pool = open_mysql(&effective).await?; close_existing(&state).await; @@ -1542,11 +1791,13 @@ pub async fn connect_mysql( } pub(crate) async fn resolve_mysql_ssh(config: MysqlConfig) -> Result<(MysqlConfig, Option), String> { - if let Some(ref ssh_cfg) = config.ssh { + if let Some(ref ssh_cfg) = crate::db::ssh_tunnel::effective(&config.ssh) { let tunnel = SshTunnel::establish(ssh_cfg, &config.host, config.port).await?; let local_port = tunnel.local_port; let mut direct = config.clone(); - direct.host = "127.0.0.1".to_string(); + // Dial the tunnel, keep the name: TLS (verify-full, VERIFY_IDENTITY) + // checks the certificate against the real host, not 127.0.0.1. + direct.via = Some(std::net::SocketAddr::from(([127, 0, 0, 1], local_port))); direct.port = local_port; direct.ssh = None; Ok((direct, Some(tunnel))) @@ -1585,7 +1836,13 @@ pub async fn connect_libsql(state: Db<'_>, config: LibSqlConfig) -> Result<(), S // ── ClickHouse connect / test ───────────────────────────────────────────────── pub async fn test_clickhouse_connection(config: ClickhouseConfig) -> Result<(), String> { - let (host, port) = (config.host.clone(), config.port); + let (config, _tunnel) = resolve_clickhouse_ssh(config).await?; + probe_clickhouse(config).await +} + +/// `config` already points where to dial (through its tunnel, if any). +async fn probe_clickhouse(config: ClickhouseConfig) -> Result<(), String> { + let (host, port) = probe_target(&config.host, config.port, config.via); connect_racing_probe(&host, port, None, async move { crate::db::clickhouse::query(&config, "SELECT 1").await?; Ok(()) @@ -1593,11 +1850,14 @@ pub async fn test_clickhouse_connection(config: ClickhouseConfig) -> Result<(), .await } -pub async fn connect_clickhouse(state: Db<'_>, config: ClickhouseConfig) -> Result<(), String> { +pub async fn connect_clickhouse(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: ClickhouseConfig) -> Result<(), String> { + let (config, tunnel) = resolve_clickhouse_ssh(config).await?; // Validate credentials/reachability before storing. - test_clickhouse_connection(config.clone()).await?; + probe_clickhouse(config.clone()).await?; close_existing(&state).await; - set_conn(&state, Some(ActiveConnection::Clickhouse(config))) + set_conn(&state, Some(ActiveConnection::Clickhouse(config)))?; + tunnel_state.set(tunnel); + Ok(()) } // ── PostHog connect / test ──────────────────────────────────────────────────── @@ -1621,14 +1881,93 @@ pub async fn connect_dynamodb(state: Db<'_>, config: crate::db::dynamodb::Dynamo // ── Document engines connect ────────────────────────────────────────────────── -pub async fn connect_cassandra(state: Db<'_>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { +pub async fn connect_cassandra(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::cassandra::CassandraConfig) -> Result<(), String> { + let (config, tunnel) = resolve_cassandra_ssh(config).await?; let session = crate::db::cassandra::connect(&config).await?; - set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(session)))) + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Cassandra(session))))?; + tunnel_state.set(tunnel); + Ok(()) } -pub async fn connect_mongo(state: Db<'_>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { +pub async fn connect_mongo(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::mongo::MongoConfig) -> Result<(), String> { + let (config, tunnel) = resolve_mongo_ssh(config).await?; let handle = crate::db::mongo::connect(&config).await?; - set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(handle)))) + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Mongo(handle))))?; + tunnel_state.set(tunnel); + Ok(()) +} + +/// Google Cloud Spanner (beta): checks the database, learns its dialect and +/// opens a session before it becomes the active connection. +/// Returns the database's dialect ("googlesql" or "postgresql"): the +/// frontend writes its review and generated SQL in it. +pub async fn connect_spanner(state: Db<'_>, config: crate::db::spanner::SpannerConfig) -> Result { + let h = crate::db::spanner::connect(&config).await?; + let dialect = match h.dialect { + crate::db::spanner::Dialect::Postgres => "postgresql", + crate::db::spanner::Dialect::GoogleSql => "googlesql", + }; + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Spanner(h)))?; + Ok(dialect.to_string()) +} + +/// Google BigQuery (beta): the project answers before it becomes the active +/// connection. +pub async fn connect_bigquery(state: Db<'_>, config: crate::db::bigquery::BigQueryConfig) -> Result<(), String> { + let h = crate::db::bigquery::connect(&config).await?; + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Bigquery(h))) +} + +/// A database through its ODBC driver (beta): connects and reads what the +/// driver says about naming and paging before it becomes active. +pub async fn connect_odbc(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::odbc::OdbcConfig) -> Result { + let (config, tunnel) = resolve_odbc_ssh(config).await?; + let h = crate::db::odbc::connect(&config).await?; + let summary = h.info.summary(); + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Odbc(h)))?; + tunnel_state.set(tunnel); + Ok(summary) +} + +/// An ODBC connection through SSH: the tunnel to the preset's host and port, +/// and the connection string pointed at its local end. +pub(crate) async fn resolve_odbc_ssh(mut c: crate::db::odbc::OdbcConfig) -> Result<(crate::db::odbc::OdbcConfig, Option), String> { + let Some(ssh) = c.ssh.clone() else { return Ok((c, None)) }; + let (Some(host), Some(port)) = (c.target_host.clone().filter(|h| !h.trim().is_empty()), c.target_port) else { + return Err("An SSH tunnel needs the database's host and port: fill them in on the Fields tab".into()); + }; + let tunnel = SshTunnel::establish(&ssh, host.trim(), port).await?; + let cs = crate::db::odbc::connection_string(&c)?; + c.connection_string = Some(crate::db::odbc::retarget(&cs, &host, port, tunnel.local_port)); + c.dsn = None; + // The credentials are in the retargeted string already. + c.user = None; + c.password = None; + Ok((c, Some(tunnel))) +} + +/// Snowflake (beta): signs in and runs SELECT 1 before it becomes active. +pub async fn connect_snowflake(state: Db<'_>, config: crate::db::snowflake::SnowflakeConfig) -> Result<(), String> { + let h = crate::db::snowflake::connect(&config).await?; + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Snowflake(h))) +} + +/// InfluxDB (beta, read-only): 1.x, 2.x or 3.x over HTTP. +pub async fn connect_influx(state: Db<'_>, config: crate::db::influx::InfluxConfig) -> Result<(), String> { + let config = crate::db::influx::connect(&config).await?; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Influx(config)))) +} + +/// Neo4j (beta): over its HTTP API. +pub async fn connect_neo4j(state: Db<'_>, config: crate::db::neo4j::Neo4jConfig) -> Result<(), String> { + let config = crate::db::neo4j::connect(&config).await?; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Neo4j(config)))) } pub async fn connect_firestore(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { @@ -1636,28 +1975,45 @@ pub async fn connect_firestore(state: Db<'_>, config: crate::db::firestore::Fire set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Firestore(config)))) } -pub async fn connect_couchdb(state: Db<'_>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { +pub async fn connect_couchdb(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::couchdb::CouchConfig) -> Result<(), String> { + let (config, tunnel) = resolve_couch_ssh(config).await?; crate::db::couchdb::ping(&config).await?; - set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Couch(config)))) + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Couch(config))))?; + tunnel_state.set(tunnel); + Ok(()) } -pub async fn connect_elastic(state: Db<'_>, config: crate::db::elastic::EsConfig) -> Result<(), String> { +pub async fn connect_elastic(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: crate::db::elastic::EsConfig) -> Result<(), String> { + let (config, tunnel) = resolve_elastic_ssh(config).await?; let config = crate::db::elastic::connect(config).await?; - set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Elastic(config)))) + close_existing(&state).await; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Elastic(config))))?; + tunnel_state.set(tunnel); + Ok(()) } // ── Redis connect / test ────────────────────────────────────────────────────── pub async fn test_redis_connection(config: RedisConfig) -> Result<(), String> { - let (host, port) = (config.host.clone(), config.port); - connect_racing_probe(&host, port, None, crate::db::redis::ping(&config)).await + let (config, _tunnel) = resolve_redis_ssh(config).await?; + probe_redis(&config).await } -pub async fn connect_redis(state: Db<'_>, config: RedisConfig) -> Result<(), String> { +/// `config` already points where to dial (through its tunnel, if any). +async fn probe_redis(config: &RedisConfig) -> Result<(), String> { + let (host, port) = probe_target(&config.host, config.port, config.via); + connect_racing_probe(&host, port, None, crate::db::redis::ping(config)).await +} + +pub async fn connect_redis(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: RedisConfig) -> Result<(), String> { + let (config, tunnel) = resolve_redis_ssh(config).await?; // Validate credentials/reachability before storing. - test_redis_connection(config.clone()).await?; + probe_redis(&config).await?; close_existing(&state).await; - set_conn(&state, Some(ActiveConnection::Redis(config))) + set_conn(&state, Some(ActiveConnection::Redis(config)))?; + tunnel_state.set(tunnel); + Ok(()) } // ── DuckDB connect / test ────────────────────────────────────────────────────── @@ -1699,20 +2055,27 @@ pub async fn connect_duckdb(state: Db<'_>, config: DuckdbConfig) -> Result<(), S // ── MS SQL Server connect / test ──────────────────────────────────────────────── pub(crate) async fn open_mssql(config: &MssqlConfig) -> Result { - let client = - connect_racing_probe(&config.host, config.port, None, crate::db::mssql::connect(config)).await?; - Ok(Arc::new(tokio::sync::Mutex::new(client))) + let (host, port) = probe_target(&config.host, config.port, config.via); + let client = connect_racing_probe(&host, port, None, crate::db::mssql::connect(config)).await?; + let handle = Arc::new(tokio::sync::Mutex::new(client)); + // So Stop can find this session (see mssql::cancel). + crate::db::mssql::remember(&handle, config).await; + Ok(handle) } pub async fn test_mssql_connection(config: MssqlConfig) -> Result<(), String> { + let (config, _tunnel) = resolve_mssql_ssh(config).await?; let handle = open_mssql(&config).await?; crate::db::mssql::ping(&handle).await } -pub async fn connect_mssql(state: Db<'_>, config: MssqlConfig) -> Result<(), String> { +pub async fn connect_mssql(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: MssqlConfig) -> Result<(), String> { + let (config, tunnel) = resolve_mssql_ssh(config).await?; let handle = open_mssql(&config).await?; close_existing(&state).await; - set_conn(&state, Some(ActiveConnection::Mssql(handle))) + set_conn(&state, Some(ActiveConnection::Mssql(handle)))?; + tunnel_state.set(tunnel); + Ok(()) } // ── Oracle connect / test ─────────────────────────────────────────────────────── @@ -1729,14 +2092,18 @@ pub(crate) async fn open_oracle(config: &OracleConfig) -> Result Result<(), String> { + let (config, _tunnel) = resolve_oracle_ssh(config).await?; let handle = open_oracle(&config).await?; crate::db::oracle::ping(&handle).await } -pub async fn connect_oracle(state: Db<'_>, config: OracleConfig) -> Result<(), String> { +pub async fn connect_oracle(state: Db<'_>, tunnel_state: State<'_, TunnelState>, config: OracleConfig) -> Result<(), String> { + let (config, tunnel) = resolve_oracle_ssh(config).await?; let handle = open_oracle(&config).await?; close_existing(&state).await; - set_conn(&state, Some(ActiveConnection::Oracle(handle))) + set_conn(&state, Some(ActiveConnection::Oracle(handle)))?; + tunnel_state.set(tunnel); + Ok(()) } // ── Disconnect ──────────────────────────────────────────────────────────────── @@ -1765,6 +2132,7 @@ mod tests { fn pg(ssl: bool, mode: Option<&str>, ca: Option<&str>) -> PgConfig { PgConfig { + via: None, name: "t".into(), host: "db.example.com".into(), port: 5432, @@ -1776,9 +2144,64 @@ mod tests { ssl_root_cert: ca.map(str::to_string), ssh: None, timezone: None, + params: None, } } + #[test] + fn a_pasted_urls_other_parameters_ride_along() { + let mut c = pg(true, Some("verify-full"), None); + c.params = Some("application_name=stroke&options=endpoint%3Dep-1&sslmode=disable&bad#frag& &=x".into()); + let url = c.connection_url(); + assert!(url.ends_with("?sslmode=verify-full&application_name=stroke&options=endpoint%3Dep-1"), "{url}"); + let opts: PgConnectOptions = url.parse().unwrap(); + assert_eq!(opts.get_application_name(), Some("stroke")); + // No params, no change. + assert!(pg(false, None, None).connection_url().ends_with("/shop")); + } + + // Live: TLS through an SSH tunnel verifies the server's real name. The + // scratch server's certificate names db.stroke.test, which does not even + // resolve: only dialing the tunnel while TLS checks that name can work. + // Before, the config was rewritten to 127.0.0.1 and verify-full failed. + // STROKE_TEST_SSH=user@127.0.0.1:2222 STROKE_TEST_SSH_KEY=… STROKE_TEST_KNOWN_HOSTS=… + // STROKE_TEST_TLS_PG=127.0.0.1:5544 STROKE_TEST_TLS_CA=/path/ca.crt + #[tokio::test] + async fn live_tls_through_a_tunnel_verifies_the_real_name() { + let (Ok(target), Ok(key), Ok(tls_pg), Ok(ca)) = ( + std::env::var("STROKE_TEST_SSH"), + std::env::var("STROKE_TEST_SSH_KEY"), + std::env::var("STROKE_TEST_TLS_PG"), + std::env::var("STROKE_TEST_TLS_CA"), + ) else { + return; + }; + let (user, hostport) = target.split_once('@').unwrap(); + let (sh, sp) = hostport.split_once(':').unwrap(); + let (_, pg_port) = tls_pg.split_once(':').unwrap(); + let mut c = pg(true, Some("verify-full"), Some(&ca)); + c.host = "db.stroke.test".into(); + c.port = pg_port.parse().unwrap(); + c.user = "postgres".into(); + c.password = String::new(); + c.database = "postgres".into(); + // The tunnel forwards to the scratch server; its far end resolves + // nothing, it just connects to 127.0.0.1. + let ssh = SshConfig { host: sh.into(), port: sp.parse().unwrap(), username: user.into(), private_key_path: key, keepalive: 30, ..Default::default() }; + let tunnel = SshTunnel::establish(&ssh, "127.0.0.1", c.port).await.unwrap(); + c.via = Some(std::net::SocketAddr::from(([127, 0, 0, 1], tunnel.local_port))); + c.port = tunnel.local_port; + let pool = open_pg(&c).await.expect("verify-full against db.stroke.test through the tunnel"); + let ssl: bool = sqlx::query_scalar("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetch_one(&pool).await.unwrap(); + assert!(ssl); + // The old way, dialing and verifying 127.0.0.1, is refused. + let mut old = c.clone(); + old.via = None; + old.host = "127.0.0.1".into(); + let err = open_pg(&old).await.err().expect("127.0.0.1 is not the certificate's name"); + assert!(err.to_lowercase().contains("certificate") || err.to_lowercase().contains("name"), "{err}"); + } + /// A password ending in `%` and a database name with `%`/`#` must reach /// sqlx intact: it percent-decodes the whole URL, so anything left raw was /// cut or misread. @@ -1828,6 +2251,7 @@ mod tests { fn my(ssl: bool, mode: Option<&str>, ca: Option<&str>) -> MysqlConfig { MysqlConfig { + via: None, name: "t".into(), host: "db.example.com".into(), port: 3306, diff --git a/src-tauri/src/db/couchdb.rs b/src-tauri/src/db/couchdb.rs index bf43e8d2..a56fb7d8 100644 --- a/src-tauri/src/db/couchdb.rs +++ b/src-tauri/src/db/couchdb.rs @@ -22,12 +22,19 @@ pub struct CouchConfig { pub user: Option, #[serde(default)] pub password: Option, + /// Reach the server through an SSH tunnel (connection::tunnel_to and friends). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + /// The tunnel's local end, when there is one: the URL keeps the server's + /// real name (TLS checks it) and the client resolves that name to here. + #[serde(skip)] + pub via: Option, } fn client() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .timeout(Duration::from_secs(60)) .connect_timeout(Duration::from_secs(10)) .build() @@ -38,7 +45,9 @@ fn client() -> &'static reqwest::Client { fn base(cfg: &CouchConfig) -> Result { let raw = cfg.url.trim().trim_end_matches('/'); let raw = if raw.contains("://") { raw.to_string() } else { format!("http://{raw}") }; - reqwest::Url::parse(&format!("{raw}/")).map_err(|e| format!("Invalid CouchDB URL \"{raw}\": {e}")) + reqwest::Url::parse(&format!("{raw}/")) + .map(|u| super::ssh_tunnel::url_via(u, cfg.via)) + .map_err(|e| format!("Invalid CouchDB URL \"{raw}\": {e}")) } /// Requests the app may make. Server administration (`/_config`, `/_node`, @@ -77,7 +86,10 @@ pub async fn request(cfg: &CouchConfig, method: &str, path: &str, body: Option<& .join(path.trim_start_matches('/')) .map_err(|e| format!("Invalid path \"{path}\": {e}"))?; let m = reqwest::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?; - let mut req = client().request(m, url.clone()); + let host = url.host_str().unwrap_or_default().to_string(); + let mut req = super::ssh_tunnel::http_client(&host, cfg.via, false) + .unwrap_or_else(|| client().clone()) + .request(m, url.clone()); if let Some(u) = cfg.user.as_deref().filter(|u| !u.is_empty()) { req = req.basic_auth(u, cfg.password.as_deref()); } @@ -215,6 +227,45 @@ pub async fn query(cfg: &CouchConfig, stmt: &str) -> Result Result { + let Statement::Find { db, selector, opts } = parse(stmt)? else { + return Err("Explain works on find queries: db.find({selector})".into()); + }; + let mut body = json!({ "selector": selector }); + if let Some(o) = opts.as_object() { + for (k, v) in o { + body[k] = v.clone(); + } + } + let out = request(cfg, "POST", &format!("{}/_explain", enc(&db)), Some(&body)).await?; + Ok(explain_tree(&out, &db)) +} + +/// `_explain` output → plan tree. Pure, so it is tested on recorded output. +pub fn explain_tree(out: &Value, db: &str) -> Value { + let ix = &out["index"]; + let kind = ix["type"].as_str().unwrap_or(""); + let name = ix["name"].as_str().unwrap_or(""); + let scan = match kind { + "special" => json!({ "Node Type": "All documents scan", "Relation Name": db }), + _ => json!({ + "Node Type": format!("{} index scan", if kind.is_empty() { "Index" } else { kind }), + "Relation Name": db, + "Index Name": if name.is_empty() { ix["ddoc"].as_str().unwrap_or("") } else { name }, + "Index Cond": ix["def"]["fields"].to_string(), + }), + }; + json!({ + "Node Type": "Find", + "Relation Name": db, + "Filter": out["selector"].to_string(), + "Plan Rows": out["limit"].as_i64(), + "Plans": [scan], + }) +} + /// A result-grid cell: Extended JSON scalars (`{"$oid": ...}`, `{"$date": ...}`, /// `{"$numberLong": ...}`, `{"$numberDecimal": ...}`) as their plain value, and /// the type name for the column header. @@ -396,7 +447,7 @@ mod tests { #[tokio::test] #[ignore] async fn couch_live() { - let cfg = CouchConfig { name: "t".into(), url: "http://localhost:5984".into(), user: Some("admin".into()), password: Some("admin".into()) }; + let cfg = CouchConfig { ssh: None, via: None, name: "t".into(), url: "http://localhost:5984".into(), user: Some("admin".into()), password: Some("admin".into()) }; ping(&cfg).await.unwrap(); let dbs = list_databases(&cfg).await.unwrap(); assert!(dbs.contains(&"products".to_string()), "{dbs:?}"); diff --git a/src-tauri/src/db/d1.rs b/src-tauri/src/db/d1.rs index 51a24c11..224a1d4a 100644 --- a/src-tauri/src/db/d1.rs +++ b/src-tauri/src/db/d1.rs @@ -14,7 +14,7 @@ static D1_CLIENT: OnceLock = OnceLock::new(); fn client() -> &'static reqwest::Client { D1_CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(10) .pool_idle_timeout(std::time::Duration::from_secs(90)) @@ -100,7 +100,7 @@ fn result_to_sql(result: D1QueryResult, elapsed: u64) -> Result 0 { - Some(format!("{} row(s) affected", result.meta.changes)) + Some(super::query::affected_message("", result.meta.changes as i64)) } else { None }; diff --git a/src-tauri/src/db/docdb.rs b/src-tauri/src/db/docdb.rs index 04dff9a3..325031ea 100644 --- a/src-tauri/src/db/docdb.rs +++ b/src-tauri/src/db/docdb.rs @@ -13,6 +13,8 @@ pub enum DocConn { Firestore(super::firestore::FirestoreConfig), Mongo(super::mongo::MongoHandle), Elastic(super::elastic::EsConfig), + Neo4j(super::neo4j::Neo4jConfig), + Influx(super::influx::InfluxConfig), } impl DocConn { @@ -24,6 +26,8 @@ impl DocConn { Self::Mongo(_) => "mongodb", Self::Elastic(c) if c.is_opensearch() => "opensearch", Self::Elastic(_) => "elasticsearch", + Self::Neo4j(_) => "neo4j", + Self::Influx(_) => "influxdb", } } } @@ -36,6 +40,8 @@ pub async fn query(conn: &DocConn, stmt: &str) -> Result { DocConn::Firestore(c) => super::firestore::query(c, stmt).await, DocConn::Mongo(m) => super::mongo::query(m, stmt).await, DocConn::Elastic(c) => super::elastic::query(c, stmt).await, + DocConn::Neo4j(c) => super::neo4j::query(c, stmt).await, + DocConn::Influx(c) => super::influx::query(c, stmt).await, } } @@ -57,6 +63,8 @@ pub async fn list_tables(conn: &DocConn) -> Result, String> { DocConn::Firestore(c) => super::firestore::list_collections(c).await?, DocConn::Mongo(m) => super::mongo::list_collections(m).await?, DocConn::Elastic(c) => super::elastic::list_indices(c).await?.into_iter().map(|i| i.name).collect(), + DocConn::Neo4j(c) => super::neo4j::labels(c).await?.into_iter().map(|(n, _)| n).collect(), + DocConn::Influx(c) => super::influx::measurements(c).await?, }; Ok(names .into_iter() @@ -74,7 +82,7 @@ pub async fn list_schemas(conn: &DocConn) -> Result, String> { match conn { DocConn::Mongo(m) => super::mongo::list_databases(m).await, DocConn::Cassandra(s) => super::cassandra::list_keyspaces(s).await, - DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) => Ok(vec![FLAT_SCHEMA.to_string()]), + DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![FLAT_SCHEMA.to_string()]), } } @@ -117,6 +125,8 @@ pub async fn list_tables_in(conn: &DocConn, schema: &str) -> Result Ok(super::firestore::list_collections(c).await?.into_iter().map(|n| info(n, -1)).collect()), DocConn::Elastic(c) => Ok(super::elastic::list_indices(c).await?.into_iter().map(|i| info(i.name, i.docs)).collect()), + DocConn::Neo4j(c) => Ok(super::neo4j::labels(c).await?.into_iter().map(|(n, k)| info(n, k)).collect()), + DocConn::Influx(c) => Ok(super::influx::measurements(c).await?.into_iter().map(|n| info(n, -1)).collect()), } } @@ -138,7 +148,7 @@ pub async fn use_schema(conn: &DocConn, schema: &str) -> Result<(), String> { } s.use_keyspace(schema, true).await.map_err(|e| format!("Keyspace \"{schema}\": {e}")) } - DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) => Ok(()), + DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(()), } } @@ -155,7 +165,7 @@ pub async fn columns_in(conn: &DocConn, schema: &str, table: &str) -> Result super::elastic::index_columns(c, table).await, - DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) => Ok(vec![]), + DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![]), } } @@ -164,7 +174,7 @@ pub async fn columns_in(conn: &DocConn, schema: &str, table: &str) -> Result Result, String> { match conn { DocConn::Cassandra(s) => Ok(super::cassandra::columns_by_table(super::cassandra::keyspace_columns(s, schema).await?)), - DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) => Ok(vec![]), + DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![]), } } diff --git a/src-tauri/src/db/duckdb.rs b/src-tauri/src/db/duckdb.rs index 0f49440a..215cb5d3 100644 --- a/src-tauri/src/db/duckdb.rs +++ b/src-tauri/src/db/duckdb.rs @@ -148,31 +148,177 @@ fn collect_rows( sql: &str, params: &[DuckValue], ) -> Result<(Vec, Vec>), String> { + let mut columns = Vec::new(); + let mut out: Vec> = Vec::new(); + for_each_row(conn, sql, params, |c| columns = c, |r| { + out.push(r); + true + })?; + Ok((columns, out)) +} + +/// Run `sql` and hand each row to `on_row` as it is read, after the columns to +/// `on_columns`. `on_row` returns false to stop reading. +fn for_each_row( + conn: &::duckdb::Connection, + sql: &str, + params: &[DuckValue], + on_columns: impl FnOnce(Vec), + on_row: impl FnMut(Vec) -> bool, +) -> Result<(), String> { + for_each_row_in(conn, sql, params, false, on_columns, on_row) +} + +/// `for_each_row` on DuckDB's streaming result: chunks are produced as they +/// are read, so DuckDB never holds the whole result either. For reads only +/// (streaming execution refuses DML that returns rows). +fn for_each_row_streaming( + conn: &::duckdb::Connection, + sql: &str, + on_columns: impl FnOnce(Vec), + on_row: impl FnMut(Vec) -> bool, +) -> Result<(), String> { + for_each_row_in(conn, sql, &[], true, on_columns, on_row) +} + + +/// DuckDB's SQL name for a column's logical type (the short aliases it accepts). +fn duck_type_name(id: ::duckdb::core::LogicalTypeId) -> String { + use ::duckdb::core::LogicalTypeId as T; + match id { + T::Boolean => "boolean", + T::Tinyint => "tinyint", + T::Smallint => "smallint", + T::Integer => "integer", + T::Bigint => "bigint", + T::Hugeint => "hugeint", + T::UTinyint => "utinyint", + T::USmallint => "usmallint", + T::UInteger => "uinteger", + T::UBigint => "ubigint", + T::UHugeint => "uhugeint", + T::Float => "float", + T::Double => "double", + T::Decimal => "decimal", + T::Varchar => "varchar", + T::Blob => "blob", + T::Date => "date", + T::Time => "time", + T::TimeTZ => "timetz", + T::Timestamp => "timestamp", + T::TimestampS => "timestamp_s", + T::TimestampMs => "timestamp_ms", + T::TimestampNs => "timestamp_ns", + T::TimestampTZ => "timestamptz", + T::Interval => "interval", + T::Uuid => "uuid", + T::Enum => "enum", + T::List => "list", + T::Array => "array", + T::Struct => "struct", + T::Map => "map", + T::Union => "union", + T::Bit => "bit", + T::Geometry => "geometry", + _ => "", + } + .to_string() +} + +fn is_spurious_interrupt(e: &str) -> bool { + e.contains("INTERRUPT Error") +} + +/// DuckDB race: when a worker thread fails, `Executor::PushError` sets the +/// context's `interrupted` flag, and a streaming fetch that checks the flag +/// first throws "Interrupted!" instead of the stored error +/// (`SimpleBufferedData::ExecuteTaskInternal`). The run's rows are already +/// spent, so the only way to the real message is to read the query again, +/// discarding its rows. Streamed queries are reads, so this repeats nothing +/// but the work. It gives up after two tries, or once Stop is pressed. +fn real_error(conn: &::duckdb::Connection, sql: &str, first: String, stop_pressed: impl Fn() -> bool) -> String { + for _ in 0..2 { + if stop_pressed() { + break; + } + match for_each_row_streaming(conn, sql, |_| {}, |_| true) { + Err(e) if is_spurious_interrupt(&e) => continue, + Err(e) => return e, + // Not reproducible (the error depended on timing or randomness). + Ok(()) => break, + } + } + first +} + +fn for_each_row_in( + conn: &::duckdb::Connection, + sql: &str, + params: &[DuckValue], + streaming: bool, + on_columns: impl FnOnce(Vec), + mut on_row: impl FnMut(Vec) -> bool, +) -> Result<(), String> { let mut stmt = conn.prepare(sql).map_err(|e| format!("DuckDB error: {e}"))?; // column_names()/column_count() panic before the statement is executed, so we // run query() first (it executes eagerly) and read metadata via rows.as_ref(). - let mut rows = stmt - .query(::duckdb::params_from_iter(params.iter())) - .map_err(|e| format!("DuckDB error: {e}"))?; + // + // Streaming: stream_arrow executes in DuckDB's streaming mode, and + // raw_query reads that same result through the row API. Its own Arrow + // iterator panics on a mid-stream error (fatal with panic=abort); the + // row API returns the error instead. + let mut rows = if streaming { + drop(stmt.stream_arrow(::duckdb::params_from_iter(params.iter())).map_err(|e| format!("DuckDB error: {e}"))?); + stmt.raw_query() + } else { + stmt.query(::duckdb::params_from_iter(params.iter())).map_err(|e| format!("DuckDB error: {e}"))? + }; - let (col_names, col_count): (Vec, usize) = match rows.as_ref() { - Some(s) => (s.column_names(), s.column_count()), - None => (Vec::new(), 0), + let (col_names, col_count, col_types): (Vec, usize, Vec) = match rows.as_ref() { + Some(s) => { + let n = s.column_count(); + (s.column_names(), n, (0..n).map(|i| duck_type_name(s.column_logical_type(i).id())).collect()) + } + None => (Vec::new(), 0, Vec::new()), }; - let mut out: Vec> = Vec::new(); + // Each column with DuckDB's name for its type; the grid's headers showed none. + on_columns(col_names.into_iter().zip(col_types.into_iter().chain(std::iter::repeat(String::new()))).map(|(n, t)| ColumnInfo::new(n, t)).collect()); while let Some(row) = rows.next().map_err(|e| format!("DuckDB row error: {e}"))? { let mut r = Vec::with_capacity(col_count); for i in 0..col_count { let vref = row.get_ref(i).map_err(|e| format!("DuckDB cell error: {e}"))?; r.push(valueref_to_json(vref)); } - out.push(r); + if !on_row(r) { + break; + } } + Ok(()) +} - let columns = col_names.into_iter().map(|n| ColumnInfo::new(n, "")).collect(); - Ok((columns, out)) +/// A second connection to the same database, for a transaction: DuckDB's +/// handle is one shared connection, and every other query would otherwise +/// have run inside the transaction. +pub async fn open_tx_conn(handle: &DuckdbHandle) -> Result { + run_blocking(handle.clone(), |conn| { + conn.try_clone() + .map(|c| std::sync::Arc::new(std::sync::Mutex::new(c))) + .map_err(|e| format!("DuckDB could not open a second connection: {e}")) + }) + .await +} + +/// One statement for its side effect (BEGIN, COMMIT, ROLLBACK). +pub async fn batch(handle: &DuckdbHandle, sql: &str) -> Result<(), String> { + let sql = sql.to_string(); + run_blocking(handle.clone(), move |conn| conn.execute_batch(&sql).map_err(|e| format!("DuckDB error: {e}"))).await +} + +/// Whether `sql` reads (and so has rows to stream). +pub(crate) fn reads(sql: &str) -> bool { + is_read_query(sql) } fn is_read_query(sql: &str) -> bool { @@ -214,6 +360,191 @@ pub async fn execute_sql_readonly(handle: &DuckdbHandle, sql: &str) -> Result, +) -> Result { + #[derive(Default)] + struct Slot { + stopped: bool, + interrupt: Option>, + } + let slot = std::sync::Arc::new(std::sync::Mutex::new(Slot::default())); + let s = slot.clone(); + let arm = super::stop::Arm::new(cancel, move || { + let mut g = s.lock().unwrap_or_else(|e| e.into_inner()); + g.stopped = true; + if let Some(h) = &g.interrupt { + h.interrupt(); + } + }); + let h = handle.clone(); + let sql = sql.trim().to_string(); + let t0 = Instant::now(); + let read = is_read_query(&sql); + let result = run_blocking(h, move |conn| { + { + let mut g = slot.lock().unwrap_or_else(|e| e.into_inner()); + if g.stopped { + return Err(super::query::QUERY_CANCELLED.into()); + } + g.interrupt = Some(conn.interrupt_handle()); + } + let out = run_on(conn, &sql, read, t0); + slot.lock().unwrap_or_else(|e| e.into_inner()).interrupt = None; + out + }) + .await; + let stopped = arm.disarm(); + match result { + Err(_) if stopped => Err(super::query::QUERY_CANCELLED.into()), + other => other, + } +} + +fn run_on(conn: &::duckdb::Connection, sql: &str, read: bool, t0: Instant) -> Result { + if read { + let mut columns = Vec::new(); + let mut rows: Vec> = Vec::new(); + let mut budget = super::query::CollectBudget::default(); + let mut capped = false; + for_each_row(conn, sql, &[], |c| columns = c, |r| { + let fits = budget.take(&r); + rows.push(r); + capped = !fits; + fits + })?; + let row_count = Some(rows.len() as i64); + let message = capped.then(|| super::query::budget_message(rows.len())); + Ok(SqlResult { columns, rows, row_count, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) + } else { + let affected = conn.execute(sql, []).map_err(|e| format!("DuckDB error: {e}"))?; + Ok(SqlResult { + columns: vec![], + rows: vec![], + row_count: Some(affected as i64), + message: Some(super::query::affected_message(sql, affected as i64)), + query_ms: t0.elapsed().as_millis() as u64, + sql: sql.to_string(), + }) + } +} + +/// One row-returning statement streamed into the console's sink as DuckDB +/// produces it. The driver is synchronous: the blocking thread reads rows and +/// sends them in batches over a small bounded channel, so it never runs far +/// ahead of the window, and a sink that fails (the window went away) stops it. +pub async fn stream_into( + handle: &DuckdbHandle, + sql: &str, + sink: &mut super::query::RowSink, + cancel: tokio::sync::oneshot::Receiver<()>, +) -> Result { + enum Msg { + Columns(Vec), + Rows(Vec>), + } + const BATCH: usize = 1_000; + let slot = std::sync::Arc::new(std::sync::Mutex::new((false, None::>))); + let s = slot.clone(); + let arm = super::stop::Arm::new(cancel, move || { + let mut g = s.lock().unwrap_or_else(|e| e.into_inner()); + g.0 = true; + if let Some(h) = &g.1 { + h.interrupt(); + } + }); + let (tx, mut rx) = tokio::sync::mpsc::channel::(8); + let h = handle.clone(); + let sql_owned = sql.trim().to_string(); + let reader = run_blocking(h, move |conn| { + { + let mut g = slot.lock().unwrap_or_else(|e| e.into_inner()); + if g.0 { + return Err(super::query::QUERY_CANCELLED.into()); + } + g.1 = Some(conn.interrupt_handle()); + } + let mut batch = Vec::with_capacity(BATCH); + let out = for_each_row_streaming( + conn, + &sql_owned, + |c| { + let _ = tx.blocking_send(Msg::Columns(c)); + }, + |r| { + batch.push(r); + if batch.len() < BATCH { + return true; + } + tx.blocking_send(Msg::Rows(std::mem::replace(&mut batch, Vec::with_capacity(BATCH)))).is_ok() + }, + ); + if out.is_ok() && !batch.is_empty() { + let _ = tx.blocking_send(Msg::Rows(batch)); + } + let stop_pressed = || slot.lock().unwrap_or_else(|e| e.into_inner()).0; + let out = match out { + Err(e) if is_spurious_interrupt(&e) && !stop_pressed() => Err(real_error(conn, &sql_owned, e, stop_pressed)), + other => other, + }; + slot.lock().unwrap_or_else(|e| e.into_inner()).1 = None; + out + }); + tokio::pin!(reader); + let t0 = Instant::now(); + let mut columns = Vec::new(); + let mut total = 0usize; + let mut sink_err: Option = None; + let mut reader_out: Option> = None; + loop { + tokio::select! { + msg = rx.recv() => match msg { + Some(Msg::Columns(c)) => columns = c, + Some(Msg::Rows(rows)) => { + if sink_err.is_some() { + continue; + } + for r in rows { + if total == 0 { + if let Err(e) = sink.start(columns.clone()) { sink_err = Some(e); break; } + } + if let Err(e) = sink.push(r) { sink_err = Some(e); break; } + total += 1; + } + if sink_err.is_some() { + // Stop reading: the reader's next send fails. + rx.close(); + } + } + None => break, + }, + out = &mut reader, if reader_out.is_none() => reader_out = Some(out), + } + } + let out = match reader_out { + Some(o) => o, + None => reader.await, + }; + let stopped = arm.disarm(); + if let Some(e) = sink_err { + return Err(e); + } + match out { + Err(_) if stopped => return Err(super::query::QUERY_CANCELLED.into()), + Err(e) => return Err(e), + Ok(()) => {} + } + if total > 0 { + sink.finish()?; + } + Ok(SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + pub async fn execute_sql(handle: &DuckdbHandle, sql: &str) -> Result { let h = handle.clone(); let sql = sql.trim().to_string(); @@ -231,7 +562,7 @@ pub async fn execute_sql(handle: &DuckdbHandle, sql: &str) -> Result Option { #[cfg(test)] mod tests { + + /// A transaction lives on its own connection: the shared one (grid, + /// sidebar) never sees uncommitted rows, and ROLLBACK throws them away. + #[tokio::test] + async fn tx_conn_isolates_and_rolls_back() { + let shared: DuckdbHandle = std::sync::Arc::new(std::sync::Mutex::new(duckdb::Connection::open_in_memory().unwrap())); + batch(&shared, "CREATE TABLE t (id INTEGER)").await.unwrap(); + let tx = open_tx_conn(&shared).await.unwrap(); + batch(&tx, "BEGIN TRANSACTION").await.unwrap(); + batch(&tx, "INSERT INTO t VALUES (1)").await.unwrap(); + let inside = execute_sql(&tx, "SELECT count(*) AS n FROM t").await.unwrap(); + assert_eq!(inside.rows[0][0], serde_json::json!(1)); + let outside = execute_sql(&shared, "SELECT count(*) AS n FROM t").await.unwrap(); + assert_eq!(outside.rows[0][0], serde_json::json!(0)); + batch(&tx, "ROLLBACK").await.unwrap(); + let after = execute_sql(&shared, "SELECT count(*) AS n FROM t").await.unwrap(); + assert_eq!(after.rows[0][0], serde_json::json!(0)); + } + use super::*; use std::sync::{Arc, Mutex}; diff --git a/src-tauri/src/db/dynamodb.rs b/src-tauri/src/db/dynamodb.rs index d1c1b3d8..e146797a 100644 --- a/src-tauri/src/db/dynamodb.rs +++ b/src-tauri/src/db/dynamodb.rs @@ -289,7 +289,7 @@ fn op_allowed(op: &str) -> bool { fn client() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .timeout(Duration::from_secs(60)) .connect_timeout(Duration::from_secs(10)) .build() diff --git a/src-tauri/src/db/elastic.rs b/src-tauri/src/db/elastic.rs index 66003e7b..a102fe09 100644 --- a/src-tauri/src/db/elastic.rs +++ b/src-tauri/src/db/elastic.rs @@ -38,6 +38,13 @@ pub struct EsConfig { /// Accept a self-signed certificate (a local OpenSearch's demo TLS). #[serde(default)] pub insecure: bool, + /// Reach the server through an SSH tunnel (connection::tunnel_to and friends). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + /// The tunnel's local end, when there is one: the URL keeps the server's + /// real name (TLS checks it) and the client resolves that name to here. + #[serde(skip)] + pub via: Option, } impl EsConfig { @@ -54,7 +61,7 @@ fn client(insecure: bool) -> &'static reqwest::Client { static LAX: OnceLock = OnceLock::new(); let cell = if insecure { &LAX } else { &SAFE }; cell.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .timeout(Duration::from_secs(60)) .connect_timeout(Duration::from_secs(10)) .danger_accept_invalid_certs(insecure) @@ -66,7 +73,9 @@ fn client(insecure: bool) -> &'static reqwest::Client { fn base(cfg: &EsConfig) -> Result { let raw = cfg.url.trim().trim_end_matches('/'); let raw = if raw.contains("://") { raw.to_string() } else { format!("http://{raw}") }; - reqwest::Url::parse(&format!("{raw}/")).map_err(|e| format!("Invalid {} URL \"{raw}\": {e}", cfg.label())) + reqwest::Url::parse(&format!("{raw}/")) + .map(|u| super::ssh_tunnel::url_via(u, cfg.via)) + .map_err(|e| format!("Invalid {} URL \"{raw}\": {e}", cfg.label())) } /// Endpoints (`_name` path segments) that only read. The console may call @@ -223,15 +232,64 @@ enum Body<'a> { Ndjson(String), } +tokio::task_local! { + /// The console run's id, sent as X-Opaque-Id so Stop can find its tasks. + static OPAQUE_ID: String; +} + +/// `query`, stoppable on the server. Every request the statement makes +/// carries an X-Opaque-Id; Stop drops the request and cancels the tasks that +/// carry that id. Searches already end when their connection closes, but +/// `_sql`, `_delete_by_query`, `_update_by_query` and the like run on. +pub async fn query_cancellable(cfg: &EsConfig, stmt: &str, stop: &super::stop::Stop) -> Result { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = format!("stroke-{:x}-{:x}", std::process::id(), SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)); + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(OPAQUE_ID.scope(id.clone(), query(cfg, stmt))); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + drop(run); + let _ = tokio::time::timeout(Duration::from_secs(10), cancel_tasks(cfg, &id)).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +/// Cancel every task whose X-Opaque-Id is `id`. Returns how many. +pub async fn cancel_tasks(cfg: &EsConfig, id: &str) -> Result { + let v = send(cfg, "GET", "_tasks?detailed=true&group_by=none", None).await?; + let ids: Vec = v["tasks"] + .as_array() + .map(|t| { + t.iter() + .filter(|t| t["headers"]["X-Opaque-Id"].as_str() == Some(id) && t["cancellable"].as_bool() != Some(false)) + .filter_map(|t| Some(format!("{}:{}", t["node"].as_str()?, t["id"].as_i64()?))) + .collect() + }) + .unwrap_or_default(); + for t in &ids { + let _ = send(cfg, "POST", &format!("_tasks/{t}/_cancel"), None).await; + } + Ok(ids.len()) +} + async fn send(cfg: &EsConfig, method: &str, path: &str, body: Option>) -> Result { let url = base(cfg)?.join(path.trim_start_matches('/')).map_err(|e| format!("Invalid path \"{path}\": {e}"))?; let m = reqwest::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?; - let mut req = client(cfg.insecure).request(m, url); + let host = url.host_str().unwrap_or_default().to_string(); + let mut req = super::ssh_tunnel::http_client(&host, cfg.via, cfg.insecure) + .unwrap_or_else(|| client(cfg.insecure).clone()) + .request(m, url); if let Some(k) = cfg.api_key.as_deref().map(str::trim).filter(|k| !k.is_empty()) { req = req.header("Authorization", format!("ApiKey {k}")); } else if let Some(u) = cfg.user.as_deref().filter(|u| !u.is_empty()) { req = req.basic_auth(u, cfg.password.as_deref()); } + if let Ok(id) = OPAQUE_ID.try_with(Clone::clone) { + req = req.header("X-Opaque-Id", id); + } match body { Some(Body::Json(b)) => req = req.json(b), Some(Body::Ndjson(s)) => req = req.header("Content-Type", "application/x-ndjson").body(s), @@ -264,6 +322,78 @@ async fn send(cfg: &EsConfig, method: &str, path: &str, body: Option>) Ok(v) } +/// A search's plan: the statement run once with `"profile": true`, and the +/// profile drawn as the plan view's tree (search, then each shard, then its +/// Lucene queries and aggregations with their times). Only searches have one. +pub async fn explain_plan(cfg: &EsConfig, stmt: &str) -> Result { + let (index, mut body) = match parse(stmt)? { + Statement::Search { index, body } => (index, body), + Statement::Count { index, body } => (index, json!({ "query": body.get("query").cloned().unwrap_or(json!({"match_all": {}})), "size": 0 })), + Statement::Raw { method, path, body } if (method == "GET" || method == "POST") && path.trim_end_matches('/').ends_with("_search") => { + let index = path.trim_start_matches('/').split('/').next().unwrap_or("").to_string(); + (index, body.unwrap_or(json!({}))) + } + _ => return Err("Explain works on searches: GET index/_search, index.search({...}) or index.count({...})".into()), + }; + if !body.is_object() { + body = json!({}); + } + body["profile"] = json!(true); + let path = if index.is_empty() || index == "_search" { "_search".to_string() } else { format!("{}/_search", enc(&index)) }; + let v = request(cfg, "POST", &path, Some(&body)).await?; + Ok(profile_tree(&v, &index)) +} + +/// A profiled search response → plan tree. Pure, so it is tested on recorded output. +pub fn profile_tree(v: &Value, index: &str) -> Value { + fn ms(nanos: &Value) -> Value { + nanos.as_f64().map(|n| json!((n / 1e6 * 1000.0).round() / 1000.0)).unwrap_or(Value::Null) + } + fn part(q: &Value) -> Value { + let mut n = json!({ + "Node Type": q["type"].as_str().unwrap_or("Query"), + "Filter": q["description"].as_str().unwrap_or(""), + "Actual Total Time": ms(&q["time_in_nanos"]), + }); + if let Some(kids) = q["children"].as_array().filter(|k| !k.is_empty()) { + n["Plans"] = Value::Array(kids.iter().map(part).collect()); + } + n + } + let shards: Vec = v["profile"]["shards"] + .as_array() + .map(|sh| { + sh.iter() + .map(|shard| { + let mut plans: Vec = shard["searches"] + .as_array() + .map(|ss| ss.iter().flat_map(|s| s["query"].as_array().cloned().unwrap_or_default()).map(|q| part(&q)).collect()) + .unwrap_or_default(); + plans.extend(shard["aggregations"].as_array().map(|a| a.iter().map(part).collect::>()).unwrap_or_default()); + let total: f64 = plans.iter().filter_map(|p| p["Actual Total Time"].as_f64()).sum(); + let id = shard["id"].as_str().unwrap_or(""); + // `[node][index][shard]`: the last two say which. + let label = id.split(']').filter(|p| !p.is_empty()).map(|p| p.trim_start_matches('[')).skip(1).collect::>().join(" shard "); + json!({ + "Node Type": "Shard", + "Relation Name": if label.is_empty() { id.to_string() } else { label }, + "Actual Total Time": (total * 1000.0).round() / 1000.0, + "Plans": plans, + }) + }) + .collect() + }) + .unwrap_or_default(); + let hits = v["hits"]["total"]["value"].as_i64().or_else(|| v["hits"]["total"].as_i64()); + json!({ + "Node Type": "Search", + "Relation Name": index, + "Actual Rows": hits, + "Actual Total Time": v["took"].as_f64(), + "Plans": shards, + }) +} + /// What `GET /` says about the server. #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] @@ -850,13 +980,52 @@ mod tests { assert_eq!(urlencoding::encode("a/b"), "a%2Fb"); } + /// Stop on a slow search: while it runs the server lists a task with our + /// X-Opaque-Id, and after Stop none is left. + // STROKE_TEST_ES=http://127.0.0.1:19200 cargo test --lib elastic::tests::live_stop + #[tokio::test] + async fn live_stop_cancels_the_task() { + let Ok(url) = std::env::var("STROKE_TEST_ES") else { return }; + let cfg = EsConfig { ssh: None, via: None, name: "t".into(), url, user: None, password: None, api_key: None, flavor: None, insecure: true }; + let cfg = connect(cfg).await.unwrap(); + let _ = send(&cfg, "DELETE", "stroke_slow", None).await; + let mut nd = String::new(); + for i in 0..20_000 { + nd.push_str(&format!("{{\"index\":{{\"_index\":\"stroke_slow\"}}}}\n{{\"n\":{i}}}\n")); + } + send(&cfg, "POST", "_bulk?refresh=true", Some(Body::Ndjson(nd))).await.unwrap(); + let ours = |v: &Value| -> usize { + v["tasks"].as_array().map(|t| t.iter().filter(|t| t["headers"]["X-Opaque-Id"].as_str().is_some_and(|h| h.starts_with("stroke-"))).count()).unwrap_or(0) + }; + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let probe = cfg.clone(); + let during = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(1500)).await; + let v = send(&probe, "GET", "_tasks?detailed=true&group_by=none", None).await.unwrap(); + let n = ours(&v); + let _ = tx.send(()); + n + }); + let slow = "GET stroke_slow/_search\n{\"query\": {\"script\": {\"script\": \"long x = 0; for (int i = 0; i < 900000; i++) { x += i; } return x > 0;\"}}}"; + let t0 = Instant::now(); + let e = query_cancellable(&cfg, slow, &stop).await.unwrap_err(); + assert_eq!(e, super::super::query::QUERY_CANCELLED); + assert!(during.await.unwrap() > 0, "the search carried our X-Opaque-Id"); + assert!(t0.elapsed() < Duration::from_secs(20)); + tokio::time::sleep(Duration::from_millis(1500)).await; + let v = send(&cfg, "GET", "_tasks?detailed=true&group_by=none", None).await.unwrap(); + assert_eq!(ours(&v), 0, "a task is still running after Stop"); + let _ = send(&cfg, "DELETE", "stroke_slow", None).await; + } + /// Against a local server: `cargo test --lib es_live -- --ignored`, with /// ES_URL (default http://localhost:9200). #[tokio::test] #[ignore] async fn es_live() { let url = std::env::var("ES_URL").unwrap_or_else(|_| "http://localhost:9200".into()); - let cfg = EsConfig { name: "t".into(), url, user: None, password: None, api_key: None, flavor: None, insecure: true }; + let cfg = EsConfig { ssh: None, via: None, name: "t".into(), url, user: None, password: None, api_key: None, flavor: None, insecure: true }; let cfg = connect(cfg).await.unwrap(); request(&cfg, "PUT", "stroke_it/_doc/1?refresh=wait_for", Some(&json!({"level": "error", "ms": 12}))).await.unwrap(); request(&cfg, "PUT", "stroke_it/_doc/2?refresh=wait_for", Some(&json!({"level": "info", "ms": 3}))).await.unwrap(); diff --git a/src-tauri/src/db/explain.rs b/src-tauri/src/db/explain.rs index fccd69ce..15e52cb2 100644 --- a/src-tauri/src/db/explain.rs +++ b/src-tauri/src/db/explain.rs @@ -112,7 +112,17 @@ fn strip_sql(sql: &str) -> &str { /// what gives actual rows and times), so it runs inside a transaction that is /// always rolled back: explaining a DELETE never deletes anything. Without it /// only the planner's estimates come back and nothing runs. -pub async fn explain_pg(pool: &sqlx::PgPool, sql: &str, analyze: bool) -> Result { +/// A Postgres plan that Stop can end. ANALYZE runs the statement for real, so a +/// plan of a 20-minute query took 20 minutes with nothing to press: it now runs +/// in the console's own transaction shape (the statement timeout, and a tag +/// Stop finds the backend by), and Stop cancels it on the server. +pub async fn explain_pg_stoppable( + pool: &sqlx::PgPool, + sql: &str, + analyze: bool, + cancel_rx: Option>, +) -> Result { + use std::sync::atomic::{AtomicBool, Ordering}; let stripped = strip_sql(sql); let q = if analyze { format!("EXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT JSON) {stripped}") @@ -121,14 +131,20 @@ pub async fn explain_pg(pool: &sqlx::PgPool, sql: &str, analyze: bool) -> Result }; // PG returns [{Plan: {...}, "Planning Time": x, "Execution Time": y}] + let cancelled = std::sync::Arc::new(AtomicBool::new(false)); let fetched = async { - let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + let tag = super::query::run_tag(); + let (mut tx, target) = super::query::begin_console_tx(pool, &tag).await?; + super::query::arm_pg_cancel(pool, cancel_rx, cancelled.clone(), target); let out = sqlx::query_as::<_, (serde_json::Value,)>(&q).fetch_one(&mut *tx).await; // Roll back whatever ANALYZE did, success or not. let _ = tx.rollback().await; out.map_err(|e| e.to_string()) } .await; + if cancelled.load(Ordering::Relaxed) { + return Err(super::query::QUERY_CANCELLED.into()); + } let arr = match fetched { Ok(row) => row.0, // CockroachDB speaks the PG wire protocol but rejects PG's EXPLAIN option @@ -397,3 +413,31 @@ pub fn explain_from_sqlite_plan(res: &SqlResult, driver: &str) -> ExplainResult driver: driver.into(), } } + +#[cfg(test)] +mod stop_tests { + // STROKE_TEST_PG_URL=postgres://postgres@127.0.0.1:5433/postgres cargo test --lib explain::stop_tests + #[tokio::test] + async fn explain_analyze_stops_on_the_server() { + let Ok(url) = std::env::var("STROKE_TEST_PG_URL") else { return }; + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(3).connect(&url).await.unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let _ = tx.send(()); + }); + let t = std::time::Instant::now(); + let r = super::explain_pg_stoppable(&pool, "SELECT pg_sleep(30)", true, Some(rx)).await; + assert_eq!(r.unwrap_err(), crate::db::query::QUERY_CANCELLED); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "took {:?}", t.elapsed()); + // Nothing of it is still running on the server. + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM pg_stat_activity WHERE query LIKE 'EXPLAIN (ANALYZE%pg_sleep(30)%' AND state = 'active'") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(left, 0); + // And without Stop it still returns a plan. + let ok = super::explain_pg_stoppable(&pool, "SELECT 1", true, None).await.unwrap(); + assert!(ok.plan.get("Node Type").is_some()); + } +} diff --git a/src-tauri/src/db/firestore.rs b/src-tauri/src/db/firestore.rs index 334244ae..da2dcd74 100644 --- a/src-tauri/src/db/firestore.rs +++ b/src-tauri/src/db/firestore.rs @@ -9,12 +9,10 @@ //! Documents keep Firestore's typed values (`{"stringValue": ...}`) through //! the IPC boundary; the frontend converts them to plain JSON for editing. -use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, engine::general_purpose::STANDARD as B64, Engine as _}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use std::collections::HashMap; -use std::sync::{Mutex, OnceLock}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::sync::OnceLock; +use std::time::Duration; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -57,7 +55,7 @@ fn base_url(cfg: &FirestoreConfig) -> String { fn client() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .timeout(Duration::from_secs(60)) .connect_timeout(Duration::from_secs(10)) .build() @@ -65,136 +63,8 @@ fn client() -> &'static reqwest::Client { }) } -fn now() -> u64 { - SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) -} - -// Access tokens by credential source, with their expiry (unix seconds). -static TOKENS: OnceLock>> = OnceLock::new(); - -fn cached_token(key: &str) -> Option { - let map = TOKENS.get_or_init(Default::default).lock().ok()?; - let (t, exp) = map.get(key)?; - (now() + 120 < *exp).then(|| t.clone()) -} - -fn store_token(key: &str, token: &str, exp: u64) { - if let Ok(mut map) = TOKENS.get_or_init(Default::default).lock() { - map.insert(key.to_string(), (token.to_string(), exp)); - } -} - -#[derive(Deserialize)] -struct ServiceAccount { - client_email: String, - private_key: String, - #[serde(default = "default_token_uri")] - token_uri: String, -} - -fn default_token_uri() -> String { - "https://oauth2.googleapis.com/token".into() -} - -/// PKCS#8 DER from a `-----BEGIN PRIVATE KEY-----` block. -fn pem_to_der(pem: &str) -> Result, String> { - let body: String = pem - .lines() - .map(str::trim) - .filter(|l| !l.starts_with("-----") && !l.is_empty()) - .collect(); - B64.decode(body).map_err(|e| format!("The key file's private_key is not valid PEM: {e}")) -} - -/// A signed JWT for the OAuth2 JWT-bearer grant. -pub fn sign_jwt(sa_email: &str, private_key_pem: &str, token_uri: &str, iat: u64) -> Result { - let header = B64URL.encode(br#"{"alg":"RS256","typ":"JWT"}"#); - let claims = B64URL.encode( - json!({ - "iss": sa_email, - "scope": "https://www.googleapis.com/auth/datastore", - "aud": token_uri, - "iat": iat, - "exp": iat + 3600, - }) - .to_string(), - ); - let input = format!("{header}.{claims}"); - let der = pem_to_der(private_key_pem)?; - let key = ring::signature::RsaKeyPair::from_pkcs8(&der).map_err(|e| format!("The key file's private key was rejected: {e}"))?; - let mut sig = vec![0u8; key.public().modulus_len()]; - key.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), input.as_bytes(), &mut sig) - .map_err(|_| "Could not sign with the service account key".to_string())?; - Ok(format!("{input}.{}", B64URL.encode(sig))) -} - -async fn service_account_token(path: &str) -> Result { - let key = format!("sa:{path}"); - if let Some(t) = cached_token(&key) { - return Ok(t); - } - let raw = std::fs::read_to_string(path).map_err(|e| format!("Could not read the key file {path}: {e}"))?; - let sa: ServiceAccount = serde_json::from_str(&raw).map_err(|e| format!("{path} is not a service account key: {e}"))?; - let jwt = sign_jwt(&sa.client_email, &sa.private_key, &sa.token_uri, now())?; - let resp = client() - .post(&sa.token_uri) - .form(&[("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), ("assertion", jwt.as_str())]) - .send() - .await - .map_err(|e| format!("Could not reach Google's token service: {e}"))?; - let status = resp.status(); - let v: Value = resp.json().await.map_err(|e| e.to_string())?; - if !status.is_success() { - return Err(format!( - "Google refused the service account: {}", - v.get("error_description").or_else(|| v.get("error")).and_then(|e| e.as_str()).unwrap_or("unknown error") - )); - } - let token = v["access_token"].as_str().ok_or("No access_token in Google's reply")?.to_string(); - store_token(&key, &token, now() + v["expires_in"].as_u64().unwrap_or(3600)); - Ok(token) -} - -async fn gcloud_token() -> Result { - if let Some(t) = cached_token("gcloud") { - return Ok(t); - } - let mut cmd = tokio::process::Command::new("gcloud"); - cmd.args(["auth", "print-access-token"]).kill_on_drop(true); - crate::proc::quiet(&mut cmd); - let fut = cmd.output(); - let out = tokio::time::timeout(Duration::from_secs(20), fut) - .await - .map_err(|_| "gcloud did not answer in time".to_string())? - .map_err(|e| { - if e.kind() == std::io::ErrorKind::NotFound { - "The gcloud CLI is not installed; use a service account key file instead".to_string() - } else { - e.to_string() - } - })?; - if !out.status.success() { - return Err(format!( - "gcloud has no login: {} Run `gcloud auth login` and try again.", - String::from_utf8_lossy(&out.stderr).trim() - )); - } - let token = String::from_utf8_lossy(&out.stdout).trim().to_string(); - // print-access-token doesn't say when it expires; its tokens last an hour. - store_token("gcloud", &token, now() + 3000); - Ok(token) -} - async fn token(cfg: &FirestoreConfig) -> Result { - match cfg.auth.as_str() { - "emulator" => Ok("owner".into()), - "serviceAccount" => { - let path = cfg.key_file.as_deref().map(str::trim).filter(|p| !p.is_empty()).ok_or("Pick a service account key file")?; - service_account_token(path).await - } - "gcloud" => gcloud_token().await, - other => Err(format!("Unknown sign-in \"{other}\"")), - } + super::google_auth::token(&cfg.auth, cfg.key_file.as_deref(), super::google_auth::SCOPE_DATASTORE).await } /// Only document paths under this database, and only document operations. @@ -447,6 +317,7 @@ pub async fn query(cfg: &FirestoreConfig, stmt: &str) -> Result FirestoreConfig { @@ -503,14 +374,14 @@ mod tests { fn jwt_signs_with_a_pkcs8_key() { // Throwaway 2048-bit test key (not used anywhere). let pem = include_str!("../../tests/fixtures/test-rsa-key.pem"); - let jwt = sign_jwt("sa@x.iam.gserviceaccount.com", pem, "https://oauth2.googleapis.com/token", 1_700_000_000).unwrap(); + let jwt = super::super::google_auth::sign_jwt("sa@x.iam.gserviceaccount.com", pem, "https://oauth2.googleapis.com/token", 1_700_000_000, super::super::google_auth::SCOPE_DATASTORE).unwrap(); let parts: Vec<&str> = jwt.split('.').collect(); assert_eq!(parts.len(), 3); let claims: Value = serde_json::from_slice(&B64URL.decode(parts[1]).unwrap()).unwrap(); assert_eq!(claims["iss"], "sa@x.iam.gserviceaccount.com"); assert_eq!(claims["exp"], 1_700_003_600u64); assert_eq!(B64URL.decode(parts[2]).unwrap().len(), 256); - assert!(sign_jwt("x", "-----BEGIN PRIVATE KEY-----\nnope\n-----END PRIVATE KEY-----", "u", 0).is_err()); + assert!(super::super::google_auth::sign_jwt("x", "-----BEGIN PRIVATE KEY-----\nnope\n-----END PRIVATE KEY-----", "u", 0, super::super::google_auth::SCOPE_DATASTORE).is_err()); } /// Against the dev/nosql Firestore emulator (port 8086): diff --git a/src-tauri/src/db/geo.rs b/src-tauri/src/db/geo.rs index 8e20b718..25bb4291 100644 --- a/src-tauri/src/db/geo.rs +++ b/src-tauri/src/db/geo.rs @@ -72,7 +72,7 @@ pub struct GeoFeatures { /// "clusters" - grid-collapsed points carrying a `count`. The viewport held /// more rows than could be drawn. pub mode: String, - pub features: Vec, + pub features: Vec, /// Rows matching the filter inside the viewport. pub matched: i64, pub returned: i64, @@ -88,6 +88,17 @@ pub struct GeoFeatures { pub sql: String, } +/// One GeoJSON feature. The geometry is PostGIS's own `ST_AsGeoJSON` text, +/// passed through as is: parsing it into a JSON tree only to print it again +/// was most of the serialization time for a few thousand polygons. +#[derive(Serialize)] +pub struct MapFeature { + #[serde(rename = "type")] + pub kind: &'static str, + pub geometry: Box, + pub properties: Value, +} + /// PostGIS puts its own tables in these schemas; they are plumbing, not data. const HIDDEN_SCHEMAS: &str = "('information_schema', 'pg_catalog', 'topology', 'tiger', 'tiger_data')"; @@ -391,6 +402,27 @@ pub async fn geo_features( let Some(pool) = pg_pool(&state)? else { return Err("The map view is only available on PostgreSQL with PostGIS".into()); }; + features_on(&pool, schema, table, column, kind, srid, geom_type, bbox, limit, simplify, cluster_cell, filters, include_extent).await +} + +/// `geo_features` on a pool, for the command and the tests. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn features_on( + pool: &PgPool, + schema: String, + table: String, + column: String, + kind: String, + srid: i32, + geom_type: String, + bbox: Option, + limit: i64, + simplify: f64, + cluster_cell: f64, + filters: Option>, + include_extent: bool, +) -> Result { + let pool = pool.clone(); let started = std::time::Instant::now(); super::schema::validate_ident(&schema)?; @@ -440,15 +472,19 @@ pub async fn geo_features( let connector = if where_clause.sql.is_empty() && bbox.is_none() { " WHERE" } else { " AND" }; let scope = format!("{}{viewport}{connector} {quoted} IS NOT NULL", where_clause.sql); - let count_sql = format!("SELECT COUNT(*)::bigint FROM {table_ref}{scope}"); - let matched: i64 = bind_scope(&count_sql, &where_clause.binds, bbox) + // Only whether the viewport holds more than `limit` rows decides the mode, + // so the count stops at limit + 1. Counting a whole viewport on a big table + // was a full index scan on every pan, before any feature was fetched. The + // exact number, when it's larger, comes from the clusters' own counts. + let count_sql = format!("SELECT COUNT(*)::bigint FROM (SELECT 1 FROM {table_ref}{scope} LIMIT {}) capped", limit + 1); + let capped: i64 = bind_scope(&count_sql, &where_clause.binds, bbox) .fetch_one(&pool) .await .and_then(|r| r.try_get::(0)) .map_err(|e| format!("Failed to count features: {e}"))?; let safe = geojson_expr(&wgs84_expr("ed, &kind, srid), &geom_type); - let cluster = matched > limit; + let cluster = capped > limit; let data_sql = if cluster { // One weighted point per grid cell. Snapping the centroid rather than the @@ -470,7 +506,8 @@ pub async fn geo_features( let cell_merc = cell.to_radians(); format!( "SELECT ST_AsGeoJSON(ST_SetSRID(ST_MakePoint(avg(x), avg(y)), 4326), 6) AS geometry, \ - COUNT(*)::bigint AS n \ + COUNT(*)::bigint AS n, \ + (SUM(COUNT(*)) OVER ())::bigint AS total \ FROM (SELECT x, y, \ ST_SnapToGrid(ST_MakePoint(x, ln(tan(pi()/4 + radians(y)/2))), \ {cell}, {cell_merc}) AS cell \ @@ -515,17 +552,24 @@ pub async fn geo_features( .await .map_err(|e| format!("Failed to fetch map features: {e}"))?; - let features: Vec = rows + // Clustered, every row carries the viewport's total (a window over the + // groups, before LIMIT); otherwise the rows are all there is. + let matched = if cluster { + rows.first().and_then(|r| r.try_get::(2).ok()).unwrap_or(capped) + } else { + rows.len() as i64 + }; + let features: Vec = rows .iter() .filter_map(|r| { let raw: String = r.try_get(0).ok()?; - let geometry: Value = serde_json::from_str(&raw).ok()?; + let geometry = serde_json::value::RawValue::from_string(raw).ok()?; let properties = if cluster { json!({ "count": r.try_get::(1).unwrap_or(0) }) } else { r.try_get::(1).unwrap_or_else(|_| json!({})) }; - Some(json!({ "type": "Feature", "geometry": geometry, "properties": properties })) + Some(MapFeature { kind: "Feature", geometry, properties }) }) .collect(); @@ -549,3 +593,46 @@ pub async fn geo_features( sql: format!("{data_sql}\n{count_sql}"), }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Against PostGIS: STROKE_TEST_POSTGIS = a postgres:// URL with the + /// `public.pings` (100,000 points) and `schools.areas` tables. + #[tokio::test] + async fn live_features() { + let Ok(url) = std::env::var("STROKE_TEST_POSTGIS") else { return }; + let pool = PgPool::connect(&url).await.unwrap(); + let fetch = |table: &str, schema: &str, column: &str, bbox: Option, limit: i64| { + features_on(&pool, schema.into(), table.into(), column.into(), "geometry".into(), 4326, "POINT".into(), bbox, limit, 0.0, 0.05, None, false) + }; + // More rows than the budget: clusters, with the exact total. + let all = fetch("pings", "public", "geom", None, 8000).await.unwrap(); + assert_eq!(all.mode, "clusters"); + assert_eq!(all.matched, 100_000); + assert_eq!(all.features.iter().map(|f| f.properties["count"].as_i64().unwrap()).sum::(), 100_000); + // A small window: every row, as features with their columns. + let small = GeoBbox { min_x: -0.5, min_y: 51.2, max_x: -0.49, max_y: 51.21 }; + let few = fetch("pings", "public", "geom", Some(small), 8000).await.unwrap(); + assert_eq!(few.mode, "features"); + assert_eq!(few.matched, few.returned); + assert!(few.matched > 0 && few.matched < 8000, "{}", few.matched); + // The geometry is passed through as GeoJSON text. + let json = serde_json::to_value(&few.features[0]).unwrap(); + assert_eq!(json["type"], "Feature"); + assert_eq!(json["geometry"]["type"], "Point"); + assert!(json["properties"]["device"].is_string()); + // Exactly at the budget is still features. + let at = fetch("pings", "public", "geom", Some(small), few.matched).await.unwrap(); + assert_eq!(at.mode, "features"); + let over = fetch("pings", "public", "geom", Some(small), few.matched - 1).await.unwrap(); + assert_eq!(over.mode, "clusters"); + assert_eq!(over.matched, few.matched); + // Polygons. + let areas = features_on(&pool, "schools".into(), "areas".into(), "boundary".into(), "geometry".into(), 4326, "POLYGON".into(), None, 8000, 0.0, 0.05, None, true).await.unwrap(); + assert_eq!(areas.mode, "features"); + assert_eq!(serde_json::to_value(&areas.features[0]).unwrap()["geometry"]["type"], "Polygon"); + assert!(areas.extent.is_some()); + } +} diff --git a/src-tauri/src/db/google_auth.rs b/src-tauri/src/db/google_auth.rs new file mode 100644 index 00000000..2d0a5ad1 --- /dev/null +++ b/src-tauri/src/db/google_auth.rs @@ -0,0 +1,176 @@ +//! Signing in to Google Cloud APIs, shared by Firestore, Spanner and BigQuery. +//! +//! - `emulator`: a local emulator; any token is accepted (`Bearer owner`). +//! - `serviceAccount`: a JSON key file. The app signs a JWT with the key +//! (RS256, `ring`) and trades it for an access token at Google's token URL. +//! - `gcloud`: the gcloud CLI's own login (`gcloud auth print-access-token`). +//! +//! Tokens are cached per credential and scope until two minutes before they +//! expire. + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, engine::general_purpose::STANDARD as B64, Engine as _}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// Firestore's scope. +pub const SCOPE_DATASTORE: &str = "https://www.googleapis.com/auth/datastore"; +/// Spanner and BigQuery: data and schema. +pub const SCOPE_CLOUD_PLATFORM: &str = "https://www.googleapis.com/auth/cloud-platform"; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .timeout(Duration::from_secs(30)) + .connect_timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default() + }) +} + +pub(crate) fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +// Access tokens by credential source, with their expiry (unix seconds). +static TOKENS: OnceLock>> = OnceLock::new(); + +fn cached_token(key: &str) -> Option { + let map = TOKENS.get_or_init(Default::default).lock().ok()?; + let (t, exp) = map.get(key)?; + (now() + 120 < *exp).then(|| t.clone()) +} + +fn store_token(key: &str, token: &str, exp: u64) { + if let Ok(mut map) = TOKENS.get_or_init(Default::default).lock() { + map.insert(key.to_string(), (token.to_string(), exp)); + } +} + +#[derive(Deserialize)] +struct ServiceAccount { + client_email: String, + private_key: String, + #[serde(default = "default_token_uri")] + token_uri: String, +} + +fn default_token_uri() -> String { + "https://oauth2.googleapis.com/token".into() +} + +/// PKCS#8 DER from a `-----BEGIN PRIVATE KEY-----` block. +fn pem_to_der(pem: &str) -> Result, String> { + let body: String = pem + .lines() + .map(str::trim) + .filter(|l| !l.starts_with("-----") && !l.is_empty()) + .collect(); + B64.decode(body).map_err(|e| format!("The key file's private_key is not valid PEM: {e}")) +} + +/// A signed JWT for the OAuth2 JWT-bearer grant. +pub fn sign_jwt(sa_email: &str, private_key_pem: &str, token_uri: &str, iat: u64, scope: &str) -> Result { + let header = B64URL.encode(br#"{"alg":"RS256","typ":"JWT"}"#); + let claims = B64URL.encode( + json!({ + "iss": sa_email, + "scope": scope, + "aud": token_uri, + "iat": iat, + "exp": iat + 3600, + }) + .to_string(), + ); + let input = format!("{header}.{claims}"); + let der = pem_to_der(private_key_pem)?; + let key = ring::signature::RsaKeyPair::from_pkcs8(&der).map_err(|e| format!("The key file's private key was rejected: {e}"))?; + let mut sig = vec![0u8; key.public().modulus_len()]; + key.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), input.as_bytes(), &mut sig) + .map_err(|_| "Could not sign with the service account key".to_string())?; + Ok(format!("{input}.{}", B64URL.encode(sig))) +} + +async fn service_account_token(path: &str, scope: &str) -> Result { + let key = format!("sa:{scope}:{path}"); + if let Some(t) = cached_token(&key) { + return Ok(t); + } + let raw = std::fs::read_to_string(path).map_err(|e| format!("Could not read the key file {path}: {e}"))?; + let sa: ServiceAccount = serde_json::from_str(&raw).map_err(|e| format!("{path} is not a service account key: {e}"))?; + let jwt = sign_jwt(&sa.client_email, &sa.private_key, &sa.token_uri, now(), scope)?; + let resp = client() + .post(&sa.token_uri) + .form(&[("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), ("assertion", jwt.as_str())]) + .send() + .await + .map_err(|e| format!("Could not reach Google's token service: {e}"))?; + let status = resp.status(); + let v: Value = resp.json().await.map_err(|e| e.to_string())?; + if !status.is_success() { + return Err(format!( + "Google refused the service account: {}", + v.get("error_description").or_else(|| v.get("error")).and_then(|e| e.as_str()).unwrap_or("unknown error") + )); + } + let token = v["access_token"].as_str().ok_or("No access_token in Google's reply")?.to_string(); + store_token(&key, &token, now() + v["expires_in"].as_u64().unwrap_or(3600)); + Ok(token) +} + +async fn gcloud_token() -> Result { + if let Some(t) = cached_token("gcloud") { + return Ok(t); + } + let mut cmd = tokio::process::Command::new("gcloud"); + cmd.args(["auth", "print-access-token"]).kill_on_drop(true); + crate::proc::quiet(&mut cmd); + let fut = cmd.output(); + let out = tokio::time::timeout(Duration::from_secs(20), fut) + .await + .map_err(|_| "gcloud did not answer in time".to_string())? + .map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + "The gcloud CLI is not installed; use a service account key file instead".to_string() + } else { + e.to_string() + } + })?; + if !out.status.success() { + return Err(format!( + "gcloud has no login: {} Run `gcloud auth login` and try again.", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + let token = String::from_utf8_lossy(&out.stdout).trim().to_string(); + // print-access-token doesn't say when it expires; its tokens last an hour. + store_token("gcloud", &token, now() + 3000); + Ok(token) +} + +/// An access token for `auth` ("emulator", "serviceAccount" or "gcloud"). The +/// gcloud login carries its own scopes; a service account asks for `scope`. +pub async fn token(auth: &str, key_file: Option<&str>, scope: &str) -> Result { + match auth { + "emulator" => Ok("owner".into()), + "serviceAccount" => { + let path = key_file.map(str::trim).filter(|p| !p.is_empty()).ok_or("Pick a service account key file")?; + service_account_token(path, scope).await + } + "gcloud" => gcloud_token().await, + other => Err(format!("Unknown sign-in \"{other}\"")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_bad_key_is_refused() { + assert!(sign_jwt("x", "-----BEGIN PRIVATE KEY-----\nnope\n-----END PRIVATE KEY-----", "u", 0, SCOPE_CLOUD_PLATFORM).is_err()); + } +} diff --git a/src-tauri/src/db/import.rs b/src-tauri/src/db/import.rs index cb9978f4..9e87289f 100644 --- a/src-tauri/src/db/import.rs +++ b/src-tauri/src/db/import.rs @@ -177,6 +177,10 @@ pub async fn import_rows( Err("Importing rows is not supported for ClickHouse. Use INSERT INTO … in the SQL console.".into()) } ActiveConnection::Posthog(_) => Err("PostHog is read-only: its data comes from HogQL queries.".into()), + c @ (ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_)) => { + let eng = super::backup::SqlEngine::of(&c).ok_or("Not an API engine")?; + import_api(&app, &eng, schema.as_deref(), &table, &columns, &rows, &opts).await + } ActiveConnection::Redis(_) => Err("Importing rows is not supported on Redis".into()), ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Err("Importing rows is not supported on DynamoDB".into()), }?; @@ -201,6 +205,91 @@ pub async fn import_rows( /// Postgres and MySQL both cap a statement's parameters at 65535, so a wide /// table needs a smaller batch than a narrow one or the statement is rejected /// outright. +/// Spanner, BigQuery, Snowflake and ODBC: INSERTs written in the engine's own +/// literal syntax, typed by the table's columns, run batch by batch. These +/// commit each statement on its own, so "all or nothing" stops at the first +/// failed batch and says how many rows already went in, rather than claiming a +/// rollback it cannot make. +async fn import_api( + app: &AppHandle, + eng: &super::backup::SqlEngine, + schema: Option<&str>, + table: &str, + columns: &[String], + rows: &[Vec], + opts: &ImportOptions, +) -> Result { + if opts.conflict != ConflictMode::Error { + return Err(format!( + "{} imports insert new rows only for now: skipping or updating on a conflict needs a MERGE this import doesn't write yet", + eng.label() + )); + } + let schema = match schema.map(str::trim).filter(|s| !s.is_empty()) { + Some(s) => s.to_string(), + None => eng.schemas().await?.into_iter().next().unwrap_or_default(), + }; + let structure = eng.columns(&schema, table).await?; + let types: Vec = columns + .iter() + .map(|c| structure.iter().find(|s| &s.name == c).map(|s| s.data_type.clone()).ok_or_else(|| format!("{table} has no column named {c}"))) + .collect::>()?; + let style = eng.style(); + let target = eng.table_ref(&schema, table); + let col_sql = columns.iter().map(|c| eng.quote(c)).collect::>().join(", "); + let lits = |row: &Vec| -> String { + row.iter().zip(&types).map(|(v, t)| super::backup::value_lit(v, t, style)).collect::>().join(", ") + }; + let per_batch = opts.batch_size.clamp(1, 200); + let mut inserted = 0usize; + let mut errors: Vec = Vec::new(); + for (batch_no, batch) in rows.chunks(per_batch).enumerate() { + if is_cancelled() { break; } + let base = batch_no * per_batch; + let values: Vec = batch.iter().map(lits).collect(); + match eng.exec(&super::backup::insert_stmt(&target, &col_sql, &values, style)).await { + Ok(()) => inserted += batch.len(), + Err(batch_err) => { + if opts.abort_on_error { + return Ok(ImportRowsResult { + inserted, + failed: 1, + skipped: rows.len() - inserted, + cancelled: false, + rolled_back: false, + errors: vec![RowError { + row: base + 1, + message: format!( + "{batch_err} (rows {}-{}). {} commits each batch, so the {inserted} row(s) before these stay imported.", + base + 1, + base + batch.len(), + eng.label() + ), + }], + }); + } + for (i, row) in batch.iter().enumerate() { + if is_cancelled() { break; } + match eng.exec(&super::backup::insert_stmt(&target, &col_sql, &[lits(row)], style)).await { + Ok(()) => inserted += 1, + Err(e) => errors.push(RowError { row: base + i + 1, message: e }), + } + } + } + } + emit_progress(app, (inserted + errors.len()).min(rows.len()), rows.len()); + } + let cancelled = is_cancelled(); + Ok(ImportRowsResult { + skipped: rows.len().saturating_sub(inserted + errors.len()), + inserted, + failed: errors.len(), + cancelled, + rolled_back: false, + errors, + }) +} + fn rows_per_batch(requested: usize, columns: usize) -> usize { let cap = if columns == 0 { 1 } else { 65535 / columns.max(1) }; requested.clamp(1, cap.max(1)) diff --git a/src-tauri/src/db/influx.rs b/src-tauri/src/db/influx.rs new file mode 100644 index 00000000..16f2c45f --- /dev/null +++ b/src-tauri/src/db/influx.rs @@ -0,0 +1,664 @@ +//! InfluxDB 1.x, 2.x and 3.x over HTTP. Beta, and read-only. +//! +//! Measurements are the collections and points the documents (one row per +//! timestamp and series, fields and tags as columns, newest first). +//! +//! - 3.x (Core, Enterprise, Cloud Dedicated/Serverless): SQL through +//! `/api/v3/query_sql`. The console takes SQL, or InfluxQL after `influxql:`. +//! - 2.x and Cloud TSM: the console takes Flux or InfluxQL; the browser uses +//! InfluxQL through the 1.x compatibility API (`/query`). +//! - 1.x: InfluxQL. +//! +//! Nothing here writes. The console refuses InfluxQL other than SELECT, SHOW +//! and EXPLAIN, and Flux that writes (`to()`) or reaches out of the database +//! (`http.post`, `sql`, notification packages). + +use super::query::{ColumnInfo, SqlResult}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InfluxConfig { + pub name: String, + pub url: String, + /// "1", "2" or "3". + #[serde(default = "default_version")] + pub version: String, + /// The bucket (2.x) or database (1.x, 3.x). + pub database: String, + /// The organization (2.x only). + #[serde(default)] + pub org: Option, + /// API token (2.x, 3.x). + #[serde(default)] + pub token: Option, + /// User and password (1.x). + #[serde(default)] + pub user: Option, + #[serde(default)] + pub password: Option, +} + +fn default_version() -> String { + "2".into() +} + +const MAX_ROWS: usize = 10_000; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| crate::proxy::http_builder(crate::proxy::Kind::Database).timeout(Duration::from_secs(120)).connect_timeout(Duration::from_secs(10)).build().unwrap_or_default()) +} + +fn base(cfg: &InfluxConfig) -> String { + let u = cfg.url.trim().trim_end_matches('/'); + if u.contains("://") { u.to_string() } else { format!("http://{u}") } +} + +fn v3(cfg: &InfluxConfig) -> bool { + cfg.version.trim() == "3" +} + +fn auth(cfg: &InfluxConfig, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + if let Some(t) = cfg.token.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + // 2.x reads "Token", 3.x "Bearer"; both take the other too. + return req.header("Authorization", if v3(cfg) { format!("Bearer {t}") } else { format!("Token {t}") }); + } + match cfg.user.as_deref().filter(|u| !u.is_empty()) { + Some(u) => req.basic_auth(u, cfg.password.as_deref()), + None => req, + } +} + +async fn send(cfg: &InfluxConfig, req: reqwest::RequestBuilder) -> Result { + let resp = auth(cfg, req).send().await.map_err(|e| { + if e.is_connect() { + format!("Could not reach InfluxDB at {}: is it running?", base(cfg)) + } else { + format!("InfluxDB request failed: {e}") + } + })?; + let status = resp.status().as_u16(); + let text = resp.text().await.map_err(|e| e.to_string())?; + if status == 401 || status == 403 { + return Err("InfluxDB refused the credentials (check the token, or the user and password)".into()); + } + if status >= 400 { + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + let msg = v["message"].as_str().or_else(|| v["error"].as_str()).map(String::from).unwrap_or_else(|| text.chars().take(300).collect()); + return Err(format!("InfluxDB: {msg}")); + } + Ok(text) +} + +// ── The three query paths ───────────────────────────────────────────────────── + +/// A table: column names, then rows. +type Table = (Vec, Vec>); + +/// InfluxQL through `/query` (1.x, and 2.x's compatibility API); series are +/// flattened, their tags becoming columns. +async fn influxql(cfg: &InfluxConfig, q: &str) -> Result { + if v3(cfg) { + let req = client().post(format!("{}/api/v3/query_influxql", base(cfg))).json(&json!({ "db": cfg.database.trim(), "q": q, "format": "json" })); + return json_rows(&send(cfg, req).await?); + } + // Times come back as RFC 3339 strings (no `epoch`). + let req = client().get(format!("{}/query", base(cfg))).query(&[("db", cfg.database.trim()), ("q", q)]); + let text = send(cfg, req).await?; + let v: Value = serde_json::from_str(&text).map_err(|e| format!("InfluxDB answered something unexpected: {e}"))?; + let mut cols: Vec = Vec::new(); + let mut rows: Vec> = Vec::new(); + for res in v["results"].as_array().into_iter().flatten() { + if let Some(e) = res["error"].as_str() { + return Err(format!("InfluxDB: {e}")); + } + for s in res["series"].as_array().into_iter().flatten() { + let tags: Vec<(String, Value)> = s["tags"].as_object().map(|t| t.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default(); + let names: Vec = s["columns"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(String::from)).collect(); + for n in names.iter().chain(tags.iter().map(|(k, _)| k)) { + if !cols.contains(n) { + cols.push(n.clone()); + } + } + for r in s["values"].as_array().into_iter().flatten() { + let mut row = vec![Value::Null; cols.len()]; + for (i, n) in names.iter().enumerate() { + let at = cols.iter().position(|c| c == n).unwrap(); + row[at] = r[i].clone(); + } + for (k, v) in &tags { + let at = cols.iter().position(|c| c == k).unwrap(); + row[at] = v.clone(); + } + rows.push(row); + } + } + } + for r in &mut rows { + r.resize(cols.len(), Value::Null); + } + Ok((cols, rows)) +} + +/// Rows of JSON objects (3.x), `time` first. +fn json_rows(text: &str) -> Result { + let v: Value = serde_json::from_str(text).map_err(|e| format!("InfluxDB answered something unexpected: {e}"))?; + let objs = v.as_array().cloned().unwrap_or_default(); + let mut cols: Vec = Vec::new(); + for o in &objs { + for k in o.as_object().into_iter().flat_map(|m| m.keys()) { + if !cols.contains(k) { + cols.push(k.clone()); + } + } + } + if let Some(i) = cols.iter().position(|c| c == "time") { + let t = cols.remove(i); + cols.insert(0, t); + } + let rows = objs.iter().map(|o| cols.iter().map(|c| o.get(c).cloned().unwrap_or(Value::Null)).collect()).collect(); + Ok((cols, rows)) +} + +async fn sql(cfg: &InfluxConfig, q: &str) -> Result { + let req = client().post(format!("{}/api/v3/query_sql", base(cfg))).json(&json!({ "db": cfg.database.trim(), "q": q, "format": "json" })); + json_rows(&send(cfg, req).await?) +} + +/// Flux (2.x): annotated CSV, every table of the result stacked. +async fn flux(cfg: &InfluxConfig, q: &str) -> Result { + let org = cfg.org.as_deref().map(str::trim).unwrap_or(""); + let req = client() + .post(format!("{}/api/v2/query", base(cfg))) + .query(&[("org", org)]) + .header("Accept", "application/csv") + .json(&json!({ "query": q, "type": "flux", "dialect": { "header": true, "annotations": ["datatype"], "delimiter": "," } })); + Ok(flux_csv(&send(cfg, req).await?)) +} + +/// Split one CSV line, honouring double quotes. +fn csv_line(line: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quoted = false; + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' if quoted && chars.peek() == Some(&'"') => { + cur.push('"'); + chars.next(); + } + '"' => quoted = !quoted, + ',' if !quoted => out.push(std::mem::take(&mut cur)), + c => cur.push(c), + } + } + out.push(cur); + out +} + +/// Split CSV text into records: a newline inside quotes stays in the field. +fn csv_records(text: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quoted = false; + for c in text.chars() { + match c { + '"' => { + quoted = !quoted; + cur.push(c); + } + '\n' if !quoted => out.push(std::mem::take(&mut cur).trim_end_matches('\r').to_string()), + c => cur.push(c), + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +fn typed(kind: &str, s: &str) -> Value { + if s.is_empty() { + return Value::Null; + } + match kind { + "long" => s.parse::().map(Value::from).unwrap_or_else(|_| json!(s)), + "unsignedLong" => s.parse::().map(Value::from).unwrap_or_else(|_| json!(s)), + "double" => s.parse::().ok().and_then(|f| serde_json::Number::from_f64(f).map(Value::Number)).unwrap_or_else(|| json!(s)), + "boolean" => json!(s == "true"), + _ => json!(s), + } +} + +/// Annotated CSV: each table brings its `#datatype` row and header. The +/// `result` and `table` bookkeeping columns are left out. +pub fn flux_csv(text: &str) -> Table { + let mut cols: Vec = Vec::new(); + let mut rows: Vec> = Vec::new(); + let mut kinds: Vec = Vec::new(); + let mut header: Option> = None; + for line in csv_records(text) { + if line.trim().is_empty() { + header = None; + continue; + } + let cells = csv_line(&line); + if cells.first().is_some_and(|c| c == "#datatype") { + kinds = cells; + header = None; + continue; + } + if cells.first().is_some_and(|c| c.starts_with('#')) { + continue; + } + let Some(h) = &header else { + for n in cells.iter().skip(1) { + if !n.is_empty() && n != "result" && n != "table" && !cols.contains(n) { + cols.push(n.clone()); + } + } + header = Some(cells); + continue; + }; + let mut row = vec![Value::Null; cols.len()]; + for (i, n) in h.iter().enumerate().skip(1) { + if let Some(at) = cols.iter().position(|c| c == n) { + row[at] = typed(kinds.get(i).map(String::as_str).unwrap_or("string"), cells.get(i).map(String::as_str).unwrap_or("")); + } + } + rows.push(row); + } + for r in &mut rows { + r.resize(cols.len(), Value::Null); + } + (cols, rows) +} + +// ── Reads only ──────────────────────────────────────────────────────────────── + +#[derive(Debug, PartialEq)] +pub enum Lang { + Sql, + InfluxQl, + Flux, +} + +/// Which language a console statement is in, for this server. +pub fn lang_of(cfg: &InfluxConfig, stmt: &str) -> (Lang, String) { + let s = stmt.trim(); + if let Some(rest) = s.strip_prefix("influxql:").or_else(|| s.strip_prefix("INFLUXQL:")) { + return (Lang::InfluxQl, rest.trim().to_string()); + } + if s.contains("|>") || s.starts_with("from(") || s.starts_with("import ") || s.starts_with("buckets(") { + return (Lang::Flux, s.to_string()); + } + (if v3(cfg) { Lang::Sql } else { Lang::InfluxQl }, s.to_string()) +} + +/// Strings and comments out, so they can't hide or fake a keyword. +fn bare(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' | '\'' => { + while let Some(d) = chars.next() { + if d == '\\' { + chars.next(); + } else if d == c { + break; + } + } + out.push(' '); + } + '/' if chars.peek() == Some(&'/') => { + for d in chars.by_ref() { + if d == '\n' { + break; + } + } + out.push('\n'); + } + '-' if chars.peek() == Some(&'-') => { + for d in chars.by_ref() { + if d == '\n' { + break; + } + } + out.push('\n'); + } + c => out.push(c), + } + } + out +} + +/// Flux packages that only compute or read this database. +const FLUX_IMPORTS: &[&str] = &[ + "influxdata/influxdb/schema", "influxdata/influxdb/v1", "strings", "math", "date", "regexp", "array", "join", "types", + "timezone", "interpolate", "experimental", "experimental/aggregate", "experimental/array", "experimental/table", "dict", "universe", +]; + +/// Why the console won't run this, if it won't: the engine is read-only. +pub fn refusal(lang: &Lang, stmt: &str) -> Option { + match lang { + Lang::Flux => { + for line in stmt.lines().map(str::trim).filter(|l| l.starts_with("import")) { + let pkg = line.trim_start_matches("import").trim().trim_matches('"'); + if !FLUX_IMPORTS.contains(&pkg) { + return Some(format!("The Flux package \"{pkg}\" can write or reach other systems; InfluxDB is read-only here")); + } + } + let b = bare(stmt); + let writes = regex_lite_to(&b); + writes.then(|| "This Flux writes (to()); InfluxDB is read-only here".to_string()) + } + Lang::InfluxQl | Lang::Sql => { + let b = bare(stmt).to_ascii_uppercase(); + let parts: Vec<&str> = b.split(';').map(str::trim).filter(|p| !p.is_empty()).collect(); + if parts.len() > 1 && matches!(lang, Lang::Sql) { + return Some("Run one statement at a time".into()); + } + for p in parts { + let head = p.split_whitespace().next().unwrap_or(""); + if !matches!(head, "SELECT" | "SHOW" | "EXPLAIN" | "WITH" | "DESCRIBE") { + return Some(format!("{head} changes data; InfluxDB is read-only here (SELECT, SHOW and EXPLAIN run)")); + } + if matches!(lang, Lang::InfluxQl) && head == "SELECT" && p.split_whitespace().any(|w| w == "INTO") { + return Some("SELECT ... INTO writes; InfluxDB is read-only here".into()); + } + } + None + } + } +} + +/// A call to `to(`, `wideTo(` or `*.to(` in Flux. +fn regex_lite_to(b: &str) -> bool { + let bytes = b.as_bytes(); + let mut i = 0; + while let Some(off) = b[i..].find("to") { + let at = i + off; + let before = if at == 0 { b' ' } else { bytes[at - 1] }; + let word_start = !(before.is_ascii_alphanumeric() || before == b'_') || b[..at].ends_with("wide"); + let after = b[at + 2..].trim_start(); + if word_start && after.starts_with('(') { + return true; + } + i = at + 2; + } + false +} + +pub async fn connect(cfg: &InfluxConfig) -> Result { + if cfg.url.trim().is_empty() { + return Err("Enter the InfluxDB address".into()); + } + if cfg.database.trim().is_empty() { + return Err(if cfg.version.trim() == "2" { "Enter the bucket".into() } else { "Enter the database".into() }); + } + if cfg.version.trim() == "2" && cfg.org.as_deref().map(str::trim).unwrap_or("").is_empty() { + return Err("Enter the organization".into()); + } + measurements(cfg).await?; + Ok(cfg.clone()) +} + +fn kind_of(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(n) if n.is_i64() || n.is_u64() => "integer", + Value::Number(_) => "float", + _ => "string", + } +} + +fn to_result(cols: Vec, mut rows: Vec>, sql: &str, t0: Instant) -> SqlResult { + let total = rows.len(); + rows.truncate(MAX_ROWS); + let columns = cols + .iter() + .enumerate() + .map(|(i, n)| { + let k = if n == "time" || n == "_time" { "timestamp" } else { rows.iter().map(|r| kind_of(&r[i])).find(|k| *k != "null").unwrap_or("string") }; + ColumnInfo::new(n.clone(), k) + }) + .collect(); + let message = (total > rows.len()).then(|| format!("Showing the first {} of {total} rows", rows.len())); + SqlResult { row_count: Some(rows.len() as i64), columns, rows, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() } +} + +/// A console statement: SQL (3.x), Flux (2.x) or InfluxQL. +pub async fn query(cfg: &InfluxConfig, stmt: &str) -> Result { + let t0 = Instant::now(); + let (lang, text) = lang_of(cfg, stmt.trim().trim_end_matches(';')); + if text.trim().is_empty() { + return Err("Query is empty".into()); + } + if let Some(why) = refusal(&lang, &text) { + return Err(why); + } + let (cols, rows) = match lang { + Lang::Sql => sql(cfg, &text).await?, + Lang::InfluxQl => influxql(cfg, &text).await?, + Lang::Flux if v3(cfg) => return Err("InfluxDB 3 doesn't run Flux: use SQL, or InfluxQL after \"influxql:\"".into()), + Lang::Flux => flux(cfg, &text).await?, + }; + Ok(to_result(cols, rows, &text, t0)) +} + +// ── The browser ─────────────────────────────────────────────────────────────── + +fn quote_ident(name: &str) -> String { + format!("\"{}\"", name.replace('\\', "\\\\").replace('"', "\\\"")) +} + +fn sql_ident(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +/// Measurement names. +pub async fn measurements(cfg: &InfluxConfig) -> Result, String> { + let (cols, rows) = if v3(cfg) { + sql(cfg, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'iox' ORDER BY table_name").await? + } else { + influxql(cfg, "SHOW MEASUREMENTS").await? + }; + let at = cols.iter().position(|c| c == "table_name" || c == "name").unwrap_or(0); + Ok(rows.into_iter().filter_map(|r| r.get(at).and_then(|v| v.as_str().map(String::from))).collect()) +} + +/// Tags and fields of a measurement, with their types. +pub async fn describe(cfg: &InfluxConfig, m: &str) -> Result { + if v3(cfg) { + let (_, rows) = sql( + cfg, + &format!( + "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'iox' AND table_name = '{}' ORDER BY ordinal_position", + m.replace('\'', "''") + ), + ) + .await?; + let mut tags = vec![]; + let mut fields = vec![]; + for r in rows { + let name = r[0].as_str().unwrap_or("").to_string(); + let ty = r[1].as_str().unwrap_or(""); + if name == "time" { + continue; + } + if ty.starts_with("Dictionary") { + tags.push(json!(name)); + } else { + fields.push(json!({ "name": name, "type": ty })); + } + } + return Ok(json!({ "tags": tags, "fields": fields })); + } + let (_, tag_rows) = influxql(cfg, &format!("SHOW TAG KEYS FROM {}", quote_ident(m))).await?; + let (_, field_rows) = influxql(cfg, &format!("SHOW FIELD KEYS FROM {}", quote_ident(m))).await?; + Ok(json!({ + "tags": tag_rows.iter().map(|r| r[0].clone()).collect::>(), + "fields": field_rows.iter().map(|r| json!({ "name": r[0], "type": r.get(1).cloned().unwrap_or(Value::Null) })).collect::>(), + })) +} + +/// A WHERE condition from the browser's filter box: one read-only expression. +fn check_filter(filter: &str) -> Result<(), String> { + let b = bare(filter); + if b.contains(';') { + return Err("The filter is one condition: no \";\"".into()); + } + let mut depth = 0i32; + for c in b.chars() { + depth += match c { + '(' => 1, + ')' => -1, + _ => 0, + }; + if depth < 0 { + return Err("The filter's parentheses don't match".into()); + } + } + if depth != 0 { + return Err("The filter's parentheses don't match".into()); + } + let up = b.to_ascii_uppercase(); + if up.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').any(|w| matches!(w, "INTO" | "UNION" | "LIMIT" | "OFFSET" | "SLIMIT" | "SOFFSET" | "ORDER" | "GROUP")) { + return Err("The filter is a WHERE condition only".into()); + } + Ok(()) +} + +/// One page of points, newest first. +pub async fn page(cfg: &InfluxConfig, m: &str, filter: &str, skip: i64, limit: i64) -> Result { + let filter = filter.trim(); + if !filter.is_empty() { + check_filter(filter)?; + } + let wh = if filter.is_empty() { String::new() } else { format!(" WHERE {filter}") }; + let limit = limit.clamp(1, 5000); + let skip = skip.max(0); + let (cols, rows) = if v3(cfg) { + sql(cfg, &format!("SELECT * FROM {}{wh} ORDER BY time DESC LIMIT {limit} OFFSET {skip}", sql_ident(m))).await? + } else { + influxql(cfg, &format!("SELECT * FROM {}{wh} ORDER BY time DESC LIMIT {limit} OFFSET {skip}", quote_ident(m))).await? + }; + let docs: Vec = rows + .into_iter() + .map(|r| Value::Object(cols.iter().cloned().zip(r).collect::>())) + .collect(); + let next = (docs.len() as i64 >= limit).then_some(skip + docs.len() as i64); + Ok(json!({ "docs": docs, "next": next })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg(version: &str) -> InfluxConfig { + InfluxConfig { name: "t".into(), url: "localhost:8086".into(), version: version.into(), database: "db".into(), org: Some("o".into()), token: None, user: None, password: None } + } + + #[test] + fn languages() { + assert_eq!(lang_of(&cfg("2"), "from(bucket: \"b\") |> range(start: -1h)").0, Lang::Flux); + assert_eq!(lang_of(&cfg("2"), "SELECT * FROM cpu").0, Lang::InfluxQl); + assert_eq!(lang_of(&cfg("3"), "SELECT * FROM cpu").0, Lang::Sql); + assert_eq!(lang_of(&cfg("3"), "influxql: SHOW MEASUREMENTS"), (Lang::InfluxQl, "SHOW MEASUREMENTS".into())); + } + + #[test] + fn writes_are_refused() { + assert!(refusal(&Lang::InfluxQl, "SELECT * FROM cpu").is_none()); + assert!(refusal(&Lang::InfluxQl, "SHOW MEASUREMENTS").is_none()); + assert!(refusal(&Lang::InfluxQl, "DROP MEASUREMENT cpu").is_some()); + assert!(refusal(&Lang::InfluxQl, "SELECT * INTO copy FROM cpu").is_some()); + assert!(refusal(&Lang::InfluxQl, "SELECT * FROM cpu; DELETE FROM cpu").is_some()); + assert!(refusal(&Lang::InfluxQl, "SELECT * FROM cpu WHERE host = 'DROP x; INTO'").is_none(), "strings don't count"); + assert!(refusal(&Lang::Sql, "SELECT 1; SELECT 2").is_some()); + assert!(refusal(&Lang::Flux, "from(bucket: \"b\") |> range(start: -1h) |> filter(fn: (r) => r.to == \"x\")").is_none()); + assert!(refusal(&Lang::Flux, "from(bucket: \"b\") |> range(start: -1h) |> to(bucket: \"c\")").is_some()); + assert!(refusal(&Lang::Flux, "import \"experimental\"\nfrom(bucket: \"b\") |> range(start: -1h) |> experimental.to(bucket: \"c\")").is_some()); + assert!(refusal(&Lang::Flux, "import \"influxdata/influxdb/schema\"\nschema.measurements(bucket: \"b\")").is_none()); + assert!(refusal(&Lang::Flux, "import \"http\"\nhttp.post(url: \"https://x\")").is_some()); + assert!(refusal(&Lang::Flux, "import \"sql\"\nsql.from(driverName: \"postgres\", dataSourceName: \"x\", query: \"y\")").is_some()); + } + + #[test] + fn filters() { + assert!(check_filter("host = 'a' AND usage > 50").is_ok()); + assert!(check_filter("time > now() - 1h").is_ok()); + assert!(check_filter("1=1) LIMIT 1 (").is_err()); + assert!(check_filter("host = 'a'; DROP MEASUREMENT cpu").is_err()); + assert!(check_filter("host = 'a' GROUP BY host").is_err()); + assert!(check_filter("note = 'limit; (('").is_ok()); + } + + #[test] + fn annotated_csv() { + let text = "#datatype,string,long,dateTime:RFC3339,string,double\r\n,result,table,_time,host,usage\r\n,_result,0,2026-01-01T00:00:00Z,a,1.5\r\n,_result,0,2026-01-01T00:00:01Z,\"b,\"\"c\"\"\",2\r\n\r\n#datatype,string,long,string,long\r\n,result,table,host,cores\r\n,_result,1,a,4\r\n"; + let (cols, rows) = flux_csv(text); + assert_eq!(cols, vec!["_time", "host", "usage", "cores"]); + assert_eq!(rows[0], vec![json!("2026-01-01T00:00:00Z"), json!("a"), json!(1.5), Value::Null]); + assert_eq!(rows[1][1], json!("b,\"c\"")); + assert_eq!(rows[2], vec![Value::Null, json!("a"), Value::Null, json!(4)]); + } + + /// STROKE_TEST_INFLUX2 = url|org|bucket|token (with cpu and mem points), + /// STROKE_TEST_INFLUX3 = url|database (no auth). + #[tokio::test] + async fn live_round_trip() { + let mut ran = false; + if let Ok(spec) = std::env::var("STROKE_TEST_INFLUX2") { + let p: Vec<&str> = spec.split('|').collect(); + let c = InfluxConfig { name: "t".into(), url: p[0].into(), version: "2".into(), org: Some(p[1].into()), database: p[2].into(), token: Some(p[3].into()), user: None, password: None }; + check(&c).await; + let r = query(&c, &format!("from(bucket: \"{}\") |> range(start: 0) |> filter(fn: (r) => r._measurement == \"cpu\" and r._field == \"usage\")", p[2])).await.unwrap(); + assert_eq!(r.rows.len(), 2); + assert!(r.columns.iter().any(|c| c.name == "_value")); + assert!(query(&c, &format!("from(bucket: \"{}\") |> range(start: 0) |> to(bucket: \"x\")", p[2])).await.is_err()); + let bad = InfluxConfig { token: Some("nope".into()), ..c.clone() }; + assert!(connect(&bad).await.unwrap_err().contains("refused")); + ran = true; + } + if let Ok(spec) = std::env::var("STROKE_TEST_INFLUX3") { + let p: Vec<&str> = spec.split('|').collect(); + let c = InfluxConfig { name: "t".into(), url: p[0].into(), version: "3".into(), org: None, database: p[1].into(), token: None, user: None, password: None }; + check(&c).await; + let r = query(&c, "SELECT host, avg(usage) AS u FROM cpu GROUP BY host ORDER BY host").await.unwrap(); + assert_eq!(r.rows.len(), 2); + assert!(query(&c, "influxql: SHOW MEASUREMENTS").await.unwrap().rows.len() >= 2); + assert!(query(&c, "DELETE FROM cpu").await.is_err()); + ran = true; + } + let _ = ran; + } + + async fn check(c: &InfluxConfig) { + let c = connect(c).await.unwrap(); + let ms = measurements(&c).await.unwrap(); + assert!(ms.contains(&"cpu".to_string()) && ms.contains(&"mem".to_string()), "{ms:?}"); + let d = describe(&c, "cpu").await.unwrap(); + assert!(d["tags"].as_array().unwrap().iter().any(|t| t == "host"), "{d}"); + assert!(d["fields"].as_array().unwrap().iter().any(|f| f["name"] == "usage"), "{d}"); + let pg = page(&c, "cpu", "host = 'b'", 0, 50).await.unwrap(); + let docs = pg["docs"].as_array().unwrap(); + assert_eq!(docs.len(), 1, "{pg}"); + assert_eq!(docs[0]["usage"], json!(80.1)); + assert_eq!(docs[0]["region"], json!("us")); + let all = page(&c, "cpu", "", 0, 1).await.unwrap(); + assert_eq!(all["next"], json!(1)); + assert!(page(&c, "cpu", "1=1; DROP MEASUREMENT cpu", 0, 1).await.is_err()); + let r = query(&c, "SELECT * FROM cpu").await.unwrap(); + assert_eq!(r.rows.len(), 2); + assert_eq!(r.columns[0].name, "time"); + assert!(query(&c, "DROP MEASUREMENT cpu").await.is_err()); + } +} diff --git a/src-tauri/src/db/insights.rs b/src-tauri/src/db/insights.rs index 2a189807..5bf931d0 100644 --- a/src-tauri/src/db/insights.rs +++ b/src-tauri/src/db/insights.rs @@ -334,6 +334,7 @@ pub struct SessionCounts { pub struct ActivityCounters { pub commits: i64, pub rollbacks: i64, + pub tup_inserted: i64, pub tup_updated: i64, pub tup_deleted: i64, pub tup_fetched: i64, @@ -412,6 +413,7 @@ async fn pg_activity(pool: &PgPool) -> InstanceActivity { let counters = match sqlx::query( "SELECT COALESCE(sum(xact_commit),0)::bigint AS commits, COALESCE(sum(xact_rollback),0)::bigint AS rollbacks, + COALESCE(sum(tup_inserted),0)::bigint AS tup_inserted, COALESCE(sum(tup_updated),0)::bigint AS tup_updated, COALESCE(sum(tup_deleted),0)::bigint AS tup_deleted, COALESCE(sum(tup_fetched),0)::bigint AS tup_fetched, @@ -426,6 +428,7 @@ async fn pg_activity(pool: &PgPool) -> InstanceActivity { Ok(r) => ActivityCounters { commits: r.try_get("commits").unwrap_or(0), rollbacks: r.try_get("rollbacks").unwrap_or(0), + tup_inserted: r.try_get("tup_inserted").unwrap_or(0), tup_updated: r.try_get("tup_updated").unwrap_or(0), tup_deleted: r.try_get("tup_deleted").unwrap_or(0), tup_fetched: r.try_get("tup_fetched").unwrap_or(0), @@ -484,12 +487,20 @@ async fn mysql_activity(pool: &MySqlPool) -> InstanceActivity { "Innodb_rows_updated", "Innodb_rows_deleted", "Innodb_rows_read", + // MariaDB 10.6+ dropped the Innodb_rows_* counters; the server-wide + // Rows_* and Handler_* ones count the same work. + "Rows_read", + "Handler_update", + "Handler_delete", "Innodb_buffer_pool_read_requests", "Innodb_buffer_pool_reads", ], ) .await; let g = |k: &str| -> i64 { status.get(k).copied().unwrap_or(0) }; + // The first counter the server has, so MariaDB reads its own names rather + // than zeros for counters MySQL alone still keeps. + let first = |keys: &[&str]| -> i64 { keys.iter().find_map(|k| status.get(*k).copied()).unwrap_or(0) }; // InnoDB exposes logical read requests and physical (disk) reads. Map onto the // PostgreSQL buffer-cache model: hits = requests - physical reads (pages served @@ -501,10 +512,11 @@ async fn mysql_activity(pool: &MySqlPool) -> InstanceActivity { let counters = ActivityCounters { commits: g("Com_commit"), rollbacks: g("Com_rollback"), - tup_updated: g("Innodb_rows_updated"), - tup_deleted: g("Innodb_rows_deleted"), - tup_fetched: g("Innodb_rows_read"), - tup_returned: g("Innodb_rows_read"), + tup_inserted: first(&["Innodb_rows_inserted", "Handler_write"]), + tup_updated: first(&["Innodb_rows_updated", "Handler_update"]), + tup_deleted: first(&["Innodb_rows_deleted", "Handler_delete"]), + tup_fetched: first(&["Innodb_rows_read", "Rows_read"]), + tup_returned: first(&["Innodb_rows_read", "Rows_read"]), blks_read: disk_reads, blks_hit, }; @@ -522,6 +534,7 @@ fn zero_counters() -> ActivityCounters { ActivityCounters { commits: 0, rollbacks: 0, + tup_inserted: 0, tup_updated: 0, tup_deleted: 0, tup_fetched: 0, @@ -571,8 +584,10 @@ pub async fn instance_state(state: Db<'_>) -> Result { ActiveConnection::Postgres(pool) => { let sessions = pg_query_objects( &pool, + // Background workers have no user; their type (checkpointer, + // autovacuum launcher) says what they are where a dash said nothing. "SELECT pid, - usename AS \"user\", + COALESCE(usename::text, backend_type) AS \"user\", application_name AS application, client_addr::text AS client, state, diff --git a/src-tauri/src/db/libsql.rs b/src-tauri/src/db/libsql.rs index a71a971e..f3d300a4 100644 --- a/src-tauri/src/db/libsql.rs +++ b/src-tauri/src/db/libsql.rs @@ -9,7 +9,7 @@ static LIBSQL_CLIENT: OnceLock = OnceLock::new(); fn client() -> &'static reqwest::Client { LIBSQL_CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(10) .pool_idle_timeout(std::time::Duration::from_secs(90)) @@ -21,14 +21,35 @@ fn client() -> &'static reqwest::Client { }) } -/// Normalise a user-supplied URL to an https:// base URL. +/// Normalise a user-supplied URL to an http(s):// base URL. fn base_url(config: &LibSqlConfig) -> String { - let url = config.url.trim().trim_end_matches('/'); - if url.starts_with("libsql://") { - format!("https://{}", &url["libsql://".len()..]) - } else { - url.to_string() + libsql_http_url(config.url.trim().trim_end_matches('/')) +} + +/// `libsql://` as HTTP: TLS, as Turso's own client reads it, except where +/// there is none to speak. A local sqld (`turso dev`, a container) serves plain +/// HTTP, and libSQL's clients spell that `?tls=0`; a loopback host means it +/// too. Without this, a local libsql:// URL could not connect at all. +pub(crate) fn libsql_http_url(url: &str) -> String { + let Some(rest) = url.strip_prefix("libsql://") else { return url.to_string() }; + let (head, query) = rest.split_once('?').unwrap_or((rest, "")); + let mut tls = true; + let kept: Vec<&str> = query + .split('&') + .filter(|p| !p.is_empty()) + .filter(|p| match *p { + "tls=0" | "tls=false" => { tls = false; false } + "tls=1" | "tls=true" => false, + _ => true, + }) + .collect(); + let host = head.split(['/', ':']).next().unwrap_or(""); + let host = if head.starts_with('[') { head.split(']').next().unwrap_or("").trim_start_matches('[') } else { host }; + if host == "localhost" || host == "::1" || host.starts_with("127.") { + tls = false; } + let q = if kept.is_empty() { String::new() } else { format!("?{}", kept.join("&")) }; + format!("{}://{head}{q}", if tls { "https" } else { "http" }) } // ── Wire format ──────────────────────────────────────────────────────────────── @@ -67,7 +88,6 @@ struct ExecResult { #[derive(Deserialize)] struct ColDef { name: String, - #[allow(dead_code)] decltype: Option, } @@ -201,8 +221,19 @@ async fn query_with(config: &LibSqlConfig, sql: &str, params: Vec, rollba let exec = exec_result.ok_or("No execute result in LibSQL response")?; - let columns: Vec = exec.cols.iter() - .map(|c| ColumnInfo::new(c.name.clone(), "text")) + // The declared type the server reports (INTEGER, BOOLEAN, ...); every + // column read "text" before. An expression has none: the first value's + // storage class stands in, as SQLite's own typeof() would say. + let columns: Vec = exec.cols.iter().enumerate() + .map(|(i, c)| { + let declared = c.decltype.as_deref().map(str::trim).filter(|t| !t.is_empty()).map(str::to_lowercase); + let seen = || exec.rows.iter() + .filter_map(|r| r.get(i)) + .map(|v| v.kind.as_str()) + .find(|k| *k != "null") + .map(|k| if k == "float" { "real".to_string() } else { k.to_string() }); + ColumnInfo::new(c.name.clone(), declared.or_else(seen).unwrap_or_else(|| "text".into())) + }) .collect(); let rows: Vec> = exec.rows.iter() @@ -211,7 +242,22 @@ async fn query_with(config: &LibSqlConfig, sql: &str, params: Vec, rollba let affected = exec.affected_row_count; let row_count = Some(if affected > 0 { affected } else { rows.len() as i64 }); - let message = if affected > 0 { Some(format!("{} row(s) affected", affected)) } else { None }; + let message = if affected > 0 { Some(super::query::affected_message(sql, affected)) } else { None }; Ok(SqlResult { columns, rows, row_count, message, query_ms: elapsed, sql: sql.to_string() }) } + + +#[cfg(test)] +mod url_tests { + #[test] + fn local_libsql_urls_speak_plain_http() { + use super::libsql_http_url as u; + assert_eq!(u("libsql://mydb-org.turso.io"), "https://mydb-org.turso.io"); + assert_eq!(u("libsql://127.0.0.1:18080"), "http://127.0.0.1:18080"); + assert_eq!(u("libsql://localhost:8080"), "http://localhost:8080"); + assert_eq!(u("libsql://[::1]:8080"), "http://[::1]:8080"); + assert_eq!(u("libsql://db.lan:8080?tls=0"), "http://db.lan:8080"); + assert_eq!(u("http://x:1"), "http://x:1"); + } +} diff --git a/src-tauri/src/db/mod.rs b/src-tauri/src/db/mod.rs index b3a800fc..e4c02626 100644 --- a/src-tauri/src/db/mod.rs +++ b/src-tauri/src/db/mod.rs @@ -3,6 +3,7 @@ pub mod backup; pub mod migrations; pub mod clickhouse; pub mod parked; +pub mod stop; pub mod posthog; pub mod connection; pub mod d1; @@ -22,6 +23,13 @@ pub mod couchdb; pub mod elastic; pub mod cassandra; pub mod firestore; +pub mod neo4j; +pub mod influx; +pub mod google_auth; +pub mod spanner; +pub mod bigquery; +pub mod odbc; +pub mod snowflake; pub mod mongo; pub mod docdb; #[cfg(test)] @@ -45,7 +53,7 @@ pub use connection::{ test_clickhouse_connection, test_connection, test_d1_connection, test_duckdb_connection, test_libsql_connection, test_mssql_connection, test_mysql_connection, test_oracle_connection, test_redis_connection, test_sqlite_connection, ActiveConnection, AnyConnectionConfig, ConnectionConfig, D1Config, DbState, LibSqlConfig, SqliteConfig, }; -pub use explain::{explain_pg, explain_mysql, explain_sqlite, explain_from_text_lines, explain_from_sqlite_plan, ExplainResult}; +pub use explain::{explain_mysql, explain_sqlite, explain_from_text_lines, explain_from_sqlite_plan, ExplainResult}; pub use insights::{ instance_activity, instance_config, instance_replication, instance_set_config, instance_state, instance_version, ConfigSetting, InstanceActivity, InstanceReplication, InstanceState, @@ -56,9 +64,9 @@ pub use ssh_tunnel::TunnelState; pub use query::{ delete_table_row, delete_table_rows, execute_ddl, execute_sql, execute_sql_multi, execute_sql_on_conn, execute_sql_script, StatementOutcome, fetch_cell_value, CellValueResult, get_column_stats, get_table_rows, count_table_rows, search_index_status, create_search_index, SearchIndexStatus, insert_table_row, update_table_cell, ping_connection, - ColumnStats, InsertRowResult, KeysetCursor, apply_table_changes, ApplyChangesResult, RowUpdate, RowChunk, RowFilter, RowSink, SortSpec, SqlResult, TableRows, + ColumnStats, InsertRowResult, KeysetCursor, FetchTag, apply_table_changes, ApplyChangesResult, RowUpdate, RowChunk, RowFilter, RowSink, SortSpec, SqlResult, TableRows, }; -pub use schema::{ +pub use schema::{schemas_of, list_schemas, list_tables, list_schemas_on_conn, list_tables_on_conn, list_indexes_for, list_enums, list_functions, list_triggers, list_sequences, table_row_counts, truncate_table, drop_table, get_table_column_structure, get_schema_column_structure, get_incoming_foreign_keys, diff --git a/src-tauri/src/db/mongo.rs b/src-tauri/src/db/mongo.rs index c6588f0f..79586bc4 100644 --- a/src-tauri/src/db/mongo.rs +++ b/src-tauri/src/db/mongo.rs @@ -32,6 +32,10 @@ pub struct MongoConfig { /// Database for `db.` in the console; the URI's, else the first one found. #[serde(default)] pub database: Option, + /// Reach the server through an SSH tunnel (connection::tunnel_to and friends). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh: Option, + } pub struct MongoConn { @@ -219,13 +223,60 @@ pub fn shell_to_json5(src: &str) -> String { out } +/// A json5 parse error in words. Its own message is pest's caret diagram +/// ending in what the grammar wanted next, which misleads for the usual +/// mistake: `{total: {$gt: 10}` points at `10` and says "expected boolean, +/// null, or string". An unbalanced bracket or quote is named first; anything +/// else keeps the grammar's last line and the position. +fn json5_error_text(src: &str, err: &json5::Error) -> String { + let mut stack: Vec = Vec::new(); + let mut in_str: Option = None; + let mut escaped = false; + for c in src.chars() { + if let Some(q) = in_str { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == q { + in_str = None; + } + continue; + } + match c { + '"' | '\'' => in_str = Some(c), + '{' => stack.push('}'), + '[' => stack.push(']'), + '}' | ']' => { + if stack.pop() != Some(c) { + return format!("there is an extra {c}, or a bracket before it isn't closed"); + } + } + _ => {} + } + } + if let Some(q) = in_str { + return format!("a string isn't closed: it needs a closing {q}"); + } + if let Some(close) = stack.last() { + return format!("it is missing a closing {close}"); + } + let json5::Error::Message { msg, location } = err; + let what = msg.lines().rev().map(str::trim).find_map(|l| l.strip_prefix("= ")).unwrap_or(msg.as_str()).trim(); + match location { + Some(l) if src.contains('\n') => format!("{what} (line {}, column {})", l.line, l.column), + Some(l) => format!("{what} (column {})", l.column), + None => what.to_string(), + } +} + /// Parse shell-style arguments (`{plan: "pro"}, {age: 1}`) into JSON values. pub fn parse_args(src: &str) -> Result, String> { let s = src.trim(); if s.is_empty() { return Ok(vec![]); } - json5::from_str::>(&format!("[{}]", shell_to_json5(s))).map_err(|e| format!("Couldn't read the arguments: {e}")) + json5::from_str::>(&format!("[{}]", shell_to_json5(s))).map_err(|e| format!("Couldn't read the arguments: {}", json5_error_text(s, &e))) } /// One filter (or sort) object from the browser's filter box. @@ -234,7 +285,7 @@ pub fn parse_object(src: &str, what: &str) -> Result { if s.is_empty() { return Ok(Document::new()); } - let v: Value = json5::from_str(&shell_to_json5(s)).map_err(|e| format!("The {what} isn't valid: {e}"))?; + let v: Value = json5::from_str(&shell_to_json5(s)).map_err(|e| format!("The {what} isn't valid: {}", json5_error_text(s, &e)))?; if !v.is_object() { return Err(format!("The {what} is an object, e.g. {{plan: \"pro\"}}")); } @@ -1075,7 +1126,7 @@ pub async fn update_field(m: &MongoConn, full: &str, id: &Value, path: &str, val /// A pipeline in shell syntax: `[{$match: {...}}, ...]`. pub fn parse_pipeline(src: &str) -> Result, String> { - let v: Value = json5::from_str(&shell_to_json5(src.trim())).map_err(|e| format!("The pipeline isn't valid: {e}"))?; + let v: Value = json5::from_str(&shell_to_json5(src.trim())).map_err(|e| format!("The pipeline isn't valid: {}", json5_error_text(src.trim(), &e)))?; let Value::Array(stages) = v else { return Err("A pipeline is an array of stages".into()) }; stages .iter() @@ -1427,8 +1478,307 @@ fn arg_doc(args: &[Value], i: usize, what: &str) -> Result { } } +/// The command a console find/aggregate/count/distinct explains as. +fn explain_cmd(coll: &str, head: &Call, args: &[Value], sort: Option, limit: Option, skip: Option) -> Result { + let cmd = match head.name.as_str() { + "find" => { + let mut f = doc! { "find": coll, "filter": arg_doc(&args, 0, "filter")? }; + if let Some(p) = args.get(1).filter(|v| v.is_object()) { + f.insert("projection", to_doc(p, None)?); + } + if let Some(s) = sort { + f.insert("sort", s); + } + if let Some(l) = limit { + f.insert("limit", l); + } + if let Some(k) = skip { + f.insert("skip", k as i64); + } + f + } + "aggregate" => { + let pipeline = match args.first() { + Some(Value::Array(stages)) => stages.iter().map(|s| to_doc(s, None)).collect::, _>>()?, + _ => return Err("aggregate() takes an array of stages".into()), + }; + doc! { "aggregate": coll, "pipeline": pipeline, "cursor": {} } + } + "countDocuments" => doc! { "count": coll, "query": arg_doc(&args, 0, "filter")? }, + "distinct" => { + let field = args.first().and_then(|v| v.as_str()).ok_or("distinct() takes a field name")?; + doc! { "distinct": coll, "key": field, "query": arg_doc(&args, 1, "filter")? } + } + other => return Err(format!("{other}() can't be explained here; try find() or aggregate()")), + }; + Ok(cmd) +} + + +/// A console statement's plan as the plan view's tree (the Postgres-shaped +/// `{Node Type, Plans, Actual Rows, ...}` it draws for every engine): the +/// executed stages with their counts and timings, aggregate stages stacked +/// above the cursor's tree. +pub async fn explain_plan(m: &MongoConn, stmt: &str) -> Result { + let db_name = m.current_db.lock().map(|g| g.clone()).unwrap_or_default(); + let Stmt::Coll { coll, calls } = parse(stmt)? else { + return Err("Explain works on db..find(...), aggregate(...), countDocuments(...) or distinct(...)".into()); + }; + let calls: Vec = calls.into_iter().filter(|c| c.name != "explain").collect(); + let (head, mods) = calls.split_first().ok_or("Missing method")?; + let args = parse_args(&head.args)?; + let (mut sort, mut limit, mut skip) = (None, None, None); + for md in mods { + let a = parse_args(&md.args)?; + match md.name.as_str() { + "sort" => sort = Some(arg_doc(&a, 0, "sort")?), + "limit" => limit = a.first().and_then(|v| v.as_i64()), + "skip" => skip = a.first().and_then(|v| v.as_u64()), + _ => {} + } + } + let cmd = explain_cmd(&coll, head, &args, sort, limit, skip)?; + let raw = m.client.database(&db_name).run_command(doc! { "explain": cmd, "verbosity": "executionStats" }).await.map_err(err)?; + Ok(plan_tree(&doc_to_json(&raw), &coll)) +} + +/// Explain output → plan tree. Pure, so it is tested on recorded output. +pub fn plan_tree(raw: &Value, coll: &str) -> Value { + fn stage_node(st: &Value, coll: &str) -> Value { + let name = st["stage"].as_str().unwrap_or("STAGE"); + let mut n = serde_json::Map::new(); + n.insert("Node Type".into(), json!(name)); + if matches!(name, "COLLSCAN" | "IXSCAN" | "FETCH" | "IDHACK" | "EXPRESS_IXSCAN" | "CLUSTERED_IXSCAN") { + n.insert("Relation Name".into(), json!(coll)); + } + if let Some(ix) = st["indexName"].as_str() { + n.insert("Index Name".into(), json!(ix)); + } + let num = |k: &str| st[k].as_i64().or_else(|| st[k].as_f64().map(|f| f as i64)).or_else(|| st[k].as_str().and_then(|s| s.parse().ok())); + if let Some(r) = num("nReturned") { + n.insert("Actual Rows".into(), json!(r)); + } + if let Some(ms) = num("executionTimeMillisEstimate") { + n.insert("Actual Total Time".into(), json!(ms)); + } + if let Some(d) = num("docsExamined") { + n.insert("Docs Examined".into(), json!(d)); + if let Some(r) = num("nReturned") { + if d > r && st.get("filter").is_some() { + n.insert("Rows Removed by Filter".into(), json!(d - r)); + } + } + } + if let Some(k) = num("keysExamined") { + n.insert("Keys Examined".into(), json!(k)); + } + if let Some(f) = st.get("filter") { + n.insert("Filter".into(), json!(f.to_string())); + } + if let Some(kp) = st.get("keyPattern") { + n.insert("Index Cond".into(), json!(kp.to_string())); + } + let mut kids: Vec = vec![]; + if let Some(c) = st.get("inputStage") { + kids.push(stage_node(c, coll)); + } + if let Some(cs) = st["inputStages"].as_array() { + kids.extend(cs.iter().map(|c| stage_node(c, coll))); + } + if !kids.is_empty() { + n.insert("Plans".into(), Value::Array(kids)); + } + Value::Object(n) + } + // aggregate: the find part sits in stages[0].$cursor, the rest above it. + let (base, later): (&Value, Vec<&Value>) = match raw["stages"].as_array() { + Some(st) if st.first().is_some_and(|s| s.get("$cursor").is_some()) => (&st[0]["$cursor"], st.iter().skip(1).collect()), + _ => (raw, vec![]), + }; + let exec = &base["executionStats"]["executionStages"]; + let mut tree = if exec.get("stage").is_some() { + stage_node(exec, coll) + } else { + let wp = &base["queryPlanner"]["winningPlan"]; + // SBE plans nest the classic tree under queryPlan. + stage_node(if wp.get("queryPlan").is_some() { &wp["queryPlan"] } else { wp }, coll) + }; + for st in later { + let Some((name, _)) = st.as_object().and_then(|o| o.iter().find(|(k, _)| k.starts_with('$'))) else { continue }; + let mut n = serde_json::Map::new(); + n.insert("Node Type".into(), json!(name)); + if let Some(r) = st["nReturned"].as_i64() { + n.insert("Actual Rows".into(), json!(r)); + } + if let Some(ms) = st["executionTimeMillisEstimate"].as_i64() { + n.insert("Actual Total Time".into(), json!(ms)); + } + n.insert("Plans".into(), json!([tree])); + tree = Value::Object(n); + } + tree +} + const CONSOLE_CAP: i64 = 5_000; +/// Fields the first batch did not have go here, as one object, so a later +/// document's extra keys are not lost from a streamed result. +pub const OTHER_FIELDS: &str = "(other fields)"; + +/// Whether `stream_into` takes this statement: a find or aggregate with no +/// limit under the console's cap (those answer in the reply as before). +pub(crate) fn streams(stmt: &str) -> bool { + let Ok(Stmt::Coll { calls, .. }) = parse(stmt) else { return false }; + let Some(head) = calls.first() else { return false }; + if head.name == "explain" || calls.iter().any(|c| c.name == "explain") { + return false; + } + if head.name != "find" && head.name != "aggregate" { + return false; + } + let limit = calls.iter().find(|c| c.name == "limit").and_then(|c| parse_args(&c.args).ok()).and_then(|a| a.first().and_then(|v| v.as_i64())); + limit.map_or(true, |l| l <= 0 || l > CONSOLE_CAP) +} + +/// A find or aggregate, streamed into `sink` from the cursor. +/// +/// The console collected at most 5,000 documents. Here the cursor's batches go +/// straight to the grid or the result store. Columns come from the first +/// 1,000 documents (`_id` first, as in the collected result); a later +/// document's keys outside them land in `(other fields)`. Stop drops the +/// cursor, which the driver kills on the server. +pub async fn stream_into( + m: &MongoConn, + stmt: &str, + sink: &mut super::query::RowSink, + stop: &super::stop::Stop, +) -> Result { + let tag = op_tag(); + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(stream_rows(m, stmt, sink, &tag)); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + drop(run); + let _ = tokio::time::timeout(std::time::Duration::from_secs(10), kill_tagged(m, &tag)).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +/// A comment to tag a run's operations with, so Stop can find them. +fn op_tag() -> String { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + format!("stroke-{:x}-{:x}", std::process::id(), SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) +} + +/// killOp every operation carrying `tag` as its comment. Dropping the cursor +/// only kills it once a batch has come back; a find still scanning for its +/// first batch, or an aggregate's $group, runs on until then. Returns how many. +pub async fn kill_tagged(m: &MongoConn, tag: &str) -> Result { + let admin = m.client.database("admin"); + let pipeline = vec![ + doc! { "$currentOp": { "allUsers": false, "idleCursors": false } }, + doc! { "$match": { "$or": [ { "command.comment": tag }, { "cursor.originatingCommand.comment": tag } ] } }, + doc! { "$project": { "opid": 1 } }, + ]; + let ops: Vec = admin.aggregate(pipeline).await.map_err(err)?.try_collect().await.map_err(err)?; + for op in &ops { + if let Some(id) = op.get("opid") { + let _ = admin.run_command(doc! { "killOp": 1, "op": id.clone() }).await; + } + } + Ok(ops.len()) +} + +async fn stream_rows(m: &MongoConn, stmt: &str, sink: &mut super::query::RowSink, tag: &str) -> Result { + use futures::StreamExt; + const SAMPLE: usize = 1_000; + let t0 = std::time::Instant::now(); + let db_name = m.current_db.lock().map(|g| g.clone()).unwrap_or_default(); + let Stmt::Coll { coll, calls } = parse(stmt)? else { return Err("Not a find or aggregate".into()) }; + let c = m.client.database(&db_name).collection::(&coll); + let (head, mods) = calls.split_first().ok_or("Missing method")?; + let args = parse_args(&head.args)?; + let (mut sort, mut limit, mut skip) = (None, None, None); + for md in mods { + let a = parse_args(&md.args)?; + match md.name.as_str() { + "sort" => sort = Some(arg_doc(&a, 0, "sort")?), + "limit" => limit = a.first().and_then(|v| v.as_i64()).filter(|l| *l > 0), + "skip" => skip = a.first().and_then(|v| v.as_u64()), + "pretty" | "toArray" => {} + other => return Err(format!(".{other}() isn't supported here")), + } + } + let mut cursor = match head.name.as_str() { + "find" => { + let mut q = c.find(arg_doc(&args, 0, "filter")?).batch_size(1_000).comment(Bson::String(tag.to_string())); + if let Some(p) = args.get(1).filter(|v| v.is_object()) { + q = q.projection(to_doc(p, None)?); + } + if let Some(s) = sort { + q = q.sort(s); + } + if let Some(k) = skip { + q = q.skip(k); + } + if let Some(l) = limit { + q = q.limit(l); + } + q.await.map_err(err)? + } + _ => { + let pipeline = match args.first() { + Some(Value::Array(stages)) => stages.iter().map(|s| to_doc(s, None)).collect::, _>>()?, + _ => return Err("aggregate() takes an array of stages".into()), + }; + c.aggregate(pipeline).batch_size(1_000).comment(Bson::String(tag.to_string())).await.map_err(err)? + } + }; + + let mut sample: Vec = Vec::with_capacity(SAMPLE); + while sample.len() < SAMPLE { + match cursor.next().await { + Some(d) => sample.push(doc_to_json(&d.map_err(err)?)), + None => break, + } + } + let exhausted = sample.len() < SAMPLE; + if exhausted { + // Small: the collected shape, exactly as before. + return Ok(super::couchdb::docs_result(sample, None, stmt, t0)); + } + let shape = super::couchdb::docs_result(sample.clone(), None, stmt, t0); + let mut columns = shape.columns; + let names: Vec = columns.iter().map(|c| c.name.clone()).collect(); + let known: std::collections::HashSet = names.iter().cloned().collect(); + columns.push(super::query::ColumnInfo::new(OTHER_FIELDS, "object")); + sink.start(columns.clone())?; + let row_of = |d: &Value| -> Vec { + let mut row: Vec = names.iter().map(|n| super::couchdb::grid_cell(d.get(n).unwrap_or(&Value::Null)).0).collect(); + let extra: serde_json::Map = d + .as_object() + .map(|o| o.iter().filter(|(k, _)| !known.contains(*k)).map(|(k, v)| (k.clone(), v.clone())).collect()) + .unwrap_or_default(); + row.push(if extra.is_empty() { Value::Null } else { Value::Object(extra) }); + row + }; + let mut total = 0usize; + for d in &sample { + sink.push(row_of(d))?; + total += 1; + } + drop(sample); + while let Some(d) = cursor.next().await { + sink.push(row_of(&doc_to_json(&d.map_err(err)?)))?; + total += 1; + } + sink.finish()?; + Ok(super::query::SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: stmt.to_string() }) +} + pub async fn query(m: &MongoConn, stmt: &str) -> Result { let t0 = std::time::Instant::now(); let db_name = m.current_db.lock().map(|g| g.clone()).unwrap_or_default(); @@ -1476,37 +1826,7 @@ pub async fn query(m: &MongoConn, stmt: &str) -> Result { - let mut f = doc! { "find": coll.as_str(), "filter": arg_doc(&args, 0, "filter")? }; - if let Some(p) = args.get(1).filter(|v| v.is_object()) { - f.insert("projection", to_doc(p, None)?); - } - if let Some(s) = sort { - f.insert("sort", s); - } - if let Some(l) = limit { - f.insert("limit", l); - } - if let Some(k) = skip { - f.insert("skip", k as i64); - } - f - } - "aggregate" => { - let pipeline = match args.first() { - Some(Value::Array(stages)) => stages.iter().map(|s| to_doc(s, None)).collect::, _>>()?, - _ => return Err("aggregate() takes an array of stages".into()), - }; - doc! { "aggregate": coll.as_str(), "pipeline": pipeline, "cursor": {} } - } - "countDocuments" => doc! { "count": coll.as_str(), "query": arg_doc(&args, 0, "filter")? }, - "distinct" => { - let field = args.first().and_then(|v| v.as_str()).ok_or("distinct() takes a field name")?; - doc! { "distinct": coll.as_str(), "key": field, "query": arg_doc(&args, 1, "filter")? } - } - other => return Err(format!("{other}() can't be explained here; try find() or aggregate()")), - }; + let cmd = explain_cmd(&coll, head, &args, sort, limit, skip)?; let raw = m.client.database(&db_name).run_command(doc! { "explain": cmd, "verbosity": "executionStats" }).await.map_err(err)?; let sum = summarize_explain(&raw); let rows = sum @@ -1633,6 +1953,21 @@ pub async fn query(m: &MongoConn, stmt: &str) -> Result"), "{e}"); + // A bracket inside a string doesn't count. + assert!(parse_filter("{name: \"a}b\"}").is_ok()); + } + #[test] fn index_keys_read_as_fields() { let id = index_from_keys("users", "_id_".into(), &doc! {"_id": 1}, false); @@ -1740,7 +2075,7 @@ mod tests { #[tokio::test] #[ignore] async fn mongo_live() { - let m = connect(&MongoConfig { name: "t".into(), uri: "mongodb://localhost:27017".into(), database: Some("shop".into()) }).await.unwrap(); + let m = connect(&MongoConfig { ssh: None, name: "t".into(), uri: "mongodb://localhost:27017".into(), database: Some("shop".into()) }).await.unwrap(); let colls = list_collections(&m).await.unwrap(); assert!(colls.contains(&"shop.users".to_string()), "{colls:?}"); let info = describe(&m, "shop.orders").await.unwrap(); diff --git a/src-tauri/src/db/mssql.rs b/src-tauri/src/db/mssql.rs index 0dfc9e5e..fa487a85 100644 --- a/src-tauri/src/db/mssql.rs +++ b/src-tauri/src/db/mssql.rs @@ -3,6 +3,7 @@ use super::query::{ColumnInfo, ForeignKeyInfo, RowFilter, SqlResult, TableRows}; use super::schema::{ColumnStructureRow, IndexInfo, TableInfo}; use serde_json::Value; use std::collections::HashMap; +use chrono::Timelike; use std::time::Instant; use tiberius::{AuthMethod, Client, Config, EncryptionLevel, Row}; use tokio::net::TcpStream; @@ -10,6 +11,95 @@ use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt}; pub type MssqlClient = Client>; +// ── Stop ───────────────────────────────────────────────────────────────────── +// +// tiberius has no way to send SQL Server's attention signal, and dropping a +// query's future mid-stream leaves the TDS reply half read on the socket: the +// next query on that client would read the rest of the old one. So Stop does +// two things: `KILL`s the session from a second connection, which ends the +// statement on the server, and then `reset` swaps in a fresh client. +// +// The handle does not carry its config, so it is kept here, keyed by the +// handle's address, with the session id (`@@SPID`) to kill. + +static SESSIONS: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + +fn key(handle: &MssqlHandle) -> usize { + std::sync::Arc::as_ptr(handle) as *const () as usize +} + +async fn spid(client: &mut MssqlClient) -> Option { + let row = client.simple_query("SELECT CAST(@@SPID AS smallint)").await.ok()?.into_row().await.ok()??; + row.get::(0) +} + +/// Remember how to reach a handle's session, so Stop can kill it. +pub async fn remember(handle: &MssqlHandle, cfg: &MssqlConfig) { + let id = spid(&mut *handle.lock().await).await; + if let Some(id) = id { + SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).insert(key(handle), (cfg.clone(), id)); + } +} + +/// Drop a handle's registry entry once the handle is done with (a +/// transaction's own client). The entry holds the login, and the address it +/// is keyed by can be reused by the next handle. +pub fn forget(handle: &MssqlHandle) { + SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).remove(&key(handle)); +} + +/// A new client on the same server and login, for a transaction: on the +/// shared client every other query would have run inside it. +pub async fn open_tx_client(handle: &MssqlHandle) -> Result { + let cfg = SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).get(&key(handle)).map(|(c, _)| c.clone()); + let cfg = cfg.ok_or("This SQL Server connection can't open a second session. Reconnect and try again.")?; + let client = connect(&cfg).await?; + let h = std::sync::Arc::new(tokio::sync::Mutex::new(client)); + remember(&h, &cfg).await; + Ok(h) +} + +/// One batch on the handle, for BEGIN / COMMIT / ROLLBACK. +pub async fn batch(handle: &MssqlHandle, sql: &str) -> Result<(), String> { + let mut client = handle.lock().await; + client.simple_query(sql).await.map_err(|e| format!("MS SQL error: {e}"))?.into_results().await.map_err(|e| format!("MS SQL error: {e}"))?; + Ok(()) +} + +/// End the handle's running statement on the server. Best effort: KILL needs +/// ALTER ANY CONNECTION, and without it `reset` closing the socket is what +/// stops the work. +pub async fn cancel(handle: &MssqlHandle) { + let Some((cfg, id)) = SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).get(&key(handle)).cloned() else { return }; + let kill = async { + let mut other = connect(&cfg).await?; + other.simple_query(format!("KILL {id}")).await.map_err(|e| e.to_string())?.into_results().await.map_err(|e| e.to_string())?; + Ok::<(), String>(()) + }; + match tokio::time::timeout(std::time::Duration::from_secs(10), kill).await { + Ok(Ok(())) => {} + Ok(Err(e)) => log::info!("mssql stop: KILL {id} refused ({e}); closing the connection instead"), + Err(_) => log::info!("mssql stop: KILL {id} timed out; closing the connection instead"), + } +} + +/// Replace the handle's client after a Stop: the old socket is closed (which +/// also makes the server abandon anything still running) and the next query +/// gets a clean protocol stream. +pub async fn reset(handle: &MssqlHandle) -> Result<(), String> { + let Some((cfg, _)) = SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).get(&key(handle)).cloned() else { + return Err("The connection was stopped and can't be reopened here. Reconnect to keep working.".into()); + }; + let mut fresh = connect(&cfg).await?; + let id = spid(&mut fresh).await; + *handle.lock().await = fresh; + if let Some(id) = id { + SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).insert(key(handle), (cfg, id)); + } + Ok(()) +} + // ── Connect ────────────────────────────────────────────────────────────────── /// Open a tiberius client, following one Azure-style routing redirect if needed. @@ -18,7 +108,10 @@ pub type MssqlClient = Client>; /// bounds the whole attempt and reports which phase stalled. pub async fn connect(cfg: &MssqlConfig) -> Result { let config = build_config(cfg); - let addr = config.get_addr(); + // Through an SSH tunnel the socket goes to the tunnel's local end while + // the config keeps the server's name, which TLS checks the certificate + // against. + let addr = cfg.via.map(|a| a.to_string()).unwrap_or_else(|| config.get_addr()); let tcp = TcpStream::connect(&addr) .await .map_err(|e| format!("Can't reach {addr}: {e}"))?; @@ -100,6 +193,22 @@ pub async fn ping(handle: &MssqlHandle) -> Result<(), String> { // ── Cell conversion ────────────────────────────────────────────────────────── +/// A decimal's digits at its scale; a scale of 0 has no point. +fn numeric_text(n: tiberius::numeric::Numeric) -> String { + if n.scale() == 0 { n.value().to_string() } else { n.to_string() } +} + +/// A datetime as text. The legacy `datetime` counts in 1/300 s ticks, so .997 +/// arrived as .996666666; it is rounded to the millisecond SQL Server shows. +fn datetime_text(d: chrono::NaiveDateTime, legacy: bool) -> String { + if !legacy { + return d.format("%Y-%m-%d %H:%M:%S%.f").to_string(); + } + let ms = (d.and_utc().timestamp_subsec_nanos() as i64 + 500_000) / 1_000_000; + let d = d.with_nanosecond(0).unwrap_or(d) + chrono::Duration::milliseconds(ms); + d.format("%Y-%m-%d %H:%M:%S%.3f").to_string() +} + /// Convert one cell to JSON by probing the column's concrete Rust type. /// tiberius `try_get` fails (not panics) on a type mismatch, so the cascade /// lands on the first type whose `FromSql` matches the column. @@ -133,8 +242,25 @@ fn cell_to_json(row: &Row, i: usize) -> Value { try_scalar!(f64, |f| serde_json::Number::from_f64(f).map(Value::Number).unwrap_or(Value::Null)); try_scalar!(f32, |f| serde_json::Number::from_f64(f as f64).map(Value::Number).unwrap_or(Value::Null)); + // decimal/numeric as exact text: an f64 would round a decimal(38) and drop + // the scale's trailing zeros (12.50 became 12.5). Before this case the + // cascade found no match and every decimal cell read NULL. + if let Ok(v) = row.try_get::(i) { + return v.map(|n| Value::String(numeric_text(n))).unwrap_or(Value::Null); + } + // uniqueidentifier, upper case as SQL Server prints it (it read NULL too). + if let Ok(v) = row.try_get::(i) { + return v.map(|u| Value::String(u.to_string().to_uppercase())).unwrap_or(Value::Null); + } + if let Ok(v) = row.try_get::, usize>(i) { + return v.map(|d| Value::String(d.format("%Y-%m-%d %H:%M:%S%.f %:z").to_string())).unwrap_or(Value::Null); + } if let Ok(v) = row.try_get::(i) { - return v.map(|d| Value::String(d.format("%Y-%m-%d %H:%M:%S%.f").to_string())).unwrap_or(Value::Null); + let legacy = matches!( + row.columns().get(i).map(|c| c.column_type()), + Some(tiberius::ColumnType::Datetime | tiberius::ColumnType::Datetimen) + ); + return v.map(|d| Value::String(datetime_text(d, legacy))).unwrap_or(Value::Null); } if let Ok(v) = row.try_get::(i) { return v.map(|d| Value::String(d.to_string())).unwrap_or(Value::Null); @@ -148,13 +274,54 @@ fn cell_to_json(row: &Row, i: usize) -> Value { Value::Null } +/// A result column's type as SQL Server names it. The wire type's Rust name +/// (`format!("{:?}")`) showed `int4`, `intn`, `bitn` and `datetimen` in the +/// grid. The nullable wire types (`Intn`, `Floatn`, `Datetimen`) don't carry +/// their width, so they read as the family name: a nullable bigint is `int`. +fn type_name(t: tiberius::ColumnType) -> &'static str { + use tiberius::ColumnType as T; + match t { + T::Null => "null", + T::Bit | T::Bitn => "bit", + T::Int1 => "tinyint", + T::Int2 => "smallint", + T::Int4 | T::Intn => "int", + T::Int8 => "bigint", + T::Float4 => "real", + T::Float8 | T::Floatn => "float", + T::Money => "money", + T::Money4 => "smallmoney", + T::Decimaln => "decimal", + T::Numericn => "numeric", + T::Datetime | T::Datetimen => "datetime", + T::Datetime4 => "smalldatetime", + T::Datetime2 => "datetime2", + T::DatetimeOffsetn => "datetimeoffset", + T::Daten => "date", + T::Timen => "time", + T::Guid => "uniqueidentifier", + T::BigVarChar => "varchar", + T::BigChar => "char", + T::NVarchar => "nvarchar", + T::NChar => "nchar", + T::BigVarBin => "varbinary", + T::BigBinary => "binary", + T::Text => "text", + T::NText => "ntext", + T::Image => "image", + T::Xml => "xml", + T::Udt => "udt", + T::SSVariant => "sql_variant", + } +} + fn rows_to_result(rows: &[Row], elapsed: u64) -> SqlResult { let columns: Vec = rows .first() .map(|r| { r.columns() .iter() - .map(|c| ColumnInfo::new(c.name().to_string(), format!("{:?}", c.column_type()).to_lowercase())) + .map(|c| ColumnInfo::new(c.name().to_string(), type_name(c.column_type()).to_string())) .collect() }) .unwrap_or_default(); @@ -255,13 +422,64 @@ pub async fn execute_sql(handle: &MssqlHandle, sql: &str) -> Result Result { + use futures::TryStreamExt; + let t0 = Instant::now(); + let mut client = handle.lock().await; + let mut stream = client.simple_query(sql).await.map_err(|e| format!("MS SQL error: {e}"))?; + let mut columns: Vec = Vec::new(); + let mut total = 0usize; + let mut sink_err: Option = None; + while let Some(item) = stream.try_next().await.map_err(|e| format!("MS SQL error: {e}"))? { + match item { + tiberius::QueryItem::Metadata(m) if m.result_index() == 0 => { + columns = m + .columns() + .iter() + .map(|c| ColumnInfo::new(c.name().to_string(), type_name(c.column_type()).to_string())) + .collect(); + } + tiberius::QueryItem::Row(r) if r.result_index() == 0 && sink_err.is_none() => { + if total == 0 { + if let Err(e) = sink.start(columns.clone()) { + sink_err = Some(e); + continue; + } + } + match sink.push((0..r.columns().len()).map(|i| cell_to_json(&r, i)).collect()) { + Ok(()) => total += 1, + Err(e) => sink_err = Some(e), + } + } + _ => {} + } + } + drop(stream); + if let Some(e) = sink_err { + return Err(e); + } + if total > 0 { + sink.finish()?; + } + Ok(SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + +/// Whether `sql` reads (and so has rows to stream). +pub(crate) fn reads(sql: &str) -> bool { + is_read_query(sql) +} + /// Run a read query and return the first result set's rows (helper for introspection). async fn fetch_rows(handle: &MssqlHandle, sql: &str) -> Result, String> { let mut client = handle.lock().await; @@ -764,11 +982,20 @@ fn sql_literal(v: &Value) -> String { Value::Null => "NULL".to_string(), Value::Bool(b) => if *b { "1".to_string() } else { "0".to_string() }, Value::Number(n) => n.to_string(), - Value::String(s) => format!("'{}'", esc_literal(s)), - other => format!("'{}'", esc_literal(&other.to_string())), + Value::String(s) => str_literal(s), + other => str_literal(&other.to_string()), } } +/// A T-SQL string. Non-ASCII text is written N'...': a plain literal is +/// converted to the database's code page first, so an edit to Chinese or +/// Cyrillic text was stored as question marks. ASCII stays plain, which keeps +/// a lookup on a varchar key from converting the whole index to nvarchar. +fn str_literal(s: &str) -> String { + let n = if s.is_ascii() { "" } else { "N" }; + format!("{n}'{}'", esc_literal(s)) +} + fn pk_where(pk: &HashMap) -> String { let clauses: Vec = pk.iter().map(|(c, v)| format!("{} = {}", quote_ident(c), sql_literal(v))).collect(); format!(" WHERE {}", clauses.join(" AND ")) @@ -843,24 +1070,106 @@ pub async fn delete_table_rows( Ok(deleted) } +#[cfg(test)] +mod literal_tests { + use serde_json::json; + #[test] + fn unicode_strings_get_the_n_prefix() { + assert_eq!(super::sql_literal(&json!("東京")), "N'東京'"); + assert_eq!(super::sql_literal(&json!("O'Neil")), "'O''Neil'"); + assert_eq!(super::sql_literal(&json!(7)), "7"); + } +} + #[cfg(test)] mod tests { use super::*; use crate::db::connection::open_mssql; fn test_config() -> MssqlConfig { - MssqlConfig { + // STROKE_TEST_MSSQL=host:port:user:password, as tx.rs reads it. + let spec = std::env::var("STROKE_TEST_MSSQL").ok(); + let parts: Vec<&str> = spec.as_deref().map(|s| s.splitn(4, ':').collect()).unwrap_or_default(); + let get = |i: usize, d: &str| parts.get(i).map(|s| s.to_string()).unwrap_or_else(|| d.to_string()); + MssqlConfig { ssh: None, via: None, name: "test".into(), - host: "127.0.0.1".into(), - port: 1433, + host: get(0, "127.0.0.1"), + port: get(1, "1433").parse().unwrap_or(1433), database: "master".into(), - user: "sa".into(), - password: "Strong!Passw0rd".into(), + user: get(2, "sa"), + password: get(3, "Strong!Passw0rd"), encrypt: false, trust_cert: true, } } + #[test] + fn legacy_datetime_rounds_to_the_millisecond() { + let d = chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap().and_hms_nano_opt(3, 4, 5, 996_666_666).unwrap(); + assert_eq!(datetime_text(d, true), "2026-01-02 03:04:05.997"); + assert_eq!(datetime_text(d, false), "2026-01-02 03:04:05.996666666"); + let edge = chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap().and_hms_nano_opt(23, 59, 59, 999_700_000).unwrap(); + assert_eq!(datetime_text(edge, true), "2026-01-03 00:00:00.000"); + } + + // Requires a live SQL Server (STROKE_TEST_MSSQL); run with --ignored. + #[tokio::test] + #[ignore] + async fn cell_values_live() { + let h = open_mssql(&test_config()).await.expect("connect"); + let r = execute_sql( + &h, + "SELECT CAST(12.50 AS decimal(10,2)) AS d, CAST(7 AS decimal(5,0)) AS d0, \ + CAST('6F9619FF-8B86-D011-B42D-00C04FC964FF' AS uniqueidentifier) AS g, \ + CAST('2026-01-02 03:04:05 +05:45' AS datetimeoffset(0)) AS o, \ + CAST('2026-01-02 03:04:05.997' AS datetime) AS dt, CAST(NULL AS decimal(5,2)) AS n", + ) + .await + .unwrap(); + assert_eq!( + r.rows[0], + vec![ + Value::from("12.50"), + Value::from("7"), + Value::from("6F9619FF-8B86-D011-B42D-00C04FC964FF"), + Value::from("2026-01-02 03:04:05 +05:45"), + Value::from("2026-01-02 03:04:05.997"), + Value::Null, + ] + ); + } + + #[test] + fn result_types_use_sql_server_names() { + use tiberius::ColumnType as T; + assert_eq!(type_name(T::Int4), "int"); + assert_eq!(type_name(T::Intn), "int"); + assert_eq!(type_name(T::Bitn), "bit"); + assert_eq!(type_name(T::NVarchar), "nvarchar"); + assert_eq!(type_name(T::Guid), "uniqueidentifier"); + assert_eq!(type_name(T::Datetimen), "datetime"); + } + + // Requires a live SQL Server (STROKE_TEST_MSSQL); run with --ignored. + #[tokio::test] + #[ignore] + async fn result_types_live() { + let h = open_mssql(&test_config()).await.expect("connect"); + let r = execute_sql( + &h, + "SELECT CAST(1 AS int) AS a, CAST(NULL AS int) AS b, CAST(1 AS bit) AS c, CAST(1 AS bigint) AS d, \ + N'x' AS e, NEWID() AS f, SYSDATETIME() AS g, CAST(1.5 AS decimal(5,2)) AS h", + ) + .await + .unwrap(); + let types: Vec<&str> = r.columns.iter().map(|c| c.data_type.as_str()).collect(); + assert!(types.iter().all(|t| !t.ends_with('n') || *t == "nvarchar"), "{types:?}"); + assert_eq!(types[0], "int"); + assert_eq!(types[2], "bit"); + assert_eq!(types[4], "nvarchar"); + assert_eq!(types[5], "uniqueidentifier"); + } + #[test] fn showplan_all_batches_turn_plan_mode_off_last() { let [on, query, off] = showplan_all_batches(" SELECT * FROM t WHERE id = 1; "); @@ -915,9 +1224,49 @@ mod tests { let _ddl = get_ddl(&h, "dbo", "t_users").await.unwrap(); update_table_cell(&h, "dbo", "t_users", std::collections::HashMap::from([("id".into(), Value::from(1))]), "name", &Value::from("ada2")).await.unwrap(); + // Non-ASCII text survives an edit: a plain '...' literal was converted + // to the code page and stored question marks. + update_table_cell(&h, "dbo", "t_users", std::collections::HashMap::from([("id".into(), Value::from(1))]), "name", &Value::from("東京 Zoë")).await.unwrap(); + let back = execute_sql(&h, "SELECT name FROM dbo.t_users WHERE id = 1").await.unwrap(); + assert_eq!(back.rows[0][0], Value::from("東京 Zoë")); let deleted = delete_table_rows(&h, "dbo", "t_users", vec![std::collections::HashMap::from([("id".into(), Value::from(2))])]).await.unwrap(); assert_eq!(deleted, 1); execute_sql(&h, "DROP TABLE dbo.t_users").await.unwrap(); + + // New table's SQL Server starter (sql-complete-data.js), filled in, runs. + execute_sql(&h, "IF OBJECT_ID('dbo.t_starter','U') IS NOT NULL DROP TABLE dbo.t_starter").await.unwrap(); + execute_sql(&h, "CREATE TABLE t_starter (\n id bigint IDENTITY(1,1) PRIMARY KEY,\n label nvarchar(255) NOT NULL,\n created_at datetime2 NOT NULL DEFAULT sysutcdatetime()\n)").await.unwrap(); + execute_sql(&h, "DROP TABLE dbo.t_starter").await.unwrap(); + } +} + +#[cfg(test)] +mod via_tests { + // The socket goes to `via` while the config keeps the server's name. With + // a name that does not resolve and something listening at `via` that is + // not SQL Server, the connect must get as far as the handshake: failing on + // a lookup or "Can't reach" would mean the name was dialed. + // STROKE_TEST_FAKE_RESP=127.0.0.1:16390 cargo test --lib mssql::via_tests + #[tokio::test] + async fn dials_the_tunnel_and_keeps_the_name() { + let Ok(addr) = std::env::var("STROKE_TEST_FAKE_RESP") else { return }; + let cfg = super::MssqlConfig { + name: "t".into(), + host: "mssql.stroke.test".into(), + port: 1433, + database: "master".into(), + user: "sa".into(), + password: "x".into(), + encrypt: false, + trust_cert: false, + ssh: None, + via: Some(addr.parse().unwrap()), + }; + let err = tokio::time::timeout(std::time::Duration::from_secs(5), super::connect(&cfg)) + .await + .map(|r| r.err().unwrap_or_default()) + .unwrap_or_else(|_| "handshake stalled (reached the listener)".into()); + assert!(!err.contains("Can't reach") && !err.to_lowercase().contains("lookup"), "{err}"); } } diff --git a/src-tauri/src/db/mysql.rs b/src-tauri/src/db/mysql.rs index ad26cc14..e0a84e65 100644 --- a/src-tauri/src/db/mysql.rs +++ b/src-tauri/src/db/mysql.rs @@ -271,6 +271,50 @@ fn searchable_columns(columns: &[(String, String)], term: &str) -> Vec { .collect() } +/// The values of a MySQL `enum('a','b','it''s')` column type, in order. +fn enum_values(column_type: &str) -> Option> { + let t = column_type.trim(); + let inner = t.strip_prefix("enum(").or_else(|| t.strip_prefix("ENUM("))?.strip_suffix(')')?; + let mut out = Vec::new(); + let mut chars = inner.chars().peekable(); + loop { + while chars.peek().is_some_and(|c| *c == ',' || c.is_whitespace()) { + chars.next(); + } + if chars.next()? != '\'' { + return None; + } + let mut v = String::new(); + loop { + match chars.next()? { + '\'' if chars.peek() == Some(&'\'') => { + chars.next(); + v.push('\''); + } + '\'' => break, + '\\' => v.push(chars.next()?), + c => v.push(c), + } + } + out.push(v); + if chars.peek().is_none() { + return Some(out); + } + } +} + +#[cfg(test)] +mod enum_values_tests { + #[test] + fn reads_an_enum_column_type() { + assert_eq!(super::enum_values("enum('book','game','tool')").unwrap(), ["book", "game", "tool"]); + // As information_schema writes them: a quote doubled, a backslash escaped. + assert_eq!(super::enum_values(r"ENUM('it''s', 'a,b', 'x\\y')").unwrap(), ["it's", "a,b", r"x\y"]); + assert_eq!(super::enum_values("varchar(20)"), None); + assert_eq!(super::enum_values("enum('open"), None); + } +} + #[cfg(test)] fn build_where(columns: &[String], search: Option<&str>, search_is_regex: bool, search_case_sensitive: bool, filters: &[RowFilter]) -> Result { build_where_searching(columns, None, search, search_is_regex, search_case_sensitive, filters) @@ -442,7 +486,7 @@ pub async fn get_table_rows( // fetch; and a plain open (no search, filter or sort) doesn't need the column // list to build its query, so the column metadata joins it too: one stage. let meta_q = sqlx::query( - "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, EXTRA, COLUMN_DEFAULT \ + "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, EXTRA, COLUMN_DEFAULT, COLUMN_TYPE \ FROM information_schema.COLUMNS \ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION", ) @@ -570,7 +614,26 @@ pub async fn get_table_rows( .collect() }; + // The catalog's type over the wire's: a result names a binary-collation + // text column "BLOB", which is how MariaDB's JSON (LONGTEXT, utf8mb4_bin) + // read in the grid header, and an ENUM can come back as plain CHAR. + let declared: HashMap = meta_rows + .iter() + .filter_map(|r| Some((my_text(r, 0)?, my_text(r, 1)?.to_lowercase()))) + .collect(); + // An ENUM's values, so its cell edits from a list as a Postgres enum does; + // it opened as free text, where a typo is an error from the server. + let enums: HashMap> = meta_rows + .iter() + .filter_map(|r| Some((my_text(r, 0)?, enum_values(&my_text(r, 5)?)?))) + .collect(); for col in &mut columns { + if let Some(t) = declared.get(&col.name).filter(|t| !t.is_empty()) { + col.data_type = t.clone(); + } + if let Some(v) = enums.get(&col.name) { + col.enum_values = Some(v.clone()); + } if let Some(f) = flags_map.get(&col.name) { col.nullable = f.nullable; col.auto_generated = f.auto_generated; @@ -661,20 +724,7 @@ pub async fn execute_sql( .await .map_err(|e| format!("Failed to acquire connection: {e}"))?; if let Some(rx) = cancel_rx { - if let Ok(conn_id) = sqlx::query_scalar::<_, u64>("SELECT CONNECTION_ID()") - .fetch_one(&mut *conn) - .await - { - let cancel_pool = pool.clone(); - tokio::spawn(async move { - if rx.await.is_ok() { - // conn_id is a numeric id from the server; safe to inline. - let _ = sqlx::query(&format!("KILL QUERY {conn_id}")) - .execute(&cancel_pool) - .await; - } - }); - } + arm_kill(pool, &mut conn, rx).await; } // A script (`CREATE DATABASE x; USE x; CREATE TABLE …`) cannot go through @@ -704,6 +754,76 @@ pub async fn execute_sql( result } +/// Arm Stop for a run on `conn`: `KILL QUERY` its connection id from another +/// pooled connection when `rx` fires. The run's end drops the sender, which +/// disarms it. +async fn arm_kill(pool: &MySqlPool, conn: &mut sqlx::pool::PoolConnection, rx: tokio::sync::oneshot::Receiver<()>) { + if let Ok(conn_id) = sqlx::query_scalar::<_, u64>("SELECT CONNECTION_ID()").fetch_one(&mut **conn).await { + let cancel_pool = pool.clone(); + tokio::spawn(async move { + if rx.await.is_ok() { + // conn_id is a numeric id from the server; safe to inline. + let _ = sqlx::query(&format!("KILL QUERY {conn_id}")).execute(&cancel_pool).await; + } + }); + } +} + +/// One row-returning statement, streamed into the console's sink as it +/// arrives instead of collected: a 2 GB result no longer needs 2 GB here, a +/// JSON reply as large, and the window's heap after that. Rows go to the +/// result store when the sink has one. Stop is KILL QUERY, as in `execute_sql`. +pub async fn stream_into( + pool: &MySqlPool, + sql: &str, + sink: &mut super::query::RowSink, + cancel_rx: tokio::sync::oneshot::Receiver<()>, +) -> Result { + let started = Instant::now(); + let mut conn = pool.acquire().await.map_err(|e| format!("Failed to acquire connection: {e}"))?; + arm_kill(pool, &mut conn, cancel_rx).await; + let mut columns: Vec = Vec::new(); + let mut total = 0usize; + let mut text_protocol = false; + loop { + let mut stream = if text_protocol { sqlx::Executor::fetch(&mut *conn, sql) } else { sqlx::query(sql).fetch(&mut *conn) }; + let outcome: Result<(), sqlx::Error> = async { + while let Some(row) = stream.try_next().await? { + if total == 0 { + columns = row.columns().iter().map(|c| ColumnInfo::new(c.name(), c.type_info().name().to_lowercase())).collect(); + sink.start(columns.clone()).map_err(sqlx::Error::Protocol)?; + } + sink.push((0..row.len()).map(|i| cell_to_json(&row, i)).collect()).map_err(sqlx::Error::Protocol)?; + total += 1; + } + Ok(()) + } + .await; + drop(stream); + match outcome { + // Some statements can't be prepared: run them again as text, once, + // if nothing has streamed yet. + Err(e) if total == 0 && !text_protocol && unsupported_in_prepared(&e) => text_protocol = true, + Err(e) => return Err(format!("Query failed: {e}")), + Ok(()) => break, + } + } + if total > 0 { + sink.finish()?; + } else { + // No row to read the columns off: an empty SELECT showed no headers. + columns = describe_columns(&mut conn, sql).await; + } + Ok(SqlResult { + columns, + rows: vec![], + row_count: Some(total as i64), + message: None, + query_ms: started.elapsed().as_millis() as u64, + sql: sql.to_string(), + }) +} + /// Put a connection that ran `USE` back on the pool's own database. Left as it /// was, the connection went back to the pool still pointed at the other /// database, and whichever later call happened to draw it ran there: a @@ -768,12 +888,35 @@ async fn run_script_on( columns: vec![], rows: vec![], row_count: Some(affected), - message: Some(format!("{n} statements ran, {affected} row(s) affected")), + message: Some(format!("{n} statements ran, {}", super::query::affected_message("", affected))), query_ms, sql: joined, }) } +/// A connection that writes DDL the way a stock server reads it. The app's pool +/// turns on ANSI_QUOTES (see connection.rs), which makes SHOW CREATE use double +/// quotes: a dump restored with the mysql client, or DDL pasted elsewhere, +/// failed on CREATE TABLE "products". This one has ANSI_QUOTES off, and is +/// detached so the changed mode never goes back into the pool. +pub(crate) async fn backtick_conn(pool: &MySqlPool) -> Result { + let mut conn = pool.acquire().await.map_err(|e| format!("Failed to acquire connection: {e}"))?.detach(); + sqlx::query("SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', @@SESSION.sql_mode, ','), ',ANSI_QUOTES,', ','))") + .execute(&mut conn) + .await + .map_err(|e| format!("Failed to set sql_mode: {e}"))?; + Ok(conn) +} + +/// A statement's result columns, without running it again: what an empty result +/// reports. Empty when the server can't prepare it (SHOW and the like). +async fn describe_columns(conn: &mut sqlx::MySqlConnection, sql: &str) -> Vec { + match sqlx::Executor::describe(conn, sql).await { + Ok(d) => d.columns().iter().map(|c| ColumnInfo::new(c.name(), c.type_info().name().to_lowercase())).collect(), + Err(_) => Vec::new(), + } +} + /// A statement's first line, cut to 120 characters, for an error message. fn first_line(sql: &str) -> String { let line = sql.trim().lines().next().unwrap_or(""); @@ -798,17 +941,15 @@ async fn run_one_on(conn: &mut sqlx::MySqlConnection, sql: &str) -> Result other, } .map_err(|e| format!("Query failed: {e}"))?; + // An empty result has no row to read its columns off. + let columns = if columns.is_empty() { describe_columns(conn, sql).await } else { columns }; let row_count = data.len() as i64; return Ok(SqlResult { columns, rows: data, row_count: Some(row_count), - message: if capped { - Some(format!("Result capped at {EXECUTE_SQL_MAX_ROWS} rows - add a LIMIT clause to fetch a specific range.")) - } else { - None - }, + message: if capped { Some(super::query::budget_message(row_count as usize)) } else { None }, query_ms: query_ms(), sql: sql.to_string(), }); @@ -824,7 +965,7 @@ async fn run_one_on(conn: &mut sqlx::MySqlConnection, sql: &str) -> Result Result<(Vec, Vec>, bool), sqlx::Error> { let mut columns: Vec = Vec::new(); let mut data: Vec> = Vec::new(); + let mut budget = super::query::CollectBudget::default(); while let Some(row) = stream.try_next().await? { if data.is_empty() { columns = row @@ -857,8 +999,10 @@ async fn collect_result_rows( .map(|c| ColumnInfo::new(c.name(), c.type_info().name().to_lowercase())) .collect(); } - data.push((0..row.len()).map(|i| cell_to_json(&row, i)).collect()); - if data.len() >= EXECUTE_SQL_MAX_ROWS { + let cells: Vec = (0..row.len()).map(|i| cell_to_json(&row, i)).collect(); + let fits = budget.take(&cells); + data.push(cells); + if !fits || data.len() >= EXECUTE_SQL_MAX_ROWS { return Ok((columns, data, true)); } } @@ -1296,6 +1440,7 @@ mod ai_tool_live { let spec = std::env::var("STROKE_AI_MYSQL").ok()?; let p: Vec<&str> = spec.splitn(5, ':').collect(); Some(MysqlConfig { + via: None, name: "ai".into(), host: p[0].into(), port: p[1].parse().unwrap(), @@ -1408,3 +1553,18 @@ mod search_pruning_tests { assert_eq!(a.binds.len(), 2); } } + +#[cfg(test)] +mod empty_result_tests { + /// Against MySQL or MariaDB (STROKE_TEST_MYSQL_URL, a mysql:// URL with a + /// database): a SELECT that matches nothing still names its columns. + #[tokio::test] + async fn live_empty_select_keeps_its_columns() { + let Ok(url) = std::env::var("STROKE_TEST_MYSQL_URL") else { return }; + let pool = sqlx::MySqlPool::connect(&url).await.unwrap(); + let mut conn = pool.acquire().await.unwrap(); + let r = super::run_one_on(&mut conn, "SELECT 1 AS n, 'x' AS label FROM DUAL WHERE 1 = 0").await.unwrap(); + assert!(r.rows.is_empty()); + assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::>(), ["n", "label"]); + } +} diff --git a/src-tauri/src/db/neo4j.rs b/src-tauri/src/db/neo4j.rs new file mode 100644 index 00000000..0be2f3b6 --- /dev/null +++ b/src-tauri/src/db/neo4j.rs @@ -0,0 +1,427 @@ +//! Neo4j over its HTTP API (the transactional endpoint, Neo4j 4.x and 5.x). Beta. +//! +//! The document browser shows node labels as collections and nodes as +//! documents: each with its element id, its labels and its properties. The +//! console runs Cypher. Every value goes in as a query parameter. +//! +//! Access levels for agents read the Cypher itself: MATCH ... RETURN reads, +//! CREATE / MERGE / SET / DELETE / REMOVE write, index or constraint changes +//! alter the schema, and databases, users and privileges are dangerous. + +use super::query::{ColumnInfo, SqlResult}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Neo4jConfig { + pub name: String, + /// The HTTP address: http://localhost:7474, or https:// for Aura and TLS. + pub url: String, + /// The database; `neo4j` when blank. + #[serde(default)] + pub database: Option, + #[serde(default)] + pub user: Option, + #[serde(default)] + pub password: Option, +} + +/// Rows a console statement returns. +const MAX_ROWS: usize = 10_000; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| crate::proxy::http_builder(crate::proxy::Kind::Database).timeout(Duration::from_secs(120)).connect_timeout(Duration::from_secs(10)).build().unwrap_or_default()) +} + +fn database(cfg: &Neo4jConfig) -> String { + cfg.database.as_deref().map(str::trim).filter(|d| !d.is_empty()).unwrap_or("neo4j").to_string() +} + +fn base(cfg: &Neo4jConfig) -> String { + let u = cfg.url.trim().trim_end_matches('/'); + // A bolt:// or neo4j:// address from a driver config: the HTTP API is on 7474. + if let Some(rest) = u.strip_prefix("bolt://").or_else(|| u.strip_prefix("neo4j://")) { + let host = rest.split(':').next().unwrap_or(rest); + return format!("http://{host}:7474"); + } + if u.contains("://") { u.to_string() } else { format!("http://{u}") } +} + +/// Run statements in one transaction; the results, in order. +async fn run(cfg: &Neo4jConfig, statements: Vec<(String, Value)>) -> Result, String> { + let url = format!("{}/db/{}/tx/commit", base(cfg), urlencoding::encode(&database(cfg))); + let body = json!({ + "statements": statements + .into_iter() + .map(|(s, p)| json!({ "statement": s, "parameters": p, "resultDataContents": ["row"], "includeStats": true })) + .collect::>(), + }); + let mut req = client().post(&url).json(&body).header("Accept", "application/json;charset=UTF-8"); + if let Some(u) = cfg.user.as_deref().filter(|u| !u.is_empty()) { + req = req.basic_auth(u, cfg.password.as_deref()); + } + let resp = req.send().await.map_err(|e| { + if e.is_connect() { + format!("Could not reach Neo4j at {}: is it running, and is the HTTP port (7474) open?", base(cfg)) + } else { + format!("Neo4j request failed: {e}") + } + })?; + let status = resp.status().as_u16(); + let text = resp.text().await.map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if status == 401 { + return Err("Neo4j refused the user name or password".into()); + } + if let Some(err) = v["errors"].as_array().and_then(|e| e.first()) { + let code = err["code"].as_str().unwrap_or(""); + let msg = err["message"].as_str().unwrap_or("Neo4j error"); + return Err(if code.is_empty() { msg.to_string() } else { format!("{msg} ({})", code.rsplit('.').next().unwrap_or(code)) }); + } + if status >= 400 { + return Err(format!("Neo4j answered HTTP {status}: {}", text.chars().take(300).collect::())); + } + Ok(v["results"].as_array().cloned().unwrap_or_default()) +} + +async fn run_one(cfg: &Neo4jConfig, statement: &str, params: Value) -> Result { + run(cfg, vec![(statement.to_string(), params)]).await?.into_iter().next().ok_or_else(|| "Neo4j returned no result".to_string()) +} + +pub async fn connect(cfg: &Neo4jConfig) -> Result { + if cfg.url.trim().is_empty() { + return Err("Enter the Neo4j address".into()); + } + run_one(cfg, "RETURN 1", json!({})).await?; + Ok(cfg.clone()) +} + +fn kind_of(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "BOOLEAN", + Value::Number(n) if n.is_i64() || n.is_u64() => "INTEGER", + Value::Number(_) => "FLOAT", + Value::String(_) => "STRING", + Value::Array(_) => "LIST", + Value::Object(_) => "MAP", + } +} + +/// A Cypher statement from the console, as a table. +pub async fn query(cfg: &Neo4jConfig, stmt: &str) -> Result { + let t0 = Instant::now(); + let sql = stmt.trim().trim_end_matches(';').trim(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let r = run_one(cfg, sql, json!({})).await?; + let names: Vec = r["columns"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(String::from)).collect(); + let data = r["data"].as_array().cloned().unwrap_or_default(); + let total = data.len(); + let rows: Vec> = data + .into_iter() + .take(MAX_ROWS) + .map(|d| d["row"].as_array().cloned().unwrap_or_default().into_iter().map(|v| super::sql_util::cap_json_value("text", v)).collect()) + .collect(); + // Types from the first non-null value in each column. + let columns = names + .iter() + .enumerate() + .map(|(i, n)| ColumnInfo::new(n.clone(), rows.iter().map(|r| kind_of(&r[i])).find(|k| *k != "null").unwrap_or("ANY"))) + .collect(); + let (row_count, message) = if names.is_empty() { + let s = &r["stats"]; + let parts: Vec = ["nodes_created", "nodes_deleted", "relationships_created", "relationships_deleted", "properties_set"] + .iter() + .filter_map(|k| s[*k].as_i64().filter(|n| *n > 0).map(|n| format!("{n} {}", k.replace('_', " ")))) + .collect(); + (Some(0), Some(if parts.is_empty() { "Done".into() } else { parts.join(", ") })) + } else { + let msg = (total > rows.len()).then(|| format!("Showing the first {} of {total} rows", rows.len())); + (Some(rows.len() as i64), msg) + }; + Ok(SqlResult { columns, rows, row_count, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + +/// The planner's plan for a statement (EXPLAIN: nothing runs), as the +/// Postgres-shaped tree the plan viewer draws. +pub async fn explain_plan(cfg: &Neo4jConfig, stmt: &str) -> Result { + let s = stmt.trim().trim_end_matches(';').trim(); + let upper = s.to_ascii_uppercase(); + let body = if upper.starts_with("EXPLAIN ") || upper.starts_with("PROFILE ") { &s[8..] } else { s }; + let r = run_one(cfg, &format!("EXPLAIN {body}"), json!({})).await?; + let root = &r["plan"]["root"]; + if root.is_null() { + return Err("Neo4j returned no plan for this statement".into()); + } + Ok(plan_node(root)) +} + +fn plan_node(op: &Value) -> Value { + let mut n = Map::new(); + let kind = op["operatorType"].as_str().unwrap_or("Operator"); + n.insert("Node Type".into(), json!(kind.split('@').next().unwrap_or(kind))); + if let Some(d) = op["Details"].as_str().filter(|d| !d.is_empty()) { + n.insert("Filter".into(), json!(d)); + } + if let Some(rows) = op["EstimatedRows"].as_f64() { + n.insert("Plan Rows".into(), json!(rows.round() as i64)); + } + if let Some(ids) = op["identifiers"].as_array().filter(|a| !a.is_empty()) { + n.insert("Output".into(), Value::Array(ids.clone())); + } + let kids: Vec = op["children"].as_array().into_iter().flatten().map(plan_node).collect(); + if !kids.is_empty() { + n.insert("Plans".into(), Value::Array(kids)); + } + Value::Object(n) +} + +/// The access level a Cypher script needs: 0 read, 1 write, 2 schema, +/// 3 server administration (the levels of `mcp::access`). +pub fn cypher_level(stmt: &str) -> u8 { + // Strings and comments can't change the level: strip them first. + let mut clean = String::with_capacity(stmt.len()); + let mut chars = stmt.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '\'' | '"' | '`' => { + let q = c; + while let Some(d) = chars.next() { + if d == '\\' { + chars.next(); + } else if d == q { + break; + } + } + clean.push(' '); + } + '/' if chars.peek() == Some(&'/') => { + for d in chars.by_ref() { + if d == '\n' { + break; + } + } + } + '/' if chars.peek() == Some(&'*') => { + chars.next(); + let mut prev = ' '; + for d in chars.by_ref() { + if prev == '*' && d == '/' { + break; + } + prev = d; + } + } + c => clean.push(c.to_ascii_uppercase()), + } + } + let words: Vec<&str> = clean.split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.').filter(|w| !w.is_empty()).collect(); + let has = |w: &str| words.contains(&w); + // Databases, users, roles and privileges: the server's administration. + let admin = words.windows(2).any(|p| { + matches!(p[0], "CREATE" | "DROP" | "ALTER" | "START" | "STOP" | "RENAME" | "REPLACE") + && matches!(p[1], "DATABASE" | "COMPOSITE" | "USER" | "ROLE" | "ALIAS" | "SERVER" | "OR") + }) || ["GRANT", "REVOKE", "DENY", "ALTER"].iter().any(|w| has(w)); + if admin { + return 3; + } + let schema = words.windows(2).any(|p| { + matches!(p[0], "CREATE" | "DROP") + && matches!(p[1], "INDEX" | "CONSTRAINT" | "FULLTEXT" | "RANGE" | "TEXT" | "POINT" | "LOOKUP" | "VECTOR" | "BTREE") + }); + if schema { + return 2; + } + // Procedures can write (apoc.create.*, db.create.*, ...): any CALL + // that isn't a known read counts as a write. + let writing_call = words.windows(2).any(|p| { + p[0] == "CALL" + && !(p[1].starts_with("DB.LABELS") || p[1].starts_with("DB.RELATIONSHIPTYPES") || p[1].starts_with("DB.PROPERTYKEYS") || p[1].starts_with("DB.SCHEMA.") || p[1].starts_with("DB.INDEXES") || p[1].starts_with("DB.CONSTRAINTS") || p[1].starts_with("DBMS.COMPONENTS") || p[1].starts_with("SHOW")) + }); + if ["CREATE", "MERGE", "SET", "DELETE", "DETACH", "REMOVE", "FOREACH", "LOAD"].iter().any(|w| has(w)) || writing_call { + 1 + } else { + 0 + } +} + +// ── The document browser ────────────────────────────────────────────────────── + +fn label_ident(label: &str) -> String { + format!("`{}`", label.replace('`', "``")) +} + +/// Node labels, with how many nodes carry each. +pub async fn labels(cfg: &Neo4jConfig) -> Result, String> { + let r = run_one(cfg, "CALL db.labels() YIELD label RETURN label ORDER BY label", json!({})).await?; + let names: Vec = r["data"].as_array().into_iter().flatten().filter_map(|d| d["row"][0].as_str().map(String::from)).collect(); + if names.is_empty() { + return Ok(vec![]); + } + let stmts = names.iter().map(|n| (format!("MATCH (n:{}) RETURN count(n)", label_ident(n)), json!({}))).collect(); + let counts = run(cfg, stmts).await?; + Ok(names.into_iter().zip(counts).map(|(n, c)| (n, c["data"][0]["row"][0].as_i64().unwrap_or(-1))).collect()) +} + +/// Property keys seen on nodes with a label (a sample), for the describe panel. +pub async fn describe(cfg: &Neo4jConfig, label: &str) -> Result { + let r = run_one( + cfg, + &format!("MATCH (n:{}) WITH n LIMIT 200 UNWIND keys(n) AS k RETURN k, count(*) AS c ORDER BY c DESC, k", label_ident(label)), + json!({}), + ) + .await?; + let keys: Vec = r["data"].as_array().into_iter().flatten().map(|d| d["row"][0].clone()).collect(); + let count = run_one(cfg, &format!("MATCH (n:{}) RETURN count(n)", label_ident(label)), json!({})).await?; + Ok(json!({ "keys": keys, "count": count["data"][0]["row"][0] })) +} + +/// One page of nodes with a label. `filter` is a Cypher WHERE condition on `n`. +pub async fn page(cfg: &Neo4jConfig, label: &str, filter: &str, skip: i64, limit: i64) -> Result { + let filter = filter.trim(); + if cypher_level(filter) > 0 { + return Err("The filter is a WHERE condition: it can't write".into()); + } + let wh = if filter.is_empty() { String::new() } else { format!(" WHERE {filter}") }; + let stmt = format!( + "MATCH (n:{}){wh} RETURN elementId(n) AS id, labels(n) AS labels, properties(n) AS props ORDER BY elementId(n) SKIP $skip LIMIT $limit", + label_ident(label) + ); + let r = run_one(cfg, &stmt, json!({ "skip": skip.max(0), "limit": limit.clamp(1, 5000) })).await?; + let docs: Vec = r["data"] + .as_array() + .into_iter() + .flatten() + .map(|d| { + let row = &d["row"]; + let mut doc = Map::new(); + doc.insert("_id".into(), row[0].clone()); + doc.insert("_labels".into(), row[1].clone()); + if let Some(props) = row[2].as_object() { + for (k, v) in props { + doc.insert(k.clone(), v.clone()); + } + } + Value::Object(doc) + }) + .collect(); + let next = (docs.len() as i64 >= limit).then_some(skip + docs.len() as i64); + Ok(json!({ "docs": docs, "next": next })) +} + +/// The properties to store: everything but the browser's own fields. +fn props_of(doc: &Value) -> Value { + let mut out = Map::new(); + if let Some(o) = doc.as_object() { + for (k, v) in o { + if k != "_id" && k != "_labels" { + out.insert(k.clone(), v.clone()); + } + } + } + Value::Object(out) +} + +/// Save a node: replace its properties, or create it under `label`. +pub async fn save(cfg: &Neo4jConfig, label: &str, doc: &Value) -> Result { + let props = props_of(doc); + let (stmt, params) = match doc["_id"].as_str().filter(|s| !s.is_empty()) { + Some(id) => ( + "MATCH (n) WHERE elementId(n) = $id SET n = $props RETURN elementId(n), labels(n), properties(n)".to_string(), + json!({ "id": id, "props": props }), + ), + None => ( + format!("CREATE (n:{}) SET n = $props RETURN elementId(n), labels(n), properties(n)", label_ident(label)), + json!({ "props": props }), + ), + }; + let r = run_one(cfg, &stmt, params).await?; + let row = &r["data"][0]["row"]; + if row.is_null() { + return Err("That node no longer exists".into()); + } + let mut out = Map::new(); + out.insert("_id".into(), row[0].clone()); + out.insert("_labels".into(), row[1].clone()); + if let Some(p) = row[2].as_object() { + out.extend(p.clone()); + } + Ok(Value::Object(out)) +} + +/// Delete a node and its relationships. +pub async fn remove(cfg: &Neo4jConfig, id: &str) -> Result<(), String> { + run_one(cfg, "MATCH (n) WHERE elementId(n) = $id DETACH DELETE n", json!({ "id": id })).await.map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cypher_levels() { + assert_eq!(cypher_level("MATCH (n:Person) RETURN n LIMIT 10"), 0); + assert_eq!(cypher_level("MATCH (n) WHERE n.name = 'CREATE me' RETURN n"), 0, "strings don't count"); + assert_eq!(cypher_level("CALL db.labels()"), 0); + assert_eq!(cypher_level("MATCH (n) SET n.x = 1"), 1); + assert_eq!(cypher_level("MATCH (n) DETACH DELETE n"), 1); + assert_eq!(cypher_level("MERGE (a:A {id: 1})"), 1); + assert_eq!(cypher_level("CALL apoc.create.node(['X'], {})"), 1); + assert_eq!(cypher_level("LOAD CSV FROM 'file:///x' AS r CREATE (:R)"), 1); + assert_eq!(cypher_level("CREATE INDEX FOR (n:Person) ON (n.name)"), 2); + assert_eq!(cypher_level("DROP CONSTRAINT c"), 2); + assert_eq!(cypher_level("DROP DATABASE shop"), 3); + assert_eq!(cypher_level("CREATE USER bob SET PASSWORD 'x'"), 3); + assert_eq!(cypher_level("GRANT ROLE admin TO bob"), 3); + assert_eq!(cypher_level("MATCH (n:`CREATE`) RETURN n"), 0, "quoted names don't count"); + } + + #[test] + fn addresses_become_http() { + let c = |u: &str| Neo4jConfig { name: "t".into(), url: u.into(), database: None, user: None, password: None }; + assert_eq!(base(&c("localhost:7474")), "http://localhost:7474"); + assert_eq!(base(&c("bolt://db.example.com:7687")), "http://db.example.com:7474"); + assert_eq!(base(&c("https://x.databases.neo4j.io/")), "https://x.databases.neo4j.io"); + } + + /// Against a Neo4j server: STROKE_TEST_NEO4J = url|user|password. + #[tokio::test] + async fn live_round_trip() { + let Ok(spec) = std::env::var("STROKE_TEST_NEO4J") else { return }; + let p: Vec<&str> = spec.splitn(3, '|').collect(); + let cfg = Neo4jConfig { name: "t".into(), url: p[0].into(), database: None, user: Some(p[1].into()), password: Some(p[2].into()) }; + let cfg = connect(&cfg).await.unwrap(); + let label = format!("StrokeTest{}", std::process::id()); + query(&cfg, &format!("CREATE (:{label} {{name: 'Ada', born: 1815}}), (:{label} {{name: 'Alan', born: 1912}})")).await.unwrap(); + let ls = labels(&cfg).await.unwrap(); + assert!(ls.iter().any(|(n, c)| n == &label && *c == 2), "{ls:?}"); + let pg = page(&cfg, &label, "n.born > 1900", 0, 50).await.unwrap(); + assert_eq!(pg["docs"].as_array().unwrap().len(), 1); + let mut doc = pg["docs"][0].clone(); + assert_eq!(doc["name"], "Alan"); + doc["name"] = json!("Alan Turing"); + let saved = save(&cfg, &label, &doc).await.unwrap(); + assert_eq!(saved["name"], "Alan Turing"); + let created = save(&cfg, &label, &json!({ "name": "Grace", "born": 1906 })).await.unwrap(); + assert!(created["_id"].as_str().is_some()); + remove(&cfg, created["_id"].as_str().unwrap()).await.unwrap(); + let d = describe(&cfg, &label).await.unwrap(); + assert_eq!(d["count"], 2); + let r = query(&cfg, &format!("MATCH (n:{label}) RETURN n.name AS name, n.born AS born ORDER BY born")).await.unwrap(); + assert_eq!(r.rows[1], vec![json!("Alan Turing"), json!(1912)]); + assert_eq!(r.columns[1].data_type, "INTEGER"); + assert!(page(&cfg, &label, "true DETACH DELETE n", 0, 10).await.is_err(), "a filter can't write"); + let gone = query(&cfg, &format!("MATCH (n:{label}) DETACH DELETE n")).await.unwrap(); + assert!(gone.message.unwrap().contains("2 nodes deleted")); + let plan = explain_plan(&cfg, &format!("MATCH (n:{label}) WHERE n.born > 1900 RETURN n.name LIMIT 5")).await.unwrap(); + assert_eq!(plan["Node Type"], "ProduceResults"); + assert!(plan.to_string().contains("NodeByLabelScan"), "{plan}"); + assert!(query(&cfg, "MATCH (n RETURN n").await.is_err()); + } +} diff --git a/src-tauri/src/db/objects.rs b/src-tauri/src/db/objects.rs index 4f3d7cc4..729bfc42 100644 --- a/src-tauri/src/db/objects.rs +++ b/src-tauri/src/db/objects.rs @@ -72,7 +72,7 @@ pub fn kinds_for(conn: &ActiveConnection) -> &'static [&'static str] { ActiveConnection::Duckdb(_) => &["view", "function", "sequence"], // Materialized views come back from list_tables as views here. ActiveConnection::Clickhouse(_) => &["view", "function"], - ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) => &[], + ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => &[], } } @@ -245,7 +245,7 @@ pub async fn list_db_objects(state: Db<'_>, schema: String) -> Result sqlite_triggers_from(libsql_query(cfg, SQLITE_TRIGGERS, vec![]).await?), ActiveConnection::Duckdb(h) => list_duckdb(h, &schema).await?, ActiveConnection::Clickhouse(cfg) => list_clickhouse(cfg).await?, - ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) => vec![], + ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => vec![], }; Ok(ObjectListing { kinds, cascade, objects }) } @@ -689,7 +689,7 @@ pub async fn get_object_definition( } ActiveConnection::Duckdb(h) => def_duckdb(h, &kind, &schema, &name).await?, ActiveConnection::Clickhouse(cfg) => def_clickhouse(cfg, &kind, &schema, &name).await?, - ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) => return Err(unsupported(&kind)), + ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => return Err(unsupported(&kind)), }; Ok(format!("{}\n", def.trim_end())) } @@ -910,7 +910,9 @@ async fn def_pg(pool: &PgPool, kind: &str, schema: &str, name: &str, args: &str, /// SHOW CREATE goes over the text protocol: MySQL won't prepare SHOW CREATE /// TRIGGER, nor any of the statements this module runs for routines. async fn mysql_show(pool: &MySqlPool, sql: &str, column: &str) -> Result, String> { - let rows = sqlx::raw_sql(sql).fetch_all(pool).await.map_err(|e| e.to_string())?; + // Backticks, so a definition copied out runs on a stock server too. + let mut conn = super::mysql::backtick_conn(pool).await?; + let rows = sqlx::Executor::fetch_all(&mut conn, sql).await.map_err(|e| e.to_string())?; Ok(rows.first().and_then(|r| my_text_named(r, column))) } @@ -1147,7 +1149,7 @@ pub async fn drop_object( super::clickhouse::query(cfg, &sql).await.map_err(fail)?; Ok(sql) } - ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) => Err(unsupported(&kind)), + ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Oracle(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => Err(unsupported(&kind)), } } diff --git a/src-tauri/src/db/odbc.rs b/src-tauri/src/db/odbc.rs new file mode 100644 index 00000000..9b2779fa --- /dev/null +++ b/src-tauri/src/db/odbc.rs @@ -0,0 +1,1869 @@ +//! The ODBC bridge: any database with an ODBC driver installed. Beta. +//! +//! One driver for many engines (Db2, SAP HANA, Teradata, Vertica, Exasol, +//! Firebird, Redshift, Databricks, Hive, Trino, Dremio, IRIS, Access, ...). +//! The app ships the driver manager; the database's own ODBC driver does the +//! talking. On Windows that manager is the system's `odbc32`. Elsewhere it is +//! unixODBC, built into the app, so nothing has to be installed for the app +//! to start, only the driver for the database you connect to. +//! +//! The bundled unixODBC reads its driver list from a merged copy of the +//! system's: `/etc/odbcinst.ini`, Homebrew's, and macOS's `/Library/ODBC` +//! (where iODBC-registered drivers live), with bare library names resolved to +//! full paths. See [`registry`]. +//! +//! Everything runs through the ODBC catalog functions (SQLTables, SQLColumns, +//! SQLPrimaryKeys, SQLForeignKeys), so browsing works the same on every +//! driver. Paging adapts to the database: LIMIT/OFFSET where it is spoken, +//! OFFSET/FETCH, SKIP/FIRST or TOP elsewhere, and skipping rows on this side +//! when nothing else is known to work. +//! +//! ODBC calls block, so each one runs on a blocking thread holding the +//! connection. Stop calls SQLCancel on the running statement from another +//! thread, which the ODBC spec allows for exactly this. + +use super::query::{ColumnInfo, ForeignKeyInfo, RowFilter, SqlResult, TableRows}; +use super::schema::{ColumnStructureRow, TableInfo}; +use odbc_api::handles::{AnyHandle, AsStatementRef}; +use odbc_api::{parameter::InputParameter, Connection, ConnectionOptions, Cursor, DataType, IntoParameter, ResultSetMetadata}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OdbcConfig { + pub name: String, + /// The engine this connection is for (`db2`, `hana`, ... or `generic`). + /// Only labels and hints depend on it; the driver decides the rest. + #[serde(default)] + pub preset: Option, + /// A data source name from odbc.ini / the ODBC Data Source Administrator. + #[serde(default)] + pub dsn: Option, + /// A whole connection string (`Driver={...};Server=...;`), when no DSN. + #[serde(default)] + pub connection_string: Option, + #[serde(default)] + pub user: Option, + #[serde(default)] + pub password: Option, + /// An SSH tunnel to the database's host and port. Only a preset's fields + /// say where that is (`target_host`, `target_port`); the string is + /// pointed at the tunnel's local end. + #[serde(default)] + pub ssh: Option, + #[serde(default)] + pub target_host: Option, + #[serde(default)] + pub target_port: Option, +} + +/// How the database names what the app calls a schema. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Namespace { + /// `schema.table` (Db2, HANA, Postgres, Oracle, SQL Server, Trino, ...). + Schema, + /// `catalog.table`, no schemas (MySQL and MariaDB call databases catalogs). + Catalog, + /// Bare table names (SQLite, Access, a CSV driver). + Flat, +} + +/// How a page of rows is asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Paging { + LimitOffset, + /// Trino and Presto: `OFFSET n LIMIT m`. + OffsetLimit, + /// `OFFSET n ROWS FETCH NEXT m ROWS ONLY` (Db2, Oracle, Firebird 3+). + OffsetFetch, + /// SQL Server and Sybase IQ want an ORDER BY with OFFSET/FETCH. + OffsetFetchOrdered, + /// Informix: `SELECT SKIP n FIRST m`. + SkipFirst, + /// `SELECT TOP n+m`, then skip n here (Teradata, SAP ASE, Access, IRIS). + Top, + /// No clause: read and skip here. + Client, +} + +#[derive(Debug, Clone)] +pub struct OdbcInfo { + /// What SQL_DBMS_NAME says (`DB2/LINUXX8664`, `HDB`, `PostgreSQL`, ...). + pub dbms: String, + pub quote: Option, + pub namespace: Namespace, + /// The connection's current catalog, for catalog calls in Schema mode. + pub catalog: String, + pub paging: Paging, +} + +/// What the window needs to write SQL for this connection. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OdbcSummary { + pub dbms: String, + /// The identifier quote: `"`, `` ` `` or `[`. None when the driver has none. + pub quote: Option, + /// "schema", "catalog" or "flat". + pub namespace: &'static str, +} + +impl OdbcInfo { + pub fn summary(&self) -> OdbcSummary { + OdbcSummary { + dbms: self.dbms.clone(), + quote: self.quote.map(String::from), + namespace: match self.namespace { + Namespace::Schema => "schema", + Namespace::Catalog => "catalog", + Namespace::Flat => "flat", + }, + } + } +} + +pub struct OdbcConn { + pub info: OdbcInfo, + /// The connection string, to open a transaction's own connection beside + /// this one. Held in memory only. + cs: String, + conn: Mutex>, +} + +pub type OdbcHandle = Arc; + +/// What the schema list shows for a database without schemas. +pub const FLAT_SCHEMA: &str = "default"; + +// ── Driver registry (unixODBC) ──────────────────────────────────────────────── + +/// The merged driver and data source list the bundled unixODBC reads. +/// +/// unixODBC resolves a driver registered by a bare file name (`Driver = +/// psqlodbcw.so`, as Debian and Ubuntu packages do) against its own build's +/// library directory, which for a copy built into this app is nowhere. So the +/// app reads every registry it knows of, writes the paths out in full, and +/// points ODBCSYSINI at the result. A user's own ODBCSYSINI is read first. +#[cfg(not(windows))] +pub mod registry { + use std::path::{Path, PathBuf}; + + fn home() -> Option { + std::env::var_os("HOME").map(PathBuf::from) + } + + /// Where registries live, most specific first. The user's own data + /// sources (`~/.odbc.ini`, or ODBCINI) come before the system's: unixODBC + /// built into the app does not read them itself, so they ride in the + /// merged file. + fn sources(file: &str, user_sysini: Option<&Path>) -> Vec { + let mut out = Vec::new(); + if file == "odbc.ini" { + if let Some(p) = std::env::var_os("ODBCINI") { + out.push(PathBuf::from(p)); + } + if let Some(h) = home() { + out.push(h.join(".odbc.ini")); + } + } + if let Some(dir) = user_sysini { + out.push(dir.join(file)); + } + for dir in ["/etc", "/etc/unixODBC", "/usr/local/etc", "/opt/homebrew/etc", "/Library/ODBC"] { + out.push(Path::new(dir).join(file)); + } + if let Some(h) = home() { + out.push(h.join("Library/ODBC").join(file)); + if file == "odbcinst.ini" { + out.push(h.join(".odbcinst.ini")); + } + } + out + } + + /// Directories a bare driver file name may be in. + fn lib_dirs() -> Vec { + let mut out = Vec::new(); + if let Ok(rd) = std::fs::read_dir("/usr/lib") { + for e in rd.flatten() { + let p = e.path(); + if p.join("odbc").is_dir() { + out.push(p.join("odbc")); + } + if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.contains("-linux-gnu")) { + out.push(p); + } + } + } + for d in ["/usr/lib/odbc", "/usr/lib64", "/usr/lib", "/usr/local/lib", "/opt/homebrew/lib", "/usr/lib64/odbc"] { + out.push(PathBuf::from(d)); + } + out + } + + /// `[section]` → ordered (key, value) pairs. + pub fn parse(text: &str) -> Vec<(String, Vec<(String, String)>)> { + let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new(); + for raw in text.lines() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') || line.starts_with(';') { + continue; + } + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + out.push((name.trim().to_string(), Vec::new())); + } else if let (Some((k, v)), Some(last)) = (line.split_once('='), out.last_mut()) { + last.1.push((k.trim().to_string(), v.trim().to_string())); + } + } + out + } + + /// Merge registries: the first file to define a section wins it. + pub fn merge(files: &[String], resolve: &dyn Fn(&str) -> Option) -> String { + let mut seen = std::collections::HashSet::new(); + let mut out = String::new(); + for text in files { + for (name, keys) in parse(text) { + if !seen.insert(name.to_ascii_lowercase()) { + continue; + } + out.push_str(&format!("[{name}]\n")); + for (k, v) in keys { + let v = if matches!(k.to_ascii_lowercase().as_str(), "driver" | "setup" | "driver64" | "setup64") + && !v.contains('/') + && !v.is_empty() + { + resolve(&v).unwrap_or(v) + } else { + v + }; + out.push_str(&format!("{k} = {v}\n")); + } + out.push('\n'); + } + } + out + } + + fn resolve_lib(name: &str) -> Option { + lib_dirs().into_iter().map(|d| d.join(name)).find(|p| p.is_file()).map(|p| p.to_string_lossy().into_owned()) + } + + /// Write the merged registry and point the driver manager at it. Runs + /// before every driver list, data source list and connect, so a driver + /// installed while the app is open shows up without a restart: unixODBC + /// reads the files again when they change. + pub fn install() { + // The user's own ODBCSYSINI, as it was before this app replaced it. + static USER_SYSINI: std::sync::OnceLock> = std::sync::OnceLock::new(); + let user_sysini = USER_SYSINI.get_or_init(|| std::env::var_os("ODBCSYSINI").map(PathBuf::from)).clone(); + let read = |file: &str| -> Vec { + sources(file, user_sysini.as_deref()).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect() + }; + let drivers = merge(&read("odbcinst.ini"), &resolve_lib); + let dsns = merge(&read("odbc.ini"), &resolve_lib); + let user = std::env::var("USER").unwrap_or_else(|_| "user".into()); + let dir = std::env::temp_dir().join(format!("stroke-odbc-{user}")); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + { + use std::os::unix::fs::PermissionsExt; + // System DSNs can carry passwords: this copy is the user's alone. + let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)); + } + let write = |name: &str, body: &str| -> bool { + let path = dir.join(name); + let ok = std::fs::write(&path, body).is_ok(); + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + } + ok + }; + if write("odbcinst.ini", &drivers) && write("odbc.ini", &dsns) && std::env::var_os("ODBCSYSINI").as_deref() != Some(dir.as_os_str()) { + // Set once, before the first ODBC call; nothing else in the app + // reads this variable. + std::env::set_var("ODBCSYSINI", &dir); + } + } +} + +fn environment() -> Result<&'static odbc_api::Environment, String> { + // Serialised: two refreshes at once would write the same files together. + static REFRESH: Mutex<()> = Mutex::new(()); + { + let _g = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(not(windows))] + registry::install(); + } + odbc_api::environment().map_err(|e| format!("The ODBC driver manager could not start: {e}")) +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OdbcDriver { + pub name: String, + /// The driver's library, where the registry says. + pub path: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OdbcDataSource { + pub name: String, + pub driver: String, +} + +/// Installed ODBC drivers. +pub async fn drivers() -> Result, String> { + tokio::task::spawn_blocking(|| { + let env = environment()?; + let mut out: Vec = env + .drivers() + .map_err(|e| e.to_string())? + .into_iter() + .map(|d| OdbcDriver { path: d.attributes.get("Driver").cloned(), name: d.description }) + .collect(); + out.sort_by_key(|d| d.name.to_ascii_lowercase()); + out.dedup_by(|a, b| a.name == b.name); + Ok(out) + }) + .await + .map_err(|e| e.to_string())? +} + +/// Configured data sources (DSNs), user and system. +pub async fn data_sources() -> Result, String> { + tokio::task::spawn_blocking(|| { + let env = environment()?; + let mut out: Vec = env + .data_sources() + .map_err(|e| e.to_string())? + .into_iter() + .map(|d| OdbcDataSource { name: d.server_name, driver: d.driver }) + .collect(); + out.sort_by_key(|d| d.name.to_ascii_lowercase()); + out.dedup_by(|a, b| a.name == b.name); + Ok(out) + }) + .await + .map_err(|e| e.to_string())? +} + +// ── Connecting ──────────────────────────────────────────────────────────────── + +/// A value as an ODBC connection string writes it: braced when it holds +/// anything the string's own syntax uses. +pub fn attr_value(v: &str) -> String { + if v.contains([';', '{', '}', '=']) || v.starts_with(' ') || v.ends_with(' ') { + format!("{{{}}}", v.replace('}', "}}")) + } else { + v.to_string() + } +} + +/// Is `key` already set in the string (case-insensitive)? +fn has_key(s: &str, keys: &[&str]) -> bool { + s.split(';').filter_map(|part| part.split_once('=')).any(|(k, _)| keys.iter().any(|w| k.trim().eq_ignore_ascii_case(w))) +} + +fn trimmed(s: &Option) -> Option<&str> { + s.as_deref().map(str::trim).filter(|s| !s.is_empty()) +} + +/// The connection string handed to the driver manager. +pub fn connection_string(cfg: &OdbcConfig) -> Result { + let mut s = match (trimmed(&cfg.dsn), trimmed(&cfg.connection_string)) { + (Some(dsn), _) => format!("DSN={};", attr_value(dsn)), + (None, Some(cs)) => cs.to_string(), + (None, None) => return Err("Choose a data source (DSN) or enter a connection string".into()), + }; + if !s.ends_with(';') { + s.push(';'); + } + if let Some(u) = trimmed(&cfg.user) { + if !has_key(&s, &["UID", "User", "Username"]) { + s.push_str(&format!("UID={};", attr_value(u))); + } + } + if let Some(p) = cfg.password.as_deref().filter(|p| !p.is_empty()) { + if !has_key(&s, &["PWD", "Password"]) { + s.push_str(&format!("PWD={};", attr_value(p))); + } + } + Ok(s) +} + +/// Point a connection string's host and port at a tunnel's local end: +/// `host:port` and `host/port` inside a value, and values that are exactly +/// the host or the port. Values are compared, never substrings of other words. +pub fn retarget(cs: &str, host: &str, port: u16, local_port: u16) -> String { + let (host, port_s, local) = (host.trim(), port.to_string(), local_port.to_string()); + let mut out = Vec::new(); + // Split on ';' outside braces. + let mut part = String::new(); + let mut depth = 0; + let mut parts = Vec::new(); + for c in cs.chars() { + match c { + '{' => { depth += 1; part.push(c) } + '}' => { depth -= 1; part.push(c) } + ';' if depth <= 0 => parts.push(std::mem::take(&mut part)), + c => part.push(c), + } + } + if !part.is_empty() { + parts.push(part); + } + for p in parts { + let Some((k, v)) = p.split_once('=') else { + out.push(p); + continue; + }; + let v = if v == host { + "127.0.0.1".to_string() + } else if v == port_s { + local.clone() + } else { + v.replace(&format!("{host}:{port_s}"), &format!("127.0.0.1:{local}")).replace(&format!("{host}/{port_s}"), &format!("127.0.0.1/{local}")) + }; + out.push(format!("{k}={v}")); + } + let mut s = out.join(";"); + if cs.ends_with(';') { + s.push(';'); + } + s +} + +/// Driver errors arrive as diagnostics records; keep the message, drop the +/// state codes unless that is all there is. +fn odbc_err(e: odbc_api::Error) -> String { + let text = e.to_string(); + let msgs: Vec<&str> = text.split("Message: ").skip(1).map(|m| m.split(", function:").next().unwrap_or(m).trim()).collect(); + if msgs.is_empty() { text } else { msgs.join(" ") } +} + +fn paging_for(dbms: &str) -> Paging { + let d = dbms.to_ascii_lowercase(); + let has = |w: &str| d.contains(w); + if has("trino") || has("presto") { + Paging::OffsetLimit + } else if has("microsoft sql server") || has("sybase iq") || has("adaptive server iq") { + Paging::OffsetFetchOrdered + } else if has("db2") || has("oracle") || has("firebird") || has("interbase") || has("derby") { + Paging::OffsetFetch + } else if has("informix") || d.starts_with("ids") { + Paging::SkipFirst + } else if has("teradata") || has("adaptive server") || has("sybase") || has("access") || has("iris") || has("cache") { + Paging::Top + } else if has("postgres") || has("mysql") || has("mariadb") || has("sqlite") || has("vertica") || has("exasol") || has("hdb") || has("hana") + || has("redshift") || has("snowflake") || has("bigquery") || has("google") || has("clickhouse") || has("duckdb") || has("dremio") + || has("spark") || has("databricks") || has("impala") || has("greenplum") || has("cockroach") + { + Paging::LimitOffset + } else { + Paging::Client + } +} + +pub async fn connect(cfg: &OdbcConfig) -> Result { + connect_string(connection_string(cfg)?).await.map_err(|e| explain_connect(cfg, e)) +} + +/// The driver manager's IM002 ("Data source name not found and no default +/// driver specified") says neither what is missing nor where it goes. +fn explain_connect(cfg: &OdbcConfig, e: String) -> String { + if !e.contains("Data source name not found") { + return e; + } + let where_dsns = if cfg!(windows) { + "the ODBC Data Source Administrator" + } else if cfg!(target_os = "macos") { + "~/Library/ODBC/odbc.ini or ~/.odbc.ini" + } else { + "~/.odbc.ini or /etc/odbc.ini" + }; + match trimmed(&cfg.dsn) { + Some(dsn) => format!("No ODBC data source named \"{dsn}\" on this computer. Add it in {where_dsns}, or connect with a connection string instead."), + None => "The connection string names no DSN or driver that ODBC knows. Start it with Driver={...}, using a driver name from odbcinst.ini.".into(), + } +} + +async fn connect_string(cs: String) -> Result { + tokio::task::spawn_blocking(move || { + let env = environment()?; + let options = ConnectionOptions { login_timeout_sec: Some(20), ..Default::default() }; + let conn = env.connect_with_connection_string(&cs, options).map_err(odbc_err)?; + let dbms = conn.database_management_system_name().unwrap_or_default(); + let quote = conn.identifier_quote_char().ok().flatten().filter(|c| !c.is_whitespace()); + let schema_len = conn.max_schema_name_len().unwrap_or(0); + let catalog_len = conn.max_catalog_name_len().unwrap_or(0); + let catalog = if catalog_len > 0 { conn.current_catalog().unwrap_or_default() } else { String::new() }; + let guess = if schema_len > 0 { + Namespace::Schema + } else if catalog_len > 0 { + Namespace::Catalog + } else { + Namespace::Flat + }; + let mut info = OdbcInfo { paging: paging_for(&dbms), dbms, quote, namespace: guess, catalog }; + // What the driver says it supports and what its catalog holds can + // differ (SQLite's driver reports schemas and has none): ask. + if guess == Namespace::Schema && schema_names(&conn, &info).is_empty() { + info.namespace = if catalog_len > 0 { Namespace::Catalog } else { Namespace::Flat }; + } + // The same for catalogs: SQLite's driver reports them and has none. + if info.namespace == Namespace::Catalog && catalog_names(&conn).is_empty() { + info.namespace = Namespace::Flat; + } + Ok(Arc::new(OdbcConn { info, cs, conn: Mutex::new(conn) })) + }) + .await + .map_err(|e| format!("ODBC task failed: {e}"))? +} + +/// Run `f` on a blocking thread with the connection. +async fn run(h: &OdbcHandle, f: F) -> Result +where + F: FnOnce(&Connection<'static>, &OdbcInfo) -> Result + Send + 'static, + T: Send + 'static, +{ + let h = h.clone(); + tokio::task::spawn_blocking(move || { + let conn = h.conn.lock().map_err(|_| "ODBC connection lock poisoned".to_string())?; + f(&conn, &h.info) + }) + .await + .map_err(|e| format!("ODBC task failed: {e}"))? +} + +/// A connection of its own for an explicit transaction, autocommit off: on +/// the shared one, every grid page and sidebar query would run inside it. +pub async fn open_tx(h: &OdbcHandle) -> Result { + let tx = connect_string(h.cs.clone()).await?; + run(&tx, |conn, _| conn.set_autocommit(false).map_err(odbc_err)).await?; + Ok(tx) +} + +pub async fn commit(h: &OdbcHandle) -> Result<(), String> { + run(h, |conn, _| conn.commit().map_err(odbc_err)).await +} + +pub async fn rollback(h: &OdbcHandle) -> Result<(), String> { + run(h, |conn, _| conn.rollback().map_err(odbc_err)).await +} + +pub async fn ping(h: &OdbcHandle) -> Result<(), String> { + run(h, |conn, _| match conn.is_dead() { + Ok(true) => Err("The connection to the database was lost".into()), + _ => Ok(()), + }) + .await +} + +// ── Values ──────────────────────────────────────────────────────────────────── + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind { + Int, + Float, + Bool, + Binary, + Text, +} + +fn kind_of(dt: &DataType) -> Kind { + match dt { + DataType::Integer | DataType::SmallInt | DataType::BigInt | DataType::TinyInt => Kind::Int, + DataType::Real | DataType::Double | DataType::Float { .. } => Kind::Float, + DataType::Bit => Kind::Bool, + DataType::Binary { .. } | DataType::Varbinary { .. } | DataType::LongVarbinary { .. } => Kind::Binary, + DataType::Other { data_type, .. } if data_type.0 == 16 => Kind::Bool, + _ => Kind::Text, + } +} + +/// A result column's type as a label: `INTEGER`, `VARCHAR(40)`, `DECIMAL(10,2)`. +fn type_label(dt: &DataType) -> String { + let len = |l: &Option, base: &str| match l { + Some(n) if n.get() < 1 << 30 => format!("{base}({n})"), + _ => base.to_string(), + }; + match dt { + DataType::Unknown => "UNKNOWN".into(), + DataType::Char { length } => len(length, "CHAR"), + DataType::WChar { length } => len(length, "NCHAR"), + DataType::Varchar { length } => len(length, "VARCHAR"), + DataType::WVarchar { length } => len(length, "NVARCHAR"), + DataType::LongVarchar { .. } => "TEXT".into(), + DataType::WLongVarchar { .. } => "NTEXT".into(), + DataType::Numeric { precision, scale } => format!("NUMERIC({precision},{scale})"), + DataType::Decimal { precision, scale } => format!("DECIMAL({precision},{scale})"), + DataType::Integer => "INTEGER".into(), + DataType::SmallInt => "SMALLINT".into(), + DataType::TinyInt => "TINYINT".into(), + DataType::BigInt => "BIGINT".into(), + DataType::Float { .. } => "FLOAT".into(), + DataType::Real => "REAL".into(), + DataType::Double => "DOUBLE".into(), + DataType::Date => "DATE".into(), + DataType::Time { .. } => "TIME".into(), + DataType::Timestamp { .. } => "TIMESTAMP".into(), + DataType::Bit => "BIT".into(), + DataType::Binary { length } => len(length, "BINARY"), + DataType::Varbinary { length } => len(length, "VARBINARY"), + DataType::LongVarbinary { .. } => "BLOB".into(), + DataType::Other { data_type, .. } => match data_type.0 { + 16 => "BOOLEAN".into(), + -11 => "UUID".into(), + n => format!("TYPE {n}"), + }, + } +} + +/// One cell as text into `buf`, or None for NULL. +fn text_cell(row: &mut odbc_api::CursorRow<'_>, col: u16, buf: &mut Vec, wbuf: &mut Vec) -> Result, String> { + if cfg!(windows) { + // The narrow API speaks the system code page there, not UTF-8. + let some = row.get_wide_text(col, wbuf).map_err(odbc_err)?; + Ok(some.then(|| String::from_utf16_lossy(wbuf))) + } else { + let some = row.get_text(col, buf).map_err(odbc_err)?; + Ok(some.then(|| String::from_utf8_lossy(buf).into_owned())) + } +} + +fn cell(kind: Kind, row: &mut odbc_api::CursorRow<'_>, col: u16, buf: &mut Vec, wbuf: &mut Vec) -> Result { + if kind == Kind::Binary { + let some = row.get_binary(col, buf).map_err(odbc_err)?; + if !some { + return Ok(Value::Null); + } + let mut hex = String::with_capacity(2 + buf.len() * 2); + hex.push_str("0x"); + for b in buf.iter() { + hex.push_str(&format!("{b:02x}")); + } + return Ok(super::sql_util::cap_json_value("text", Value::String(hex))); + } + let Some(s) = text_cell(row, col, buf, wbuf)? else { return Ok(Value::Null) }; + Ok(match kind { + Kind::Int => match s.trim().parse::() { + Ok(n) if n.unsigned_abs() <= (1u64 << 53) => json!(n), + _ => Value::String(s), + }, + Kind::Float => match s.trim().parse::() { + Ok(x) if x.is_finite() => json!(x), + _ => Value::String(s), + }, + Kind::Bool => match s.trim().to_ascii_lowercase().as_str() { + "1" | "t" | "true" | "y" | "yes" => json!(true), + "0" | "f" | "false" | "n" | "no" => json!(false), + _ => Value::String(s), + }, + _ => super::sql_util::cap_json_value("text", Value::String(s)), + }) +} + +/// Columns of a cursor, with how to read each. +fn describe(cursor: &mut impl ResultSetMetadata) -> Result<(Vec, Vec), String> { + let n = cursor.num_result_cols().map_err(odbc_err)?.max(0) as u16; + let mut cols = Vec::with_capacity(n as usize); + let mut kinds = Vec::with_capacity(n as usize); + for i in 1..=n { + let name = cursor.col_name(i).map_err(odbc_err)?; + let dt = cursor.col_data_type(i).unwrap_or(DataType::Unknown); + kinds.push(kind_of(&dt)); + cols.push(ColumnInfo::new(if name.is_empty() { format!("column{i}") } else { name }, type_label(&dt))); + } + Ok((cols, kinds)) +} + +/// Read a cursor's rows into `on_row` until it returns false. +fn read_rows(cursor: &mut impl Cursor, kinds: &[Kind], mut on_row: impl FnMut(Vec) -> Result) -> Result<(), String> { + let mut buf = Vec::new(); + let mut wbuf = Vec::new(); + while let Some(mut row) = cursor.next_row().map_err(odbc_err)? { + let mut out = Vec::with_capacity(kinds.len()); + for (i, k) in kinds.iter().enumerate() { + out.push(cell(*k, &mut row, i as u16 + 1, &mut buf, &mut wbuf)?); + } + if !on_row(out)? { + break; + } + } + Ok(()) +} + +/// Parameters for one statement: bound as typed values, never spliced. +#[derive(Default, Debug, Clone)] +struct Params(Vec); + +#[derive(Debug, Clone)] +enum Param { + Text(String), + Int(i64), + Float(f64), +} + +impl Params { + fn text(&mut self, s: impl Into) -> &'static str { + self.0.push(Param::Text(s.into())); + "?" + } + fn boxed(&self) -> Vec> { + self.0 + .iter() + .map(|p| -> Box { + match p { + Param::Int(n) => Box::new(*n), + Param::Float(x) => Box::new(*x), + // Wide (UTF-16) text on Windows, where narrow means the code page. + #[cfg(windows)] + Param::Text(s) => Box::new(s.as_str().into_parameter()), + #[cfg(not(windows))] + Param::Text(s) => Box::new(odbc_api::Narrow(s.clone()).into_parameter()), + } + }) + .collect() + } +} + +/// The running statement's handle, for Stop. Cleared under the lock before +/// the statement is freed, so a late Stop never reaches a freed handle. +#[derive(Default)] +struct CancelSlot { + stopped: bool, + handle: Option, +} + +type Slot = Arc>; + +fn cancel_now(slot: &Slot) { + let mut g = slot.lock().unwrap_or_else(|e| e.into_inner()); + g.stopped = true; + if let Some(h) = g.handle { + // SAFETY: the handle is live while it is in the slot (see above), and + // SQLCancel is the one call ODBC allows from another thread. + unsafe { + let _ = odbc_api::sys::SQLCancel(odbc_api::sys::HStmt(h as *mut std::ffi::c_void)); + } + } +} + +/// One statement, its rows (or affected count) through `on_cols`/`on_row`. +/// Returns affected rows for a statement without a result set. +fn execute_on( + conn: &Connection<'static>, + sql: &str, + params: &Params, + slot: Option<&Slot>, + mut on_cols: impl FnMut(Vec) -> Result<(), String>, + on_row: impl FnMut(Vec) -> Result, +) -> Result, String> { + let mut stmt = conn.preallocate().map_err(odbc_err)?; + if let Some(s) = slot { + let mut g = s.lock().unwrap_or_else(|e| e.into_inner()); + if g.stopped { + return Err(super::query::QUERY_CANCELLED.into()); + } + g.handle = Some(stmt.as_stmt_ref().as_handle().0 as usize); + } + let boxed = params.boxed(); + // Ok(true): the statement returned rows. + let out: Result = (|| { + let cursor = stmt.execute(sql, &boxed[..]).map_err(odbc_err)?; + match cursor { + Some(mut cursor) => { + let (cols, kinds) = describe(&mut cursor)?; + on_cols(cols)?; + read_rows(&mut cursor, &kinds, on_row)?; + Ok(true) + } + None => Ok(false), + } + })(); + let affected = if matches!(out, Ok(false)) { stmt.row_count().ok().flatten() } else { None }; + if let Some(s) = slot { + s.lock().unwrap_or_else(|e| e.into_inner()).handle = None; + } + out.map(|_| affected) +} + +// ── Console ─────────────────────────────────────────────────────────────────── + +pub fn reads(stmt: &str) -> bool { + matches!( + super::sql_util::statement_head(stmt).as_str(), + "select" | "with" | "values" | "show" | "describe" | "desc" | "explain" + ) +} + +fn collect(conn: &Connection<'static>, sql: &str, params: &Params, slot: Option<&Slot>, t0: Instant) -> Result { + let mut columns = Vec::new(); + let mut rows: Vec> = Vec::new(); + let mut budget = super::query::CollectBudget::default(); + let mut capped = false; + let affected = execute_on(conn, sql, params, slot, |c| { + columns = c; + Ok(()) + }, |r| { + let fits = budget.take(&r); + rows.push(r); + capped = !fits; + Ok(fits) + })?; + if columns.is_empty() { + let n = affected.unwrap_or(0) as i64; + return Ok(SqlResult { + columns, + rows: vec![], + row_count: Some(n), + message: Some(format!("{n} row{} affected", if n == 1 { "" } else { "s" })), + query_ms: t0.elapsed().as_millis() as u64, + sql: sql.to_string(), + }); + } + let message = capped.then(|| super::query::budget_message(rows.len())); + Ok(SqlResult { columns, row_count: Some(rows.len() as i64), rows, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + +pub async fn query(h: &OdbcHandle, stmt: &str) -> Result { + let sql = stmt.trim().trim_end_matches(';').trim().to_string(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let t0 = Instant::now(); + run(h, move |conn, _| collect(conn, &sql, &Params::default(), None, t0)).await +} + +/// `query`, with Stop cancelling the statement on the server. +pub async fn query_cancellable(h: &OdbcHandle, stmt: &str, cancel: tokio::sync::oneshot::Receiver<()>) -> Result { + let sql = stmt.trim().trim_end_matches(';').trim().to_string(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let slot: Slot = Arc::default(); + let s = slot.clone(); + let arm = super::stop::Arm::new(cancel, move || cancel_now(&s)); + let t0 = Instant::now(); + let out = run(h, move |conn, _| collect(conn, &sql, &Params::default(), Some(&slot), t0)).await; + let stopped = arm.disarm(); + match out { + Err(_) if stopped => Err(super::query::QUERY_CANCELLED.into()), + other => other, + } +} + +/// Stream a statement's rows into the console's sink as the driver fetches +/// them, through a small bounded channel; Stop cancels the statement. +pub async fn stream_into( + h: &OdbcHandle, + stmt: &str, + sink: &mut super::query::RowSink, + cancel: tokio::sync::oneshot::Receiver<()>, +) -> Result { + enum Msg { + Columns(Vec), + Rows(Vec>), + } + const BATCH: usize = 1_000; + let sql = stmt.trim().trim_end_matches(';').trim().to_string(); + let slot: Slot = Arc::default(); + let s = slot.clone(); + let arm = super::stop::Arm::new(cancel, move || cancel_now(&s)); + let (tx, mut rx) = tokio::sync::mpsc::channel::(8); + let sql_run = sql.clone(); + let reader = run(h, move |conn, _| { + let mut batch = Vec::with_capacity(BATCH); + let txc = tx.clone(); + let affected = execute_on( + conn, + &sql_run, + &Params::default(), + Some(&slot), + |c| { + let _ = txc.blocking_send(Msg::Columns(c)); + Ok(()) + }, + |r| { + batch.push(r); + if batch.len() < BATCH { + return Ok(true); + } + Ok(tx.blocking_send(Msg::Rows(std::mem::replace(&mut batch, Vec::with_capacity(BATCH)))).is_ok()) + }, + )?; + if !batch.is_empty() { + let _ = tx.blocking_send(Msg::Rows(batch)); + } + Ok(affected) + }); + tokio::pin!(reader); + let t0 = Instant::now(); + let mut columns: Option> = None; + let mut total = 0usize; + let mut sink_err: Option = None; + let mut reader_out = None; + loop { + tokio::select! { + msg = rx.recv() => match msg { + Some(Msg::Columns(c)) => { + if let Err(e) = sink.start(c.clone()) { sink_err = Some(e); rx.close(); } + columns = Some(c); + } + Some(Msg::Rows(rows)) => { + if sink_err.is_some() { continue; } + for r in rows { + if let Err(e) = sink.push(r) { sink_err = Some(e); break; } + total += 1; + } + if sink_err.is_some() { rx.close(); } + } + None => break, + }, + out = &mut reader, if reader_out.is_none() => reader_out = Some(out), + } + } + let out = match reader_out { + Some(o) => o, + None => reader.await, + }; + let stopped = arm.disarm(); + if let Some(e) = sink_err { + return Err(e); + } + let affected = match out { + Err(_) if stopped => return Err(super::query::QUERY_CANCELLED.into()), + Err(e) => return Err(e), + Ok(a) => a, + }; + match columns { + Some(columns) => { + sink.finish()?; + Ok(SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql }) + } + None => { + let n = affected.unwrap_or(0) as i64; + Ok(SqlResult { + columns: vec![], + rows: vec![], + row_count: Some(n), + message: Some(format!("{n} row{} affected", if n == 1 { "" } else { "s" })), + query_ms: t0.elapsed().as_millis() as u64, + sql, + }) + } + } +} + +// ── Names ───────────────────────────────────────────────────────────────────── + +pub fn quote(info: &OdbcInfo, ident: &str) -> String { + match info.quote { + Some('[') => format!("[{}]", ident.replace(']', "]]")), + Some(q) => format!("{q}{}{q}", ident.replace(q, &format!("{q}{q}"))), + None => ident.to_string(), + } +} + +/// `schema.table`, `catalog.table` or `table`, by how the database names things. +pub(crate) fn table_ref(info: &OdbcInfo, schema: &str, table: &str) -> String { + let t = quote(info, table); + if schema.is_empty() || schema == FLAT_SCHEMA && info.namespace == Namespace::Flat { + return t; + } + match info.namespace { + Namespace::Flat => t, + _ => format!("{}.{t}", quote(info, schema)), + } +} + +/// (catalog, schema) arguments for a catalog call about `schema`. +fn scope(info: &OdbcInfo, schema: &str) -> (String, String) { + match info.namespace { + Namespace::Schema => (info.catalog.clone(), schema.to_string()), + Namespace::Catalog => (schema.to_string(), String::new()), + Namespace::Flat => (String::new(), String::new()), + } +} + +/// Read a catalog cursor's columns (1-based) as text. +fn catalog_rows(cursor: &mut impl Cursor, cols: &[u16]) -> Result>>, String> { + let mut out = Vec::new(); + let mut buf = Vec::new(); + let mut wbuf = Vec::new(); + while let Some(mut row) = cursor.next_row().map_err(odbc_err)? { + let mut r = Vec::with_capacity(cols.len()); + for c in cols { + r.push(text_cell(&mut row, *c, &mut buf, &mut wbuf)?); + } + out.push(r); + } + Ok(out) +} + +fn s(v: &Option) -> String { + v.clone().unwrap_or_default() +} + +/// Schemas the database itself keeps, hidden from the list. +fn is_system_schema(name: &str) -> bool { + let n = name.to_ascii_uppercase(); + matches!( + n.as_str(), + "INFORMATION_SCHEMA" | "PG_CATALOG" | "PG_TOAST" | "SYS" | "SYSIBM" | "SYSCAT" | "SYSSTAT" | "SYSFUN" | "SYSIBMADM" | "SYSPROC" + | "SYSTOOLS" | "SYSIBMINTERNAL" | "SYSIBMTS" | "SYSPUBLIC" | "NULLID" | "SQLJ" | "_SYS_BI" | "_SYS_BIC" | "_SYS_REPO" + | "_SYS_STATISTICS" | "_SYS_XS" | "_SYS_AFL" | "_SYS_EPM" | "_SYS_TASK" | "_SYS_SQL_ANALYZER" | "_SYS_PLAN_STABILITY" + | "_SYS_TELEMETRY" | "_SYS_AUDIT" | "_SYS_DATA_ANONYMIZATION" | "_SYS_LDB" | "_SYS_RT" | "_SYS_SECURITY" | "_SYS_SPS" + | "_SYS_WORKLOAD_REPLAY" | "_SYS_DI" | "_SYS_DI_TO" | "_SYS_DI_SEPARATE_CATALOG" | "_SYS_ADVISOR" | "_SYS_XB" + | "SYS_SPATIAL" | "UIS" | "HANA_XS_BASE" | "%LIBRARY" | "%SYS" | "INFORMATION_SCHEMA_VIEWS" | "V_CATALOG" | "V_MONITOR" + | "V_INTERNAL" | "V_FUNC" | "V_TXTINDEX" | "DBC" | "SYSLIB" | "SYSUDTLIB" | "SYSSPATIAL" | "TD_SYSFNLIB" | "TD_SYSXML" + | "SYSBAR" | "SYSJDBC" | "SYSXML" | "SYS_CALENDAR" | "TDSTATS" | "TD_SYSGPL" | "TDQCD" | "SQLJ_SYS" | "EXA_STATISTICS" + | "PERFORMANCE_SCHEMA" | "MYSQL" + ) +} + +/// Every schema name: SQL_ALL_SCHEMAS (catalog "", schema "%", table ""), +/// or, where a driver answers that with nothing, the schemas its tables are in. +fn schema_names(conn: &Connection<'static>, info: &OdbcInfo) -> Vec { + let ask = |cat: &str, table: &str, types: &str| -> Vec { + let Ok(mut stmt) = conn.preallocate() else { return vec![] }; + let Ok(mut cur) = stmt.tables_cursor(cat, "%", table, types) else { return vec![] }; + catalog_rows(&mut cur, &[2]).unwrap_or_default().into_iter().filter_map(|r| r[0].clone()).filter(|s| !s.is_empty()).collect() + }; + let mut names = ask("", "", ""); + if names.is_empty() { + names = ask(&info.catalog, "%", "TABLE,VIEW"); + } + names.sort(); + names.dedup(); + names +} + +/// Every catalog name: SQL_ALL_CATALOGS (catalog "%", schema "", table ""). +fn catalog_names(conn: &Connection<'static>) -> Vec { + let Ok(mut stmt) = conn.preallocate() else { return vec![] }; + let Ok(mut cur) = stmt.tables_cursor("%", "", "", "") else { return vec![] }; + catalog_rows(&mut cur, &[1]).unwrap_or_default().into_iter().filter_map(|r| r[0].clone()).filter(|s| !s.is_empty()).collect() +} + +pub async fn list_schemas(h: &OdbcHandle) -> Result, String> { + run(h, |conn, info| { + let mut names: Vec = match info.namespace { + Namespace::Flat => return Ok(vec![FLAT_SCHEMA.to_string()]), + Namespace::Schema => schema_names(conn, info), + Namespace::Catalog => catalog_names(conn), + }; + names.sort(); + names.dedup(); + let mine: Vec = names.iter().filter(|n| !is_system_schema(n)).cloned().collect(); + let mut out = if mine.is_empty() { names } else { mine }; + // The connection's own schema or catalog first. + let current = if info.namespace == Namespace::Catalog { info.catalog.clone() } else { String::new() }; + if let Some(i) = out.iter().position(|n| *n == current) { + let c = out.remove(i); + out.insert(0, c); + } + if out.is_empty() { + out.push(FLAT_SCHEMA.to_string()); + } + Ok(out) + }) + .await +} + +fn tables_on(conn: &Connection<'static>, info: &OdbcInfo, schema: &str) -> Result, String> { + let (cat, sch) = scope(info, schema); + let mut stmt = conn.preallocate().map_err(odbc_err)?; + let mut cur = stmt.tables_cursor(&cat, &sch, "%", "TABLE,VIEW").map_err(odbc_err)?; + let mut out: Vec = catalog_rows(&mut cur, &[3, 4])? + .into_iter() + .filter_map(|r| { + let name = r[0].clone()?; + let ty = s(&r[1]).to_ascii_uppercase(); + if ty.contains("SYSTEM") { + return None; + } + Some(TableInfo { + name, + row_count: -1, + kind: if ty.contains("VIEW") { "view".into() } else { "table".into() }, + rls_enabled: None, + created_at: None, + create_order: None, + system: None, + }) + }) + .collect(); + out.sort_by(|a, b| a.name.cmp(&b.name)); + out.dedup_by(|a, b| a.name == b.name); + Ok(out) +} + +pub async fn list_tables(h: &OdbcHandle, schema: &str) -> Result, String> { + let schema = schema.to_string(); + run(h, move |conn, info| tables_on(conn, info, &schema)).await +} + +/// One column of a foreign key: `fk_table.fk_column` references `pk_table.pk_column`. +struct FkRow { + pk_table: String, + pk_column: String, + fk_table: String, + fk_column: String, + name: String, +} + +/// The foreign keys of `table` (outgoing), or of the tables pointing at it. +fn foreign_keys_on(conn: &Connection<'static>, info: &OdbcInfo, schema: &str, table: &str, incoming: bool) -> Result, String> { + let (cat, sch) = scope(info, schema); + let mut stmt = conn.preallocate().map_err(odbc_err)?; + let cur = if incoming { + stmt.foreign_keys_cursor(&cat, &sch, table, "", "", "") + } else { + stmt.foreign_keys_cursor("", "", "", &cat, &sch, table) + }; + let mut cur = match cur { + Ok(c) => c, + // Drivers without SQLForeignKeys (Hive, some flat-file ones). + Err(_) => return Ok(vec![]), + }; + // 3 PKTABLE_NAME, 4 PKCOLUMN_NAME, 7 FKTABLE_NAME, 8 FKCOLUMN_NAME, 12 FK_NAME + Ok(catalog_rows(&mut cur, &[3, 4, 7, 8, 12]) + .unwrap_or_default() + .into_iter() + .map(|r| FkRow { pk_table: s(&r[0]), pk_column: s(&r[1]), fk_table: s(&r[2]), fk_column: s(&r[3]), name: s(&r[4]) }) + .collect()) +} + +fn columns_on(conn: &Connection<'static>, info: &OdbcInfo, schema: &str, table: &str) -> Result, String> { + let (cat, sch) = scope(info, schema); + let rows = { + let mut stmt = conn.preallocate().map_err(odbc_err)?; + let mut cur = stmt.columns_cursor(&cat, &sch, table, "%").map_err(odbc_err)?; + // 4 COLUMN_NAME, 5 DATA_TYPE, 6 TYPE_NAME, 7 COLUMN_SIZE, 9 DECIMAL_DIGITS, + // 11 NULLABLE, 12 REMARKS, 13 COLUMN_DEF, 17 ORDINAL_POSITION + let n = cur.num_result_cols().map_err(odbc_err)?; + let wanted: Vec = [4u16, 5, 6, 7, 9, 11, 12, 13, 17].into_iter().filter(|c| (*c as i16) <= n).collect(); + let raw = catalog_rows(&mut cur, &wanted)?; + raw.into_iter() + .map(|r| { + let mut full: Vec> = vec![None; 9]; + for (i, c) in wanted.iter().enumerate() { + let slot = [4u16, 5, 6, 7, 9, 11, 12, 13, 17].iter().position(|x| x == c).unwrap_or(0); + full[slot] = r[i].clone(); + } + full + }) + .collect::>() + }; + let pk: Vec = { + let mut stmt = conn.preallocate().map_err(odbc_err)?; + let cat_opt = (!cat.is_empty()).then_some(cat.as_str()); + let sch_opt = (!sch.is_empty()).then_some(sch.as_str()); + let keys: Vec<(i32, String)> = match stmt.primary_keys_cursor(cat_opt, sch_opt, table) { + Ok(mut cur) => catalog_rows(&mut cur, &[4, 5]) + .unwrap_or_default() + .into_iter() + .map(|r| (s(&r[1]).parse().unwrap_or(0), s(&r[0]))) + .collect(), + Err(_) => vec![], + }; + let mut keys = keys; + keys.sort(); + keys.into_iter().map(|k| k.1).collect() + }; + let fks = foreign_keys_on(conn, info, schema, table, false).unwrap_or_default(); + Ok(rows + .into_iter() + .enumerate() + .map(|(i, r)| { + let name = s(&r[0]); + let ty = s(&r[2]); + let size = s(&r[3]); + let digits = s(&r[4]); + let code: i32 = s(&r[1]).parse().unwrap_or(0); + // Only a character or binary type takes a length: some drivers + // report other types as text (psqlODBC's bool arrives as VARCHAR + // of 5), and `bool(5)` is not a type. + let sized_name = { let t = ty.to_ascii_lowercase(); t.contains("char") || t.contains("binary") || t.contains("string") }; + let shows_size = matches!(code, 1 | 12 | -8 | -9 | -2 | -3) && sized_name && !size.is_empty() && size != "0" && !ty.contains('('); + let shows_scale = matches!(code, 2 | 3) && !size.is_empty() && !ty.contains('('); + let data_type = if shows_size { + format!("{ty}({size})") + } else if shows_scale { + format!("{ty}({size},{})", if digits.is_empty() { "0" } else { &digits }) + } else { + ty + }; + let fk = fks.iter().find(|f| f.fk_column == name); + ColumnStructureRow { + ordinal_position: s(&r[8]).parse().unwrap_or((i + 1) as i32), + data_type, + is_nullable: s(&r[5]) != "0", + column_default: r[7].clone().filter(|d| !d.is_empty()), + foreign_key: fk.map(|f| format!("{}.{}", f.pk_table, f.pk_column)), + fk_constraint_name: fk.map(|f| f.name.clone()).filter(|n| !n.is_empty()), + comment: r[6].clone().filter(|d| !d.is_empty()), + is_primary_key: pk.contains(&name), + name, + } + }) + .collect()) +} + +pub async fn get_column_structure(h: &OdbcHandle, schema: &str, table: &str) -> Result, String> { + let (schema, table) = (schema.to_string(), table.to_string()); + run(h, move |conn, info| columns_on(conn, info, &schema, &table)).await +} + +pub async fn schema_column_structure(h: &OdbcHandle, schema: &str) -> Result, String> { + let schema = schema.to_string(); + run(h, move |conn, info| { + let tables = tables_on(conn, info, &schema)?; + Ok(tables + .into_iter() + .take(500) + .filter_map(|t| columns_on(conn, info, &schema, &t.name).ok().map(|columns| super::schema::TableColumnStructure { table: t.name, columns })) + .collect()) + }) + .await +} + +pub async fn incoming_foreign_keys(h: &OdbcHandle, schema: &str, table: &str) -> Result, String> { + let (schema, table) = (schema.to_string(), table.to_string()); + run(h, move |conn, info| { + let mut out: Vec = Vec::new(); + for f in foreign_keys_on(conn, info, &schema, &table, true)? { + let (col, from_table, ref_col, name) = (f.fk_column, f.fk_table, f.pk_column, f.name); + match out.iter_mut().find(|f| f.from_table == from_table && f.constraint_name == name) { + Some(f) => { + f.from_columns.push(col); + f.to_columns.push(ref_col); + } + None => out.push(super::schema::IncomingForeignKey { + from_schema: schema.clone(), + from_table, + from_columns: vec![col], + to_columns: vec![ref_col], + constraint_name: name, + }), + } + } + Ok(out) + }) + .await +} + +/// A CREATE TABLE written from the catalog: columns, NOT NULL, defaults, the +/// primary key. ODBC has no standard way to ask for the real DDL. +pub async fn get_ddl(h: &OdbcHandle, schema: &str, table: &str) -> Result { + let cols = get_column_structure(h, schema, table).await?; + let info = &h.info; + let mut lines: Vec = cols + .iter() + .map(|c| { + let mut l = format!(" {} {}", quote(info, &c.name), c.data_type); + if !c.is_nullable { + l.push_str(" NOT NULL"); + } + if let Some(d) = &c.column_default { + l.push_str(&format!(" DEFAULT {d}")); + } + l + }) + .collect(); + let pk: Vec = cols.iter().filter(|c| c.is_primary_key).map(|c| quote(info, &c.name)).collect(); + if !pk.is_empty() { + lines.push(format!(" PRIMARY KEY ({})", pk.join(", "))); + } + Ok(format!( + "-- Written from the ODBC catalog ({}); the database's own DDL may differ.\nCREATE TABLE {} (\n{}\n);", + info.dbms, + table_ref(info, schema, table), + lines.join(",\n") + )) +} + +#[cfg_attr(not(test), allow(dead_code))] +pub async fn count_rows(h: &OdbcHandle, schema: &str, table: &str) -> Result { + let sql = format!("SELECT COUNT(*) FROM {}", table_ref(&h.info, schema, table)); + let r = query(h, &sql).await?; + Ok(r.rows.first().and_then(|r| r.first()).and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok())).unwrap_or(-1)) +} + +// ── The grid ────────────────────────────────────────────────────────────────── + +fn is_numeric_type(ty: &str) -> bool { + let t = ty.to_ascii_lowercase(); + ["int", "serial", "decimal", "numeric", "number", "float", "double", "real", "money"].iter().any(|w| t.contains(w)) + && !t.contains("interval") + && !t.contains("point") +} + +fn is_text_type(ty: &str) -> bool { + let t = ty.to_ascii_lowercase(); + ["char", "text", "string", "clob", "memo", "uuid", "json", "xml"].iter().any(|w| t.contains(w)) +} + +/// A column as text, for search and contains-filters on non-text columns. +fn as_text(info: &OdbcInfo, col: &str, ty: &str) -> String { + if is_text_type(ty) { + return col.to_string(); + } + let d = info.dbms.to_ascii_lowercase(); + if d.contains("mysql") || d.contains("mariadb") { + format!("CAST({col} AS CHAR)") + } else if d.contains("access") { + format!("CStr({col})") + } else { + format!("CAST({col} AS VARCHAR(4000))") + } +} + +/// `col op value`, with numbers written in (after checking they are numbers) +/// and everything else bound as a text parameter. +fn compare(col: &str, ty: &str, op: &str, raw: &str, p: &mut Params) -> Option { + if is_numeric_type(ty) { + let t = raw.trim(); + if let Ok(n) = t.parse::() { + p.0.push(Param::Int(n)); + return Some(format!("{col} {op} ?")); + } + if let Ok(x) = t.parse::() { + if x.is_finite() { + p.0.push(Param::Float(x)); + return Some(format!("{col} {op} ?")); + } + } + return None; + } + Some(format!("{col} {op} {}", p.text(raw))) +} + +fn build_where(info: &OdbcInfo, cols: &[ColumnStructureRow], search: Option<&str>, filters: Option<&[RowFilter]>, p: &mut Params) -> String { + let by_name: HashMap<&str, &ColumnStructureRow> = cols.iter().map(|c| (c.name.as_str(), c)).collect(); + let mut clauses: Vec = Vec::new(); + if let Some(q) = search.map(str::trim).filter(|s| !s.is_empty()) { + let needle = format!("%{}%", q.to_lowercase()); + let ors: Vec = cols + .iter() + .filter(|c| is_text_type(&c.data_type)) + .map(|c| format!("LOWER({}) LIKE {}", quote(info, &c.name), p.text(needle.clone()))) + .collect(); + if !ors.is_empty() { + clauses.push(format!("({})", ors.join(" OR "))); + } + } + for f in filters.unwrap_or(&[]) { + let Some(c) = by_name.get(f.column.as_str()) else { continue }; + let col = quote(info, &c.name); + let v = f.value.as_deref().unwrap_or(""); + let text = as_text(info, &col, &c.data_type); + let clause = match f.op.as_str() { + "=" | "eq" | "!=" | "ne" | "neq" | ">" | "gt" | ">=" | "gte" | "<" | "lt" | "<=" | "lte" => { + let op = match f.op.as_str() { + "=" | "eq" => "=", + "!=" | "ne" | "neq" => "<>", + ">" | "gt" => ">", + ">=" | "gte" => ">=", + "<" | "lt" => "<", + _ => "<=", + }; + match compare(&col, &c.data_type, op, v, p) { + Some(c) => c, + None => continue, + } + } + "contains" => format!("LOWER({text}) LIKE {}", p.text(format!("%{}%", v.to_lowercase()))), + "not_contains" => format!("({col} IS NULL OR NOT LOWER({text}) LIKE {})", p.text(format!("%{}%", v.to_lowercase()))), + "starts_with" => format!("LOWER({text}) LIKE {}", p.text(format!("{}%", v.to_lowercase()))), + "ends_with" => format!("LOWER({text}) LIKE {}", p.text(format!("%{}", v.to_lowercase()))), + "between" => { + let mut parts = v.splitn(2, ','); + let (a, b) = (parts.next().unwrap_or("").trim().to_string(), parts.next().unwrap_or("").trim().to_string()); + let mut tmp = p.clone(); + match (compare(&col, &c.data_type, ">=", &a, &mut tmp), compare(&col, &c.data_type, "<=", &b, &mut tmp)) { + (Some(x), Some(y)) => { + *p = tmp; + format!("({x} AND {y})") + } + _ => continue, + } + } + "is_null" => format!("{col} IS NULL"), + "is_not_null" => format!("{col} IS NOT NULL"), + _ => continue, + }; + let joiner = if clauses.is_empty() { "" } else if f.conjunct.as_deref() == Some("or") { " OR " } else { " AND " }; + if joiner.is_empty() { + clauses.push(clause); + } else { + let last = clauses.pop().unwrap_or_default(); + clauses.push(format!("({last}{joiner}{clause})")); + } + } + if clauses.is_empty() { String::new() } else { format!(" WHERE {}", clauses.join(" AND ")) } +} + +/// The page query for a paging style, and how many leading rows to skip here. +pub(crate) fn page_sql(paging: Paging, from: &str, order: &str, limit: i64, offset: i64) -> (String, i64) { + match paging { + Paging::LimitOffset => (format!("SELECT * FROM {from}{order} LIMIT {limit} OFFSET {offset}"), 0), + Paging::OffsetLimit => (format!("SELECT * FROM {from}{order} OFFSET {offset} LIMIT {limit}"), 0), + Paging::OffsetFetch => (format!("SELECT * FROM {from}{order} OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"), 0), + Paging::OffsetFetchOrdered => { + let order = if order.is_empty() { " ORDER BY (SELECT NULL)" } else { order }; + (format!("SELECT * FROM {from}{order} OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"), 0) + } + Paging::SkipFirst => (format!("SELECT SKIP {offset} FIRST {limit} * FROM {from}{order}"), 0), + Paging::Top => (format!("SELECT TOP {} * FROM {from}{order}", limit + offset), offset), + Paging::Client => (format!("SELECT * FROM {from}{order}"), offset), + } +} + +/// Read one page: skip `skip` rows, keep `limit`, then let the cursor go. +fn read_page(conn: &Connection<'static>, sql: &str, p: &Params, skip: i64, limit: i64) -> Result<(Vec, Vec>), String> { + let mut columns = Vec::new(); + let mut rows = Vec::new(); + let mut seen = 0i64; + execute_on(conn, sql, p, None, |c| { + columns = c; + Ok(()) + }, |r| { + seen += 1; + if seen > skip { + rows.push(r); + } + Ok((rows.len() as i64) < limit) + })?; + Ok((columns, rows)) +} + +#[allow(clippy::too_many_arguments)] +pub async fn get_table_rows( + h: &OdbcHandle, + schema: &str, + table: &str, + limit: i64, + offset: i64, + search: Option, + sort_column: Option, + sort_direction: Option, + filters: Option>, +) -> Result { + let t0 = Instant::now(); + let (schema, table) = (schema.to_string(), table.to_string()); + run(h, move |conn, info| { + let cols = columns_on(conn, info, &schema, &table)?; + if cols.is_empty() { + return Err(format!("No table named {table}")); + } + let from = table_ref(info, &schema, &table); + let mut p = Params::default(); + let where_clause = build_where(info, &cols, search.as_deref(), filters.as_deref(), &mut p); + let order = match sort_column.as_deref().filter(|c| cols.iter().any(|x| x.name == *c)) { + Some(c) => { + let d = if sort_direction.as_deref().is_some_and(|d| d.eq_ignore_ascii_case("desc")) { "DESC" } else { "ASC" }; + format!(" ORDER BY {} {d}", quote(info, c)) + } + None => { + let pk: Vec = cols.iter().filter(|c| c.is_primary_key).map(|c| quote(info, &c.name)).collect(); + if pk.is_empty() { String::new() } else { format!(" ORDER BY {}", pk.join(", ")) } + } + }; + let (limit, offset) = (limit.max(0), offset.max(0)); + let from_where = format!("{from}{where_clause}"); + let (sql, skip) = page_sql(info.paging, &from_where, &order, limit, offset); + // A paging clause the database turns out not to speak: read and skip here. + let (sql, page) = match read_page(conn, &sql, &p, skip, limit) { + Ok(page) => (sql, page), + Err(e) if info.paging != Paging::Client => { + let (fallback, skip) = page_sql(Paging::Client, &from_where, &order, limit, offset); + match read_page(conn, &fallback, &p, skip, limit) { + Ok(page) => (fallback, page), + Err(_) => return Err(e), + } + } + Err(e) => return Err(e), + }; + let (columns, rows) = page; + let count_sql = format!("SELECT COUNT(*) FROM {from_where}"); + let total = collect(conn, &count_sql, &p, None, Instant::now()) + .ok() + .and_then(|r| r.rows.first().and_then(|r| r.first()).and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))) + .unwrap_or(offset + rows.len() as i64); + let fks = cols + .iter() + .filter_map(|c| { + let (t, col) = c.foreign_key.as_ref()?.split_once('.')?; + Some(ForeignKeyInfo { + columns: vec![c.name.clone()], + referenced_schema: schema.clone(), + referenced_table: t.to_string(), + referenced_columns: vec![col.to_string()], + }) + }) + .collect(); + Ok(TableRows { + preview_columns: Vec::new(), + columns, + rows, + total, + query_ms: t0.elapsed().as_millis() as u64, + primary_key: cols.iter().filter(|c| c.is_primary_key).map(|c| c.name.clone()).collect(), + foreign_keys: fks, + sql: format!("{sql}\n{count_sql}"), + }) + }) + .await +} + +/// A grid value as a typed parameter for a column, or NULL. +fn bind_value(ty: &str, v: &Value, p: &mut Params) -> String { + match v { + Value::Null => "NULL".into(), + Value::Bool(b) => { + // Booleans as 1/0: every SQL engine's BIT, SMALLINT or BOOLEAN takes it. + p.0.push(Param::Int(*b as i64)); + "?".into() + } + Value::Number(n) if n.is_i64() => { + p.0.push(Param::Int(n.as_i64().unwrap_or(0))); + "?".into() + } + Value::Number(n) => { + p.0.push(Param::Float(n.as_f64().unwrap_or(0.0))); + "?".into() + } + Value::String(s) if is_numeric_type(ty) => { + if let Ok(n) = s.trim().parse::() { + p.0.push(Param::Int(n)); + } else { + p.text(s.clone()); + } + "?".into() + } + Value::String(s) => p.text(s.clone()).into(), + other => p.text(other.to_string()).into(), + } +} + +fn pk_where(info: &OdbcInfo, cols: &[ColumnStructureRow], pk: &HashMap, p: &mut Params) -> Result { + let keys: Vec<&ColumnStructureRow> = cols.iter().filter(|c| c.is_primary_key).collect(); + if keys.is_empty() { + return Err("This table reports no primary key through its ODBC driver, so the grid can't tell rows apart. \ + Use UPDATE or DELETE in the SQL console." + .into()); + } + let mut parts = Vec::new(); + for c in keys { + let v = pk.get(&c.name).ok_or_else(|| format!("The row's {} is missing", c.name))?; + let col = quote(info, &c.name); + if v.is_null() { + parts.push(format!("{col} IS NULL")); + } else { + parts.push(format!("{col} = {}", bind_value(&c.data_type, v, p))); + } + } + Ok(parts.join(" AND ")) +} + +fn write(conn: &Connection<'static>, sql: &str, p: &Params) -> Result, String> { + execute_on(conn, sql, p, None, |_| Ok(()), |_| Ok(false)) +} + +pub async fn update_table_cell( + h: &OdbcHandle, + schema: &str, + table: &str, + primary_key: HashMap, + column: &str, + value: &Value, +) -> Result<(), String> { + let (schema, table, column, value) = (schema.to_string(), table.to_string(), column.to_string(), value.clone()); + run(h, move |conn, info| { + let cols = columns_on(conn, info, &schema, &table)?; + let c = cols.iter().find(|c| c.name == column).ok_or_else(|| format!("No column named {column}"))?; + let mut p = Params::default(); + let set = format!("{} = {}", quote(info, &column), bind_value(&c.data_type, &value, &mut p)); + let w = pk_where(info, &cols, &primary_key, &mut p)?; + let sql = format!("UPDATE {} SET {set} WHERE {w}", table_ref(info, &schema, &table)); + match write(conn, &sql, &p)? { + Some(1) | None => Ok(()), + Some(n) => Err(super::query::row_count_error(&primary_key.keys().cloned().collect::>(), &primary_key, n as u64)), + } + }) + .await +} + +pub async fn insert_table_row(h: &OdbcHandle, schema: &str, table: &str, values: HashMap) -> Result, String> { + let (schema, table) = (schema.to_string(), table.to_string()); + run(h, move |conn, info| { + let cols = columns_on(conn, info, &schema, &table)?; + let mut p = Params::default(); + let mut names = Vec::new(); + let mut holes = Vec::new(); + for c in &cols { + let Some(v) = values.get(&c.name) else { continue }; + names.push(quote(info, &c.name)); + holes.push(bind_value(&c.data_type, v, &mut p)); + } + if names.is_empty() { + return Err("Fill in at least one column".into()); + } + let sql = format!("INSERT INTO {} ({}) VALUES ({})", table_ref(info, &schema, &table), names.join(", "), holes.join(", ")); + write(conn, &sql, &p)?; + Ok(cols.iter().map(|c| values.get(&c.name).cloned().unwrap_or(Value::Null)).collect()) + }) + .await +} + +pub async fn delete_table_rows(h: &OdbcHandle, schema: &str, table: &str, primary_keys: Vec>) -> Result { + if primary_keys.is_empty() { + return Ok(0); + } + let (schema, table) = (schema.to_string(), table.to_string()); + run(h, move |conn, info| { + let cols = columns_on(conn, info, &schema, &table)?; + let mut p = Params::default(); + let mut ors = Vec::new(); + for pk in &primary_keys { + ors.push(format!("({})", pk_where(info, &cols, pk, &mut p)?)); + } + let sql = format!("DELETE FROM {} WHERE {}", table_ref(info, &schema, &table), ors.join(" OR ")); + Ok(write(conn, &sql, &p)?.map(|n| n as u64).unwrap_or(primary_keys.len() as u64)) + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg(cs: Option<&str>, dsn: Option<&str>, user: Option<&str>, pw: Option<&str>) -> OdbcConfig { + OdbcConfig { + name: "t".into(), + preset: None, + dsn: dsn.map(String::from), + connection_string: cs.map(String::from), + user: user.map(String::from), + password: pw.map(String::from), + ssh: None, + target_host: None, + target_port: None, + } + } + + #[test] + fn a_missing_dsn_says_which_and_where() { + let im002 = "[unixODBC][Driver Manager]Data source name not found and no default driver specified".to_string(); + let e = explain_connect(&cfg(None, Some("ShopPG"), None, None), im002.clone()); + assert!(e.contains("\"ShopPG\"") && e.contains("odbc.ini"), "{e}"); + let e = explain_connect(&cfg(Some("Server=x"), None, None, None), im002); + assert!(e.contains("Driver={"), "{e}"); + assert_eq!(explain_connect(&cfg(None, Some("X"), None, None), "Login failed".into()), "Login failed"); + } + + #[test] + fn connection_strings_carry_credentials_once() { + assert_eq!( + connection_string(&cfg(Some("Driver={Db2};Hostname=h;Port=50000"), None, Some("me"), Some("p;w}d"))).unwrap(), + "Driver={Db2};Hostname=h;Port=50000;UID=me;PWD={p;w}}d};" + ); + assert_eq!(connection_string(&cfg(None, Some("Sales DW"), None, None)).unwrap(), "DSN=Sales DW;"); + // A string that already says who: left alone. + assert_eq!(connection_string(&cfg(Some("DSN=x;UID=a;PWD=b;"), None, Some("me"), Some("pw"))).unwrap(), "DSN=x;UID=a;PWD=b;"); + assert!(connection_string(&cfg(None, None, None, None)).is_err()); + } + + /// Through a real SSH server (STROKE_TEST_ODBC_SSH = key|ssh port|db host|db port|connection string). + #[tokio::test] + async fn live_through_ssh() { + let Ok(spec) = std::env::var("STROKE_TEST_ODBC_SSH") else { return }; + let p: Vec<&str> = spec.splitn(5, '|').collect(); + let mut c = cfg(Some(p[4]), None, None, None); + c.ssh = Some(super::super::ssh_tunnel::SshConfig { + host: "127.0.0.1".into(), + port: p[1].parse().unwrap(), + username: "tester".into(), + private_key_path: p[0].into(), + keepalive: 0, + ..Default::default() + }); + c.target_host = Some(p[2].into()); + c.target_port = Some(p[3].parse().unwrap()); + let (c, tunnel) = crate::db::connection::resolve_odbc_ssh(c).await.unwrap(); + let tunnel = tunnel.expect("a tunnel"); + let cs = c.connection_string.clone().unwrap(); + assert!(cs.contains("127.0.0.1") && cs.contains(&tunnel.local_port.to_string()) && !cs.contains(p[2]), "{cs}"); + let h = connect(&c).await.unwrap(); + assert_eq!(query(&h, "SELECT 41 + 1").await.unwrap().rows[0][0], json!(42)); + } + + #[test] + fn tunnels_retarget_host_and_port_only() { + let db2 = "Driver={IBM DB2 ODBC DRIVER};Database=SAMPLE;Hostname=db.internal;Port=50000;Protocol=TCPIP;"; + assert_eq!(retarget(db2, "db.internal", 50000, 41234), "Driver={IBM DB2 ODBC DRIVER};Database=SAMPLE;Hostname=127.0.0.1;Port=41234;Protocol=TCPIP;"); + assert_eq!(retarget("Driver={HDBODBC};ServerNode=hana.internal:30015;", "hana.internal", 30015, 5000), "Driver={HDBODBC};ServerNode=127.0.0.1:5000;"); + assert_eq!(retarget("DBQ=//ora:1521/FREEPDB1;", "ora", 1521, 7000), "DBQ=//127.0.0.1:7000/FREEPDB1;"); + assert_eq!(retarget("Dbname=fb/3050:/data/x.fdb;", "fb", 3050, 7001), "Dbname=127.0.0.1/7001:/data/x.fdb;"); + // A database named like the port, or a driver brace with ';', stays. + assert_eq!(retarget("Driver={A;B};Database=50000x;Port=50000", "h", 50000, 1), "Driver={A;B};Database=50000x;Port=1"); + } + + #[test] + fn paging_follows_the_database() { + assert_eq!(paging_for("PostgreSQL"), Paging::LimitOffset); + assert_eq!(paging_for("HDB"), Paging::LimitOffset); + assert_eq!(paging_for("DB2/LINUXX8664"), Paging::OffsetFetch); + assert_eq!(paging_for("Trino"), Paging::OffsetLimit); + assert_eq!(paging_for("Microsoft SQL Server"), Paging::OffsetFetchOrdered); + assert_eq!(paging_for("Teradata"), Paging::Top); + assert_eq!(paging_for("Informix Dynamic Server"), Paging::SkipFirst); + assert_eq!(paging_for("Something New"), Paging::Client); + assert_eq!(page_sql(Paging::Top, "t", "", 50, 100), ("SELECT TOP 150 * FROM t".to_string(), 100)); + assert_eq!(page_sql(Paging::OffsetFetchOrdered, "t", "", 5, 0).0, "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); + } + + #[test] + fn identifiers_quote_the_drivers_way() { + let mut info = OdbcInfo { dbms: "x".into(), quote: Some('"'), namespace: Namespace::Schema, catalog: String::new(), paging: Paging::Client }; + assert_eq!(table_ref(&info, "s", "a\"b"), "\"s\".\"a\"\"b\""); + info.quote = Some('`'); + info.namespace = Namespace::Catalog; + assert_eq!(table_ref(&info, "shop", "t"), "`shop`.`t`"); + info.namespace = Namespace::Flat; + assert_eq!(table_ref(&info, FLAT_SCHEMA, "t"), "`t`"); + info.quote = Some('['); + assert_eq!(quote(&info, "a]b"), "[a]]b]"); + } + + #[cfg(not(windows))] + #[test] + fn registries_merge_with_full_driver_paths() { + let a = "[PostgreSQL Unicode]\nDriver=psqlodbcw.so\nSetup = libodbcpsqlS.so\n\n[Db2]\nDriver=/opt/ibm/libdb2o.so\n".to_string(); + let b = "# brew\n[Db2]\nDriver=/elsewhere.so\n[Vertica]\nDriver=/opt/vertica/lib64/libverticaodbc.so\n".to_string(); + let out = registry::merge(&[a, b], &|name| Some(format!("/usr/lib/x/odbc/{name}"))); + assert!(out.contains("[PostgreSQL Unicode]\nDriver = /usr/lib/x/odbc/psqlodbcw.so\nSetup = /usr/lib/x/odbc/libodbcpsqlS.so")); + assert!(out.contains("[Db2]\nDriver = /opt/ibm/libdb2o.so")); + assert!(!out.contains("/elsewhere.so"), "the first registry to name a driver wins"); + assert!(out.contains("[Vertica]")); + } + + #[test] + fn filters_bind_values_and_write_numbers_checked() { + let info = OdbcInfo { dbms: "PostgreSQL".into(), quote: Some('"'), namespace: Namespace::Schema, catalog: String::new(), paging: Paging::LimitOffset }; + let col = |n: &str, t: &str| ColumnStructureRow { + ordinal_position: 1, name: n.into(), data_type: t.into(), is_nullable: true, column_default: None, + foreign_key: None, fk_constraint_name: None, comment: None, is_primary_key: false, + }; + let cols = vec![col("id", "int4"), col("name", "varchar(40)")]; + let mut p = Params::default(); + let f = |c: &str, op: &str, v: &str| RowFilter { column: c.into(), op: op.into(), value: Some(v.into()), conjunct: None, data_type: None }; + let w = build_where(&info, &cols, Some("Ann"), Some(&[f("id", ">=", "2"), f("id", "=", "2; DROP TABLE x")]), &mut p); + assert_eq!(w, " WHERE ((LOWER(\"name\") LIKE ?) AND \"id\" >= ?)"); + assert!(matches!(p.0[0], Param::Text(ref s) if s == "%ann%")); + assert!(matches!(p.0[1], Param::Int(2))); + } + + /// Live, through a real driver: STROKE_TEST_ODBC is a connection string, + /// e.g. `Driver={SQLite3};Database=/tmp/t.db` or + /// `Driver={PostgreSQL Unicode};Server=localhost;Port=5432;Database=postgres;UID=postgres;PWD=pw`. + #[tokio::test] + async fn live_round_trip() { + let Ok(cs) = std::env::var("STROKE_TEST_ODBC") else { return }; + let h = connect(&cfg(Some(&cs), None, None, None)).await.unwrap(); + ping(&h).await.unwrap(); + let t = format!("stroke_odbc_{}", std::process::id()); + let schemas = list_schemas(&h).await.unwrap(); + let schema = match h.info.namespace { + Namespace::Schema => schemas.iter().find(|s| s.eq_ignore_ascii_case("public") || s.eq_ignore_ascii_case("dbo")).cloned().unwrap_or(schemas[0].clone()), + Namespace::Catalog => h.info.catalog.clone(), + Namespace::Flat => FLAT_SCHEMA.to_string(), + }; + let tref = table_ref(&h.info, &schema, &t); + if query(&h, &format!("CREATE TABLE {tref} (id INTEGER NOT NULL PRIMARY KEY, label VARCHAR(40), price DOUBLE PRECISION, ok SMALLINT)")) + .await + .is_err() + { + query(&h, &format!("CREATE TABLE {tref} (id INTEGER NOT NULL PRIMARY KEY, label VARCHAR(40), price DOUBLE, ok SMALLINT)")).await.unwrap(); + } + // A second table pointing at the first, for the foreign key jumps. + let child = format!("{t}_c"); + let cref = table_ref(&h.info, &schema, &child); + let made_child = query(&h, &format!("CREATE TABLE {cref} (cid INTEGER NOT NULL PRIMARY KEY, item_id INTEGER, FOREIGN KEY (item_id) REFERENCES {tref} (id))")).await.is_ok(); + let ins = query(&h, &format!("INSERT INTO {tref} (id, label, price, ok) VALUES (1, 'pen', 2.5, 1), (2, 'cup', 4, 0)")).await.unwrap(); + assert_eq!(ins.row_count, Some(2), "{ins:?}"); + assert!(list_tables(&h, &schema).await.unwrap().iter().any(|x| x.name == t)); + let cols = get_column_structure(&h, &schema, &t).await.unwrap(); + assert_eq!(cols.len(), 4); + assert!(cols[0].is_primary_key, "{cols:?}"); + assert!(!cols[0].is_nullable); + + let page = get_table_rows(&h, &schema, &t, 1, 1, None, None, None, None).await.unwrap(); + assert_eq!(page.rows.len(), 1); + assert_eq!(page.rows[0][0], json!(2)); + assert_eq!(page.total, 2); + let f = RowFilter { column: "price".into(), op: ">".into(), value: Some("3".into()), conjunct: None, data_type: None }; + let page = get_table_rows(&h, &schema, &t, 50, 0, Some("CU".into()), Some("id".into()), Some("desc".into()), Some(vec![f])).await.unwrap(); + assert_eq!(page.rows.len(), 1, "{}", page.sql); + assert_eq!(page.rows[0][1], json!("cup")); + assert_eq!(page.rows[0][2], json!(4.0)); + + update_table_cell(&h, &schema, &t, HashMap::from([("id".into(), json!(1))]), "label", &json!("pencil")).await.unwrap(); + update_table_cell(&h, &schema, &t, HashMap::from([("id".into(), json!(2))]), "price", &Value::Null).await.unwrap(); + insert_table_row(&h, &schema, &t, HashMap::from([("id".into(), json!(3)), ("label".into(), json!("ink"))])).await.unwrap(); + let r = query(&h, &format!("SELECT id, label, price FROM {tref} ORDER BY id")).await.unwrap(); + assert_eq!(r.rows.len(), 3); + assert_eq!(r.rows[0][1], json!("pencil")); + assert_eq!(r.rows[1][2], Value::Null); + assert_eq!(delete_table_rows(&h, &schema, &t, vec![HashMap::from([("id".into(), json!(3))])]).await.unwrap(), 1); + assert_eq!(count_rows(&h, &schema, &t).await.unwrap(), 2); + assert!(get_ddl(&h, &schema, &t).await.unwrap().contains("PRIMARY KEY")); + assert!(query(&h, "SELECT nope FROM no_such_table_here").await.is_err()); + if made_child { + let ccols = get_column_structure(&h, &schema, &child).await.unwrap(); + let item = ccols.iter().find(|c| c.name == "item_id").unwrap(); + // SQLite's ODBC driver reports no foreign keys; the others do. + if !h.info.dbms.to_ascii_lowercase().contains("sqlite") { + assert_eq!(item.foreign_key.as_deref(), Some(format!("{t}.id").as_str()), "{ccols:?}"); + let inc = incoming_foreign_keys(&h, &schema, &t).await.unwrap(); + assert!(inc.iter().any(|f| f.from_table == child && f.from_columns == ["item_id"] && f.to_columns == ["id"]), "{}", inc.len()); + } + query(&h, &format!("DROP TABLE {cref}")).await.unwrap(); + } + query(&h, &format!("DROP TABLE {tref}")).await.unwrap(); + + // Stop: SQLCancel ends a long statement on the server. + let d = h.info.dbms.to_ascii_lowercase(); + let slow = if d.contains("postgres") { + Some("SELECT pg_sleep(30)") + } else if d.contains("mysql") || d.contains("mariadb") { + Some("SELECT SLEEP(30)") + } else { + None + }; + if let Some(slow) = slow { + let (tx, rx) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + let _ = tx.send(()); + }); + let t0 = Instant::now(); + let r = query_cancellable(&h, slow, rx).await; + let took = t0.elapsed(); + // MariaDB answers a cancelled SLEEP with its row (1) rather than an error. + assert!(took < std::time::Duration::from_secs(10), "Stop took {took:?}: {r:?}"); + // The connection is usable afterwards. + assert_eq!(query(&h, "SELECT 1").await.unwrap().rows[0][0], json!(1)); + } + } +} diff --git a/src-tauri/src/db/oracle.rs b/src-tauri/src/db/oracle.rs index c9c3872f..6452530d 100644 --- a/src-tauri/src/db/oracle.rs +++ b/src-tauri/src/db/oracle.rs @@ -28,6 +28,8 @@ use std::time::Instant; pub struct OracleSession { conn: Connection, lock: Mutex<()>, + /// How this session was opened, so a transaction can open its own. + cfg: OracleConfig, /// What the grid needs to know about a table besides its rows, by /// (schema, table). The ALL_* dictionary views behind it are the slow part /// of a page fetch (seconds for a user who sees every schema), and none of @@ -225,26 +227,53 @@ fn ensure_client(explicit_dir: &str) -> Result<(), String> { } /// Why Instant Client in `dir` would not load, and what fixes it. +/// +/// A missing dependency surfaces as "libclntsh.so: cannot open shared object +/// file", naming the library that was found rather than the one that wasn't, +/// so libaio is probed for directly instead of looked for in the message. fn load_error(dir: &Path, msg: &str) -> String { - let hint = if msg.contains("libaio") { - " Instant Client needs libaio: install it (libaio1, or libaio1t64 on Ubuntu 24.04 and later, where \ - libaio.so.1 also needs a link: sudo ln -s /usr/lib/x86_64-linux-gnu/libaio.so.1t64 /usr/lib/x86_64-linux-gnu/libaio.so.1)." - .to_string() - } else if cfg!(target_os = "linux") && msg.contains("cannot open shared object file") { + let missing_dep = cfg!(target_os = "linux") && msg.contains("cannot open shared object file"); + let mut hint = String::new(); + if msg.contains("libaio") || (missing_dep && !libaio_loads()) { + let lib = format!("/usr/lib/{}-linux-gnu", std::env::consts::ARCH); + hint.push_str(&format!( + " Instant Client needs libaio: install it (libaio1, or libaio1t64 on Ubuntu 24.04 and later, where \ + libaio.so.1 also needs a link: sudo ln -s {lib}/libaio.so.1t64 {lib}/libaio.so.1)." + )); + } + if missing_dep { // Linux Instant Client libraries carry no $ORIGIN run path, so their // own dependencies (libnnz.so) resolve only through the linker's path. - format!( + hint.push_str(&format!( " On Linux the Instant Client folder must also be on the library path: run \ sudo sh -c 'echo {} > /etc/ld.so.conf.d/oracle-instantclient.conf' && sudo ldconfig, then restart Stroke \ (or start Stroke with LD_LIBRARY_PATH set to that folder).", dir.display() - ) - } else { - String::new() - }; + )); + } format!("Could not load Oracle Instant Client from \"{}\": {msg}{hint}", dir.display()) } +/// Whether the dynamic linker can load libaio.so.1, which Instant Client links. +#[cfg(target_os = "linux")] +fn libaio_loads() -> bool { + let name = c"libaio.so.1"; + // SAFETY: dlopen with a valid C string; the handle is closed straight away. + unsafe { + let h = libc::dlopen(name.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL); + if h.is_null() { + return false; + } + libc::dlclose(h); + } + true +} + +#[cfg(not(target_os = "linux"))] +fn libaio_loads() -> bool { + true +} + // ── Connect ────────────────────────────────────────────────────────────────── /// The connect string ODPI-C gets: the connection's own Easy Connect / TNS @@ -349,7 +378,7 @@ pub async fn connect(cfg: &OracleConfig) -> Result { .connect() .map_err(|e| explain_connect_error(&e.to_string()))?; conn.execute(SESSION_SETUP, &[]).map_err(|e| format!("Oracle session setup failed: {}", clean_err(&e.to_string())))?; - Ok(std::sync::Arc::new(OracleSession { conn, lock: Mutex::new(()), meta: Mutex::new(HashMap::new()) })) + Ok(std::sync::Arc::new(OracleSession { conn, lock: Mutex::new(()), meta: Mutex::new(HashMap::new()), cfg })) }) .await .map_err(|e| format!("Oracle connect task failed: {e}"))? @@ -920,7 +949,7 @@ fn run_one(conn: &Connection, sql: &str, binds: &[Bind]) -> Result Result bool { + reads_only(sql) && !split_statements(sql).is_empty() && split_statements(sql).len() == 1 +} + +/// A query, streamed into `sink` a batch at a time while Oracle fetches it. +/// +/// `run_one` collected every row before the grid saw one, so a large result +/// stopped at the collect budget. Here the session's thread fetches 500 rows +/// per round trip and hands them over in batches of 1,000, so memory stays +/// flat whatever the size. Stop breaks the call on the server. +pub async fn stream_into( + handle: &OracleHandle, + sql: &str, + sink: &mut super::query::RowSink, + stop: &super::stop::Stop, +) -> Result { + enum Msg { + Columns(Vec), + Rows(Vec>), + } + const BATCH: usize = 1_000; + let stmt_sql = split_statements(sql).into_iter().next().unwrap_or_default(); + let (tx, mut rx) = tokio::sync::mpsc::channel::(8); + let reader = run_blocking(handle, move |conn| { + let mut stmt = conn.statement(&stmt_sql).fetch_array_size(500).build().map_err(ora_err)?; + let rs = stmt.query(&[]).map_err(ora_err)?; + let infos = rs.column_info().to_vec(); + let columns: Vec = infos + .iter() + .map(|c| { + let mut ci = ColumnInfo::new(c.name().to_string(), type_label(c.oracle_type())); + ci.nullable = c.nullable(); + ci + }) + .collect(); + if tx.blocking_send(Msg::Columns(columns)).is_err() { + return Ok(()); + } + let mut batch = Vec::with_capacity(BATCH); + for row in rs { + let row = row.map_err(ora_err)?; + batch.push(row.sql_values().iter().zip(infos.iter()).map(|(v, c)| cell_to_json(v, c.oracle_type())).collect()); + if batch.len() >= BATCH && tx.blocking_send(Msg::Rows(std::mem::replace(&mut batch, Vec::with_capacity(BATCH)))).is_err() { + return Ok(()); + } + } + if !batch.is_empty() { + let _ = tx.blocking_send(Msg::Rows(batch)); + } + Ok(()) + }); + tokio::pin!(reader); + let t0 = Instant::now(); + let mut columns = Vec::new(); + let mut total = 0usize; + let mut sink_err: Option = None; + let mut reader_out: Option> = None; + let mut stopped = false; + loop { + tokio::select! { + msg = rx.recv() => match msg { + Some(Msg::Columns(c)) => columns = c, + Some(Msg::Rows(rows)) => { + if sink_err.is_some() || stopped { + continue; + } + for r in rows { + if total == 0 { + if let Err(e) = sink.start(columns.clone()) { sink_err = Some(e); break; } + } + if let Err(e) = sink.push(r) { sink_err = Some(e); break; } + total += 1; + } + if sink_err.is_some() { + rx.close(); + } + } + None => break, + }, + out = &mut reader, if reader_out.is_none() => reader_out = Some(out), + _ = stop.wait(), if !stopped => { + stopped = true; + rx.close(); + cancel(handle).await; + } + } + } + let out = match reader_out { + Some(o) => o, + None => reader.await, + }; + if stopped { + return Err(super::query::QUERY_CANCELLED.into()); + } + if let Some(e) = sink_err { + return Err(e); + } + out?; + if total > 0 { + sink.finish()?; + } + Ok(SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + /// `run_one`, committed when it wrote (a query has nothing to commit). fn run_commit(conn: &Connection, sql: &str, binds: &[Bind]) -> Result { let r = run_one(conn, sql, binds); @@ -943,6 +1077,45 @@ fn run_commit(conn: &Connection, sql: &str, binds: &[Bind]) -> Result Result { + connect(&handle.cfg).await +} + +/// Statements inside the open transaction: nothing commits until tx_commit. +pub async fn execute_in_tx(handle: &OracleHandle, sql: &str) -> Result { + let stmts = split_statements(sql); + if stmts.is_empty() { + return Err("Query is empty".into()); + } + let original = sql.trim().to_string(); + run_blocking(handle, move |conn| { + let mut last = None; + for s in &stmts { + last = Some(run_one(conn, s, &[])?); + } + let mut out = last.expect("non-empty"); + out.sql = original; + Ok(out) + }) + .await +} + +pub async fn commit(handle: &OracleHandle) -> Result<(), String> { + run_blocking(handle, |conn| conn.commit().map_err(ora_err)).await +} + +pub async fn rollback(handle: &OracleHandle) -> Result<(), String> { + run_blocking(handle, |conn| conn.rollback().map_err(ora_err)).await +} + /// Run a script: each statement in turn, the last one's result returned. pub async fn execute_sql(handle: &OracleHandle, sql: &str) -> Result { let stmts = split_statements(sql); @@ -1811,7 +1984,7 @@ mod live_tests { let url = std::env::var("STROKE_ORACLE_TEST").ok()?; let (creds, cs) = url.split_once('@')?; let (user, password) = creds.split_once('/')?; - Some(OracleConfig { + Some(OracleConfig { ssh: None, name: "live".into(), host: String::new(), port: 1521, @@ -1862,8 +2035,20 @@ mod live_tests { mod tests { use super::*; + #[test] + fn load_error_names_libaio_when_it_is_missing() { + let msg = "DPI-1047: Cannot locate a 64-bit Oracle Client library: \"libclntsh.so: cannot open shared object file: No such file or directory\""; + let e = load_error(Path::new("/opt/ic"), msg); + assert!(e.contains("library path"), "{e}"); + if cfg!(target_os = "linux") { + assert_eq!(e.contains("needs libaio"), !libaio_loads(), "{e}"); + assert!(!e.contains("needs libaio") || e.contains(std::env::consts::ARCH), "{e}"); + } + assert!(load_error(Path::new("/opt/ic"), "libaio.so.1: cannot open").contains("needs libaio")); + } + fn cfg() -> OracleConfig { - OracleConfig { + OracleConfig { ssh: None, name: "t".into(), host: "db.example.com".into(), port: 1521, @@ -2050,7 +2235,7 @@ mod tests { let url = std::env::var("STROKE_ORACLE_TEST_URL").ok()?; let (creds, cs) = url.split_once('@')?; let (user, password) = creds.split_once('/')?; - Some(OracleConfig { + Some(OracleConfig { ssh: None, name: "live".into(), host: String::new(), port: 1521, @@ -2230,7 +2415,7 @@ mod tests { assert_eq!(exact_row_count(&h, "STROKE", "STROKE_TYPES").await.unwrap(), 28); // Messages, the explain plan and an error the UI can show. - assert_eq!(exec(&h, "UPDATE stroke_types SET ratio = 1 WHERE id < 5;").await.message.as_deref(), Some("4 row(s) affected")); + assert_eq!(exec(&h, "UPDATE stroke_types SET ratio = 1 WHERE id < 5;").await.message.as_deref(), Some("4 rows affected")); assert_eq!(exec(&h, "begin null; end;").await.message.as_deref(), Some("PL/SQL procedure successfully completed")); let plan = explain_lines(&h, "SELECT * FROM stroke_types WHERE id = 5").await.unwrap(); assert!(plan.iter().any(|l| l.contains("INDEX UNIQUE SCAN") || l.contains("TABLE ACCESS")), "{plan:?}"); diff --git a/src-tauri/src/db/parked.rs b/src-tauri/src/db/parked.rs index 6c84f0ff..1e996655 100644 --- a/src-tauri/src/db/parked.rs +++ b/src-tauri/src/db/parked.rs @@ -11,16 +11,20 @@ const MAX_PARKED: usize = 8; /// Set the open connection aside under `key`. Nothing open: nothing to do. #[tauri::command] pub fn park_connection(state: Db<'_>, key: String) -> Result<(), String> { + super::tx::connection_changed(); let Some(conn) = state.conn.lock().map_err(|e| e.to_string())?.take() else { return Ok(()); }; *state.active_key.lock().map_err(|e| e.to_string())? = None; + // Its SSH tunnel, if any, goes aside with it. + super::ssh_tunnel::park_active(&key); let mut parked = state.parked.lock().map_err(|e| e.to_string())?; parked.retain(|(k, _)| k != &key); parked.push((key, conn)); while parked.len() > MAX_PARKED { - let (_, old) = parked.remove(0); + let (old_key, old) = parked.remove(0); close_in_background(old); + super::ssh_tunnel::drop_parked(&[old_key]); } Ok(()) } @@ -34,6 +38,9 @@ pub fn resume_connection(state: Db<'_>, key: String) -> Result { parked.iter().position(|(k, _)| k == &key).map(|i| parked.remove(i).1) }; let Some(conn) = found else { return Ok(false) }; + super::tx::connection_changed(); + // Its tunnel comes back with it (and whatever was in front closes). + super::ssh_tunnel::resume_parked(&key); let previous = state.conn.lock().map_err(|e| e.to_string())?.replace(conn); *state.active_key.lock().map_err(|e| e.to_string())? = Some(key); if let Some(prev) = previous { @@ -59,9 +66,11 @@ pub fn close_parked( (None, None) => true, }); *parked = kept; + let keys: Vec = gone.iter().map(|(k, _)| k.clone()).collect(); for (_, c) in gone { close_in_background(c); } + super::ssh_tunnel::drop_parked(&keys); Ok(()) } diff --git a/src-tauri/src/db/posthog.rs b/src-tauri/src/db/posthog.rs index 02dd8844..2daedbbf 100644 --- a/src-tauri/src/db/posthog.rs +++ b/src-tauri/src/db/posthog.rs @@ -28,7 +28,7 @@ const SCHEMA_TTL: Duration = Duration::from_secs(300); fn client() -> &'static reqwest::Client { static C: OnceLock = OnceLock::new(); C.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Database) .user_agent("stroke/1.0") .pool_idle_timeout(Duration::from_secs(20)) .connect_timeout(Duration::from_secs(10)) @@ -41,6 +41,51 @@ fn client() -> &'static reqwest::Client { /// POST one query object to the project's query endpoint. async fn post_query(config: &PosthogConfig, query: Value) -> Result { + post_query_as(config, query, None).await +} + +/// `query`, stoppable on PostHog's side: the request carries a +/// client_query_id, and Stop asks PostHog to cancel that query (DELETE on the +/// query endpoint) instead of leaving it running against the 3-at-once limit. +pub async fn query_cancellable(config: &PosthogConfig, sql: &str, stop: &super::stop::Stop) -> Result { + let trimmed = sql.trim().trim_end_matches(';'); + if !is_read_query(trimmed) { + return Err("PostHog is read-only here: HogQL runs SELECT (and WITH) queries.".into()); + } + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = format!( + "stroke-{:x}-{:x}-{:x}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ); + let t0 = Instant::now(); + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(post_query_as(config, json!({ "kind": "HogQLQuery", "query": trimmed }), Some(&id))); + tokio::select! { + r = &mut run => Ok(to_sql_result(&r?, sql, t0.elapsed().as_millis() as u64)), + _ = stop.wait() => { + drop(run); + let _ = tokio::time::timeout(Duration::from_secs(10), cancel_query(config, &id)).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +/// DELETE /api/projects/{id}/query/{client_query_id}/: PostHog kills it in ClickHouse. +pub async fn cancel_query(config: &PosthogConfig, client_query_id: &str) -> Result<(), String> { + let url = format!( + "{}/api/projects/{}/query/{}/", + config.base_url(), + urlencoding::encode(config.project_id.trim()), + urlencoding::encode(client_query_id) + ); + let resp = client().delete(&url).bearer_auth(config.api_key.trim()).send().await.map_err(|e| format!("PostHog request failed: {e}"))?; + if resp.status().is_success() { Ok(()) } else { Err(format!("PostHog could not cancel the query (HTTP {})", resp.status().as_u16())) } +} + +async fn post_query_as(config: &PosthogConfig, query: Value, client_query_id: Option<&str>) -> Result { let url = format!( "{}/api/projects/{}/query/", config.base_url(), @@ -49,7 +94,10 @@ async fn post_query(config: &PosthogConfig, query: Value) -> Result json!({ "query": query, "name": "stroke", "client_query_id": id }), + None => json!({ "query": query, "name": "stroke" }), + }) .send() .await .map_err(|e| format!("PostHog request failed: {e}"))?; @@ -392,6 +440,42 @@ pub async fn get_ddl(config: &PosthogConfig, table: &str) -> Result(); + tokio::spawn(async move { + let mut held = Vec::new(); + loop { + let (mut s, _) = l.accept().await.unwrap(); + let mut buf = vec![0u8; 16384]; + let n = s.read(&mut buf).await.unwrap(); + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let _ = seen_tx.send(req.clone()); + if req.starts_with("DELETE") { + s.write_all(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n").await.unwrap(); + } else { + held.push(s); // never answered: a long query + } + } + }); + let cfg = PosthogConfig { name: "t".into(), host: format!("http://127.0.0.1:{port}"), project_id: "7".into(), api_key: "k".into() }; + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = crate::db::stop::Stop::from_rx(rx); + tokio::spawn(async move { tokio::time::sleep(Duration::from_millis(300)).await; let _ = tx.send(()); }); + let e = query_cancellable(&cfg, "SELECT count() FROM events", &stop).await.unwrap_err(); + assert_eq!(e, crate::db::query::QUERY_CANCELLED); + let post = seen_rx.recv().await.unwrap(); + assert!(post.starts_with("POST /api/projects/7/query/"), "{post}"); + let id = post.split("\"client_query_id\":\"").nth(1).and_then(|r| r.split('"').next()).expect("client_query_id sent").to_string(); + let del = seen_rx.recv().await.unwrap(); + assert!(del.starts_with(&format!("DELETE /api/projects/7/query/{id}/")), "{del}"); + } + #[test] fn hogql_response_maps_columns_types_and_rows() { let body = json!({ diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index 3edeb457..b5c6c821 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -230,6 +230,18 @@ pub async fn prefetch_primary_keys(pool: &sqlx::PgPool, schema: &str, tables: &[ /// at once (and re-read behind the page once past `PRIMARY_KEY_TTL`; a table /// open re-reads it anyway in its metadata tasks). A miss leaves the page in /// the engine's order and caches the key for the next page. +/// Offsets from here on take the primary-key skip (see get_table_rows): below +/// it OFFSET is cheap enough that the subquery is not worth it. +const DEEP_OFFSET_SKIP: i64 = 20_000; + +/// The cached primary key for a table, without waiting on the catalog. +fn cached_primary_key(pool: &sqlx::PgPool, schema: &str, table: &str) -> Option> { + let key = pool_table_key(pool, schema, table); + let cache = PRIMARY_KEY_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())); + let map = cache.lock().ok()?; + map.get(&key).filter(|(at, _)| at.elapsed() < PRIMARY_KEY_TRUST).map(|(_, pk)| pk.clone()) +} + fn pk_order_nowait(pool: &sqlx::PgPool, schema: &str, table: &str, refresh: bool, order_by: String) -> (String, bool) { let key = pool_table_key(pool, schema, table); let cache = PRIMARY_KEY_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())); @@ -380,16 +392,28 @@ pub struct SqlResult { pub sql: String, } -pub(crate) fn pg_type_label(type_name: &str) -> String { - let name = type_name; - match name { - "VARCHAR" | "CHAR" | "BPCHAR" => { - format!("{}(...)", name.to_lowercase()) - } - _ => name.to_lowercase(), +/// A result column's type as the grid shows it. A result carries no length, so +/// `varchar` stays `varchar`: it used to read `varchar(...)`, which the header +/// font draws as a ligature that looks like `varchar(.)`. +/// A statement's result columns without running it again: what an empty +/// result reports, since the columns are otherwise read off its first row. +/// Empty when the statement can't be described. +async fn pg_describe_columns(conn: &mut sqlx::PgConnection, sql: &str) -> Vec { + use sqlx::{Column, TypeInfo}; + match sqlx::Executor::describe(conn, sql).await { + Ok(d) => d + .columns() + .iter() + .map(|c| ColumnInfo::new(c.name(), pg_type_label(c.type_info().name()))) + .collect(), + Err(_) => Vec::new(), } } +pub(crate) fn pg_type_label(type_name: &str) -> String { + type_name.to_lowercase() +} + /// Render a Postgres interval the way Postgres does: "1 year 2 mons 3 days 04:05:06". /// Units are kept separate rather than normalised into seconds because months and /// days are not fixed-length - collapsing them would change the value's meaning. @@ -1467,6 +1491,10 @@ fn build_plain_search( fn ensure_column(column: &str, allowed: &[String]) -> Result<(), String> { if allowed.iter().any(|c| c == column) { Ok(()) + } else if allowed.is_empty() { + // No columns at all: the table itself is gone (dropped or renamed since + // it was listed). "Unknown column: id" sent people looking at the column. + Err("This table no longer exists. It may have been dropped or renamed; refresh the table list.".to_string()) } else { Err(format!("Unknown column: {column}")) } @@ -1832,7 +1860,7 @@ pub(super) fn build_where_typed( } /// One key of a multi-column sort. Serialized camelCase from the frontend. -#[derive(Debug, serde::Deserialize)] +#[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct SortSpec { pub column: String, @@ -1906,6 +1934,167 @@ fn short_page_total(rows: &Result, sqlx::Error>, keyset: bool, limit: (!keyset && n < limit && (n > 0 || offset == 0)).then_some(offset + n) } +/// Which grid view a row fetch belongs to: the tab, and the load it is part of +/// (each new load of a tab - another page size, sort, filter or table - has a +/// higher number; the windows of one load share it). +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FetchTag { + pub group: String, + pub generation: u64, +} + +/// Row fetches in flight, by tab, so a newer load of the tab stops the older +/// ones on the server. The grid already ignored a superseded fetch's rows, but +/// the query ran on: a table of half-megabyte rows queued page after page +/// behind the one wanted, holding connections and the link, and the grid sat +/// on skeletons. Changing the page size mid-load now cancels what it replaces. +struct RowFetches { + /// group -> (newest generation seen, fetches running). + running: std::sync::Mutex)>>, +} + +struct RunningFetch { + generation: u64, + pid: u32, + /// Fired when a newer load supersedes this fetch: it drops its connection. + stop: Option>, +} + +static ROW_FETCHES: std::sync::LazyLock = + std::sync::LazyLock::new(|| RowFetches { running: std::sync::Mutex::new(HashMap::new()) }); + +impl RowFetches { + /// Register a fetch. None when a newer load of its tab has already started: + /// the caller then skips the query. Older fetches of the group are stopped. + fn begin(&self, pool: &sqlx::PgPool, tag: &FetchTag, pid: u32) -> Option> { + let (tx, rx) = tokio::sync::oneshot::channel(); + let mut stale: Vec = Vec::new(); + { + let Ok(mut map) = self.running.lock() else { return Some(rx) }; + if map.len() > 512 { + map.retain(|_, (_, list)| !list.is_empty()); + } + let entry = map.entry(tag.group.clone()).or_insert((0, Vec::new())); + if tag.generation < entry.0 { + return None; + } + if tag.generation > entry.0 { + entry.0 = tag.generation; + entry.1.retain_mut(|f| { + if f.generation < tag.generation { + if let Some(stop) = f.stop.take() { + let _ = stop.send(()); + } + stale.push(f.pid); + false + } else { + true + } + }); + } + entry.1.push(RunningFetch { generation: tag.generation, pid, stop: Some(tx) }); + } + for pid in stale { + let pool = pool.clone(); + // Only a query of this user on this database that is still running: + // behind a pooler the startup pid is the pooler's, and this must not + // reach anyone else's backend if it happens to share the number. + tokio::spawn(async move { + let _ = sqlx::query( + "SELECT pg_cancel_backend(pid) FROM pg_stat_activity \ + WHERE pid = $1 AND usename = current_user AND datname = current_database() AND state = 'active'", + ) + .bind(pid as i32) + .execute(&pool) + .await; + }); + } + Some(rx) + } + + fn end(&self, tag: &FetchTag, pid: u32) { + if let Ok(mut map) = self.running.lock() { + if let Some((_, list)) = map.get_mut(&tag.group) { + if let Some(i) = list.iter().position(|f| f.generation == tag.generation && f.pid == pid) { + list.swap_remove(i); + } + } + } + } +} + +/// The page query, stoppable by a newer load of the same tab when tagged. +/// +/// Stopping is two things. `pg_cancel_backend` ends the statement, but what the +/// server has already written sits in socket buffers, and handing the +/// connection back to the pool drains it first: on a 3 Mbit link a cancelled +/// load still delivered ~10 s of rows ahead of the page that replaced it. So +/// the superseded fetch also drops its connection, which closes the socket and +/// stops the server sending. The pid comes from the startup message, so +/// tagging costs no round trip. +async fn fetch_page( + pool: &sqlx::PgPool, + query: sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>, + tag: Option<&FetchTag>, +) -> Result, sqlx::Error> { + let Some(tag) = tag else { return query.fetch_all(pool).await }; + let mut conn = pool.acquire().await?; + let pid = conn.backend_process_id(); + let Some(stop) = ROW_FETCHES.begin(pool, tag, pid) else { + return Err(sqlx::Error::Protocol(SUPERSEDED_FETCH.into())); + }; + let res = tokio::select! { + r = query.fetch_all(&mut *conn) => Some(r), + Ok(()) = stop => None, + }; + ROW_FETCHES.end(tag, pid); + match res { + Some(r) => r, + None => { + // Out of the pool and dropped: the socket closes, nothing drains. + discard_connection(pid); + drop(conn.detach()); + Err(sqlx::Error::Protocol(SUPERSEDED_FETCH.into())) + } + } +} + +/// Backends whose connection must be closed, not reused, when the pool gets it +/// back: a stopped run or a superseded fetch. Returned as usual, sqlx pings the +/// connection first, which reads the rest of the abandoned result off the +/// socket: megabytes on a large `SELECT *`, at the speed of the link, ahead of +/// whatever runs next (connection.rs `after_release` checks this set). +static DISCARD: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new())); + +/// Resolves once `flag` is raised (Stop). Polled every 50ms: cheap beside a +/// network read, and the stream it races is what does the work. +async fn wait_cancelled(flag: &AtomicBool) { + while !flag.load(Ordering::Relaxed) { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } +} + +/// Close this backend's connection when it is released instead of reusing it. +pub(crate) fn discard_connection(pid: u32) { + if let Ok(mut set) = DISCARD.lock() { + if set.len() > 4096 { + set.clear(); + } + set.insert(pid); + } +} + +/// True (once) when the connection was marked to be closed on release. +pub(crate) fn take_discard(pid: u32) -> bool { + DISCARD.lock().map(|mut set| set.remove(&pid)).unwrap_or(false) +} + +/// What a fetch replaced by a newer load of its tab reports. Nobody reads it: +/// the grid drops a superseded fetch's result, error or rows. +pub const SUPERSEDED_FETCH: &str = "Superseded by a newer load of this table"; + fn bind_page<'q>( sql: &'q str, where_binds: &'q [String], @@ -1933,7 +2122,7 @@ pub(crate) fn raw_filter_dialect(conn: &ActiveConnection) -> super::sql_util::Ra ActiveConnection::Sqlite(_) | ActiveConnection::D1(_) | ActiveConnection::LibSql(_) => D::Sqlite, ActiveConnection::Duckdb(_) => D::Duckdb, ActiveConnection::Oracle(_) => D::Oracle, - ActiveConnection::Mssql(_) | ActiveConnection::Clickhouse(_) | ActiveConnection::Posthog(_) | ActiveConnection::Redis(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => D::Literal, + ActiveConnection::Mssql(_) | ActiveConnection::Clickhouse(_) | ActiveConnection::Posthog(_) | ActiveConnection::Redis(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => D::Literal, } } @@ -1998,6 +2187,9 @@ pub async fn get_table_rows( // were measured, kept behind a setting for anyone who wants every value on // the page whatever it costs. preview_wide: bool, + // The grid view this fetch is for (Postgres): a newer load of the same tab + // cancels it on the server. None = not cancellable (mirror, one-offs). + fetch_tag: Option, ) -> Result { if limit > MAX_PAGE_LIMIT { return Err(format!("Limit {limit} exceeds the maximum of {MAX_PAGE_LIMIT} rows per page")); @@ -2035,6 +2227,18 @@ pub async fn get_table_rows( ActiveConnection::Posthog(cfg) => { return super::posthog::get_table_rows(&cfg, &table, limit, offset, search, sort_column, sort_direction, filters).await; } + ActiveConnection::Spanner(h) => { + return super::spanner::get_table_rows(&h, &schema, &table, limit, offset, search, sort_column, sort_direction, filters).await; + } + ActiveConnection::Bigquery(h) => { + return super::bigquery::get_table_rows(&h, &schema, &table, limit, offset, search, sort_column, sort_direction, filters).await; + } + ActiveConnection::Snowflake(h) => { + return super::snowflake::get_table_rows(&h, &schema, &table, limit, offset, search, sort_column, sort_direction, filters).await; + } + ActiveConnection::Odbc(h) => { + return super::odbc::get_table_rows(&h, &schema, &table, limit, offset, search, sort_column, sort_direction, filters).await; + } ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => { return Err("DynamoDB tables open in the DynamoDB page".into()); } @@ -2175,11 +2379,38 @@ pub async fn get_table_rows( } let limit_param = where_clause.binds.len() + 1; let offset_param = where_clause.binds.len() + 2; - data_tail = format!( - "FROM {table_ref}{}{} LIMIT ${limit_param} OFFSET ${offset_param}", - where_clause.sql, - order_by - ); + // A deep page ordered by a single-column primary key skips ahead on the + // key's index alone: `pk >= (the pk at row N)`. Plain OFFSET reads and + // throws away N whole rows first; row 990,000 of a 1M-row table took + // 187 ms that way and 71 ms this way, and the rows are the same ones + // (a unique, non-null key makes the boundary exact). Anything else - + // shallow pages, other orders, composite keys - keeps OFFSET. + let skip_key = (offset >= DEEP_OFFSET_SKIP && sorted.len() == 1) + .then(|| cached_primary_key(&pool, &schema, &table)) + .flatten() + .filter(|pk| pk.len() == 1 && pk[0] == sorted[0]) + .map(|pk| pk[0].clone()); + data_tail = match skip_key { + Some(key) => { + let col = quoted_column(&key)?; + let desc = sorts + .first() + .and_then(|s| s.direction.as_deref()) + .or(sort_direction.as_deref()) + .is_some_and(|d| d.eq_ignore_ascii_case("desc")); + let (op, dir) = if desc { ("<=", "DESC") } else { (">=", "ASC") }; + let connector = if where_clause.sql.is_empty() { " WHERE" } else { " AND" }; + format!( + "FROM {table_ref}{w}{connector} {col} {op} (SELECT {col} FROM {table_ref}{w} ORDER BY {col} {dir} OFFSET ${offset_param} LIMIT 1){order_by} LIMIT ${limit_param}", + w = where_clause.sql, + ) + } + None => format!( + "FROM {table_ref}{}{} LIMIT ${limit_param} OFFSET ${offset_param}", + where_clause.sql, + order_by + ), + }; } // ── Wide columns ship as a preview, not a value ───────────────────────── // A `jsonb` column holding an uploaded file averages half a megabyte a row, @@ -2246,7 +2477,7 @@ pub async fn get_table_rows( // Non-blocking mode: fetch only the page of rows and defer the count. // total = -1 signals "unknown / counting" to the UI (same sentinel the // sidebar already uses); the frontend fills it in via count_table_rows. - rows_res = data_query.fetch_all(&pool).await; + rows_res = fetch_page(&pool, data_query, fetch_tag.as_ref()).await; // Unless the page came back short: then it has reached the end of the // matching rows and counted them itself, and the frontend has no count // left to ask for. @@ -2256,7 +2487,7 @@ pub async fn get_table_rows( // planner estimate adds no extra round-trip in series. let estimate_query = sqlx::query_scalar::<_, i64>(ROW_ESTIMATE_SQL).bind(&table_ref); let (estimate_res, page_res) = - tokio::join!(estimate_query.fetch_optional(&pool), data_query.fetch_all(&pool)); + tokio::join!(estimate_query.fetch_optional(&pool), fetch_page(&pool, data_query, fetch_tag.as_ref())); rows_res = page_res; let estimate = estimate_res.ok().flatten(); // A page that came back short ends the table, so it has already counted @@ -2274,7 +2505,7 @@ pub async fn get_table_rows( // COUNT and data SELECT are independent - run both in parallel. let (total_result, page_res) = tokio::join!( count_query.fetch_one(&pool), - data_query.fetch_all(&pool), + fetch_page(&pool, data_query, fetch_tag.as_ref()), ); total = total_result.map_err(|e| format!("Failed to count rows: {e}"))?; rows_res = page_res; @@ -2713,6 +2944,18 @@ pub async fn update_table_cell( return Err("Inline row editing is not supported for ClickHouse (OLAP). Use ALTER TABLE … UPDATE in the SQL console.".into()); } ActiveConnection::Posthog(_) => return Err("PostHog is read-only: its data comes from HogQL queries.".into()), + ActiveConnection::Spanner(h) => { + return super::spanner::update_table_cell(&h, &schema, &table, primary_key, &column, &value).await; + } + ActiveConnection::Bigquery(h) => { + return super::bigquery::update_table_cell(&h, &schema, &table, primary_key, &column, &value).await; + } + ActiveConnection::Snowflake(h) => { + return super::snowflake::update_table_cell(&h, &schema, &table, primary_key, &column, &value).await; + } + ActiveConnection::Odbc(h) => { + return super::odbc::update_table_cell(&h, &schema, &table, primary_key, &column, &value).await; + } ActiveConnection::Redis(_) => { return Err("Editing is not supported on Redis".into()); } @@ -2938,6 +3181,22 @@ pub async fn insert_table_row( return Err("Row insertion via the grid is not supported for ClickHouse. Use INSERT INTO … in the SQL console.".into()); } ActiveConnection::Posthog(_) => return Err("PostHog is read-only: its data comes from HogQL queries.".into()), + ActiveConnection::Spanner(h) => { + let row = super::spanner::insert_table_row(&h, &schema, &table, values).await?; + return Ok(InsertRowResult { row }); + } + ActiveConnection::Bigquery(h) => { + let row = super::bigquery::insert_table_row(&h, &schema, &table, values).await?; + return Ok(InsertRowResult { row }); + } + ActiveConnection::Snowflake(h) => { + let row = super::snowflake::insert_table_row(&h, &schema, &table, values).await?; + return Ok(InsertRowResult { row }); + } + ActiveConnection::Odbc(h) => { + let row = super::odbc::insert_table_row(&h, &schema, &table, values).await?; + return Ok(InsertRowResult { row }); + } ActiveConnection::Redis(_) => { return Err("Editing is not supported on Redis".into()); } @@ -3069,6 +3328,18 @@ pub async fn delete_table_rows( return Err("Row deletion via the grid is not supported for ClickHouse. Use ALTER TABLE … DELETE in the SQL console.".into()); } ActiveConnection::Posthog(_) => return Err("PostHog is read-only: its data comes from HogQL queries.".into()), + ActiveConnection::Spanner(h) => { + return super::spanner::delete_table_rows(&h, &schema, &table, primary_keys).await; + } + ActiveConnection::Bigquery(h) => { + return super::bigquery::delete_table_rows(&h, &schema, &table, primary_keys).await; + } + ActiveConnection::Snowflake(h) => { + return super::snowflake::delete_table_rows(&h, &schema, &table, primary_keys).await; + } + ActiveConnection::Odbc(h) => { + return super::odbc::delete_table_rows(&h, &schema, &table, primary_keys).await; + } ActiveConnection::Redis(_) => { return Err("Editing is not supported on Redis".into()); } @@ -3532,6 +3803,7 @@ pub async fn execute_sql( return Err("Query is empty".into()); } let conn = require_conn(&state)?; + let tunnel = super::ssh_tunnel::RunWatch::start(); let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); // Keyed by the caller's id so several editor tabs can run at once and each // one's Cancel reaches its own query. @@ -3547,45 +3819,13 @@ pub async fn execute_sql( // when the receiver fires. ActiveConnection::Postgres(pool) => execute_sql_pg(&pool, &sql_str, Some(cancel_rx)).await, ActiveConnection::Mysql(pool) => super::mysql::execute_sql(&pool, &sql_str, Some(cancel_rx)).await, - // Oracle interrupts the running call (OCIBreak); it then fails with - // ORA-01013, reported as a cancel. - ActiveConnection::Oracle(h) => { - let run = super::oracle::execute_sql(&h, &sql_str); - tokio::pin!(run); - tokio::select! { - r = &mut run => r, - _ = async { let _ = cancel_rx.await; } => { - super::oracle::cancel(&h).await; - let _ = run.await; - Err(QUERY_CANCELLED.to_string()) - } - } - } - // Engines without a server-side cancel primitive: abandon the future when - // cancelled so the UI unblocks (the statement then finishes or times out - // server-side). This preserves the previous behavior for these engines. - other => tokio::select! { - r = async move { - match other { - ActiveConnection::Sqlite(pool) => super::sqlite::execute_sql(&pool, &sql_str).await, - ActiveConnection::D1(cfg) => super::d1::query(&cfg, &sql_str, vec![]).await, - ActiveConnection::LibSql(cfg) => super::libsql::query(&cfg, &sql_str, vec![]).await, - ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(&cfg, &sql_str).await, - ActiveConnection::Posthog(cfg) => super::posthog::query(&cfg, &sql_str).await, - ActiveConnection::Redis(cfg) => super::redis::query(&cfg, &sql_str).await, - ActiveConnection::Dynamodb(cfg) => super::dynamodb::query(&cfg, &sql_str).await, - ActiveConnection::Doc(d) => super::docdb::query(&d, &sql_str).await, - ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(&h, &sql_str).await, - ActiveConnection::Mssql(h) => super::mssql::execute_sql(&h, &sql_str).await, - ActiveConnection::Postgres(_) | ActiveConnection::Mysql(_) | ActiveConnection::Oracle(_) => unreachable!(), - } - } => r, - _ = async { let _ = cancel_rx.await; } => Err(QUERY_CANCELLED.to_string()), - }, + // Everything else stops through its own driver (see run_one_cancellable). + other => run_one_cancellable(&other, &sql_str, &super::stop::Stop::from_rx(cancel_rx)).await, }; super::connection::unregister_cancel(&state, &cancel_key); - if let Ok(r) = &mut result { - r.sql = sql_out; + match &mut result { + Ok(r) => r.sql = sql_out, + Err(e) => *e = tunnel.explain(std::mem::take(e), !is_row_returning_sql(&sql_out)), } result } @@ -3597,6 +3837,8 @@ pub async fn execute_sql_on_conn( config: super::connection::AnyConnectionConfig, sql: &str, ) -> Result { + // Its own connection, through the saved connection's SSH tunnel if any. + let (config, _tunnel) = super::connection::tunnel_any(config).await?; use super::connection::{open_mysql, open_pg, open_sqlite, AnyConnectionConfig}; let sql = sql.trim(); if sql.is_empty() { @@ -3654,6 +3896,36 @@ pub async fn execute_sql_on_conn( /// only as a last-resort circuit breaker whose "add a LIMIT" message tells the /// user what happened. const EXECUTE_SQL_MAX_ROWS: usize = 1_000_000_000; + +/// How much a result collected in memory may hold, as JSON. The SQL console +/// streams to disk and has no limit (RowSink); this guards every caller that +/// still gets its rows in one reply (the MCP server, the AI chat, exports of +/// a single statement), where a 2 GB result meant several GB in the backend, +/// a JSON string as large again, and the window's heap after that. A row cap +/// of a billion guarded nothing. +pub(crate) const COLLECT_BYTE_BUDGET: usize = 512 << 20; + +/// Counts a collected result against COLLECT_BYTE_BUDGET. +#[derive(Default)] +pub(crate) struct CollectBudget { + bytes: usize, +} + +impl CollectBudget { + /// Add a row; false once the result is over budget (stop reading). + pub(crate) fn take(&mut self, row: &[Value]) -> bool { + self.bytes += row.iter().map(approx_json_len).sum::() + row.len() + 1; + self.bytes < COLLECT_BYTE_BUDGET + } +} + +/// What a result cut short by the budget says, in place of its rows' end. +pub(crate) fn budget_message(rows: usize) -> String { + format!( + "Stopped after {rows} rows: the result passed {} MB, more than is safe to hold in memory here. The SQL console streams results of any size; elsewhere, add a LIMIT.", + COLLECT_BYTE_BUDGET >> 20 + ) +} /// Statement timeout for ad-hoc queries (milliseconds). Generous enough for /// heavier scans (e.g. tables with large TOASTed JSON columns) to finish. pub(crate) const EXECUTE_SQL_TIMEOUT_MS: i64 = 60_000; @@ -3662,8 +3934,14 @@ pub(crate) const EXECUTE_SQL_TIMEOUT_MS: i64 = 60_000; /// as stopped rather than failed. pub(crate) const QUERY_CANCELLED: &str = "Query cancelled"; +/// What a stopped run reports on an engine with no way to stop a statement +/// (HTTP engines, document stores). Starts like QUERY_CANCELLED so the window +/// shows it as stopped, then says the part that matters. +pub(crate) const QUERY_ABANDONED: &str = + "Query cancelled here, but this database has no way to stop a running statement, so the server may still finish it."; + /// Where Stop finds a run's backend. -enum CancelTarget { +pub(crate) enum CancelTarget { /// The run's own `application_name`, set in its BEGIN batch. Tag(String), /// A server that refused the tag: the backend pid, asked for up front. @@ -3672,7 +3950,7 @@ enum CancelTarget { /// An `application_name` no other run has, in this app or in another one on /// the same database. Well under Postgres's 63-byte limit. -fn run_tag() -> String { +pub(crate) fn run_tag() -> String { static SEQ: AtomicU64 = AtomicU64::new(0); let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -3687,7 +3965,7 @@ fn run_tag() -> String { /// five round trips before the user's SQL was even sent. Measured at a 100ms /// round trip (`console_run_live`): `SELECT 1` took 8 round trips, now 4; a /// repeat took 5, now 3. A retry passes the same tag, so Stop still reaches it. -async fn begin_console_tx( +pub(crate) async fn begin_console_tx( pool: &sqlx::PgPool, tag: &str, ) -> Result<(sqlx::Transaction<'static, Postgres>, CancelTarget), String> { @@ -3728,7 +4006,7 @@ async fn begin_console_tx( /// also exact: the tag ends with the transaction, so a late Stop matches nothing /// instead of whatever that connection runs next. If the run finishes first the /// sender is dropped, `rx.await` errors and the watcher exits. -fn arm_pg_cancel( +pub(crate) fn arm_pg_cancel( pool: &sqlx::PgPool, rx: Option>, cancelled: Arc, @@ -3740,6 +4018,7 @@ fn arm_pg_cancel( if rx.await.is_err() { return; } + log::info!("console run: stop received"); cancelled.store(true, Ordering::Relaxed); let cancel = match target { CancelTarget::Tag(tag) => { @@ -3839,7 +4118,7 @@ impl RowSink { } /// A result starts (again, after a retry): its columns go with the first message. - fn start(&mut self, columns: Vec) -> Result<(), String> { + pub(crate) fn start(&mut self, columns: Vec) -> Result<(), String> { if let Some(spool) = self.spool.as_mut() { spool.start(columns.clone())?; } @@ -3854,7 +4133,7 @@ impl RowSink { Ok(()) } - fn push(&mut self, row: Vec) -> Result<(), String> { + pub(crate) fn push(&mut self, row: Vec) -> Result<(), String> { match self.spool.as_mut() { Some(spool) => { self.bytes += spool.push(&row)?; @@ -3915,7 +4194,7 @@ impl RowSink { } /// Roughly how many bytes a cell takes as JSON: enough to size a chunk. -fn approx_json_len(v: &Value) -> usize { +pub(crate) fn approx_json_len(v: &Value) -> usize { match v { Value::Null => 4, Value::Bool(_) => 5, @@ -4011,6 +4290,7 @@ async fn run_sql_pg( let tag = run_tag(); let (mut tx, target) = begin_console_tx(pool, &tag).await?; + let run_pid = tx.backend_process_id(); log::info!("console run: transaction open after {}ms", query_ms()); arm_pg_cancel(pool, cancel_rx, cancelled.clone(), target); @@ -4036,9 +4316,21 @@ async fn run_sql_pg( let mut stream = sqlx::query(&executed).fetch(&mut *tx); let mut failure: Option<(String, Option)> = None; loop { - match stream.try_next().await { + // Stop does not wait for the row in flight: one jsonb value + // measured 17MB, fourteen seconds on a 10 Mbit link, and + // checking only between rows made Stop take that long. + let next = tokio::select! { + r = stream.try_next() => r, + _ = wait_cancelled(&cancelled) => { + log::info!("console run: stopped after {}ms", query_ms()); + discard_connection(run_pid); + return Err(QUERY_CANCELLED.into()); + } + }; + match next { Ok(Some(row)) => { if cancelled.load(Ordering::Relaxed) { + discard_connection(run_pid); return Err(QUERY_CANCELLED.into()); } if total == 0 { @@ -4111,6 +4403,23 @@ async fn run_sql_pg( capped = false; tx = begin_console_tx(pool, &tag).await?.0; } + // No row, so no row to read the columns off: an empty SELECT came + // back with none, and the results pane showed "Run a query" with no + // headers right after a run. Describing the statement gets them + // without running it again. + if total == 0 && columns.is_empty() { + columns = pg_describe_columns(&mut tx, &executed).await; + { + if let Some(sink) = sink.as_deref_mut() { + if !columns.is_empty() { + if let Err(e) = sink.start(columns.clone()) { + let _ = tx.rollback().await; + return Err(e.into()); + } + } + } + } + } // COMMIT, not ROLLBACK. "Ends in a SELECT" does not mean "read-only": // `UPDATE …; SELECT …`, a data-modifying CTE (`WITH d AS (DELETE … // RETURNING *) SELECT …`) and `SELECT nextval(…)` all write, and a @@ -4156,7 +4465,7 @@ async fn run_sql_pg( columns: vec![], rows: vec![], row_count: Some(affected), - message: Some(format!("{affected} row(s) affected")), + message: Some(affected_message(stmt, affected)), query_ms: query_ms(), sql: stmt.to_string(), }); @@ -4395,6 +4704,7 @@ async fn run_sql_multi_pg( ) -> Result, String> { let tag = run_tag(); let (mut tx, target) = begin_console_tx(pool, &tag).await?; + let run_pid = tx.backend_process_id(); arm_pg_cancel(pool, cancel_rx, cancelled.clone(), target); let mut results: Vec = Vec::new(); @@ -4412,9 +4722,18 @@ async fn run_sql_multi_pg( let mut capped = false; loop { - match stream.try_next().await { + // As in run_sql_pg: Stop does not wait for the row in flight. + let next = tokio::select! { + r = stream.try_next() => r, + _ = wait_cancelled(&cancelled) => { + discard_connection(run_pid); + return Err(QUERY_CANCELLED.into()); + } + }; + match next { Ok(Some(row)) => { if cancelled.load(Ordering::Relaxed) { + discard_connection(run_pid); return Err(QUERY_CANCELLED.into()); } if data.is_empty() { @@ -4439,6 +4758,10 @@ async fn run_sql_multi_pg( } } drop(stream); + // An empty result has no row to read the columns off. + if columns.is_empty() { + columns = pg_describe_columns(&mut tx, stmt).await; + } let row_count = data.len() as i64; results.push(SqlResult { @@ -4461,7 +4784,7 @@ async fn run_sql_multi_pg( columns: vec![], rows: vec![], row_count: Some(affected), - message: Some(format!("{affected} row(s) affected")), + message: Some(affected_message(stmt, affected)), query_ms: stmt_ms(), sql: stmt.clone(), }); @@ -4482,6 +4805,16 @@ pub async fn execute_sql_multi( state: Db<'_>, sql: String, query_id: Option, +) -> Result, String> { + let tunnel = super::ssh_tunnel::RunWatch::start(); + let writes = split_sql_statements(&sql).iter().any(|s| !s.trim().is_empty() && !is_row_returning_sql(s)); + execute_sql_multi_run(state, sql, query_id).await.map_err(|e| tunnel.explain(e, writes)) +} + +async fn execute_sql_multi_run( + state: Db<'_>, + sql: String, + query_id: Option, ) -> Result, String> { let sql_str = sql.trim().to_string(); if sql_str.is_empty() { @@ -4505,36 +4838,30 @@ pub async fn execute_sql_multi( super::connection::unregister_cancel(&state, &cancel_key); return result; } - // Oracle's blocking call outlives the dropped future; interrupt it too. - let oracle_h = match &conn { - ActiveConnection::Oracle(h) => Some(h.clone()), - _ => None, - }; - let result = tokio::select! { - r = async move { - // Other engines: execute sequentially, one result set per statement. - // Cancellation happens at the outer select! (the future is dropped), - // so per-statement executors get no cancel receiver - same as the - // other diff/multi callers. - let multi = stmts.len() > 1; - let mut results: Vec = Vec::with_capacity(stmts.len()); - for (idx, stmt) in stmts.iter().enumerate() { - let r = run_one_other(&conn, stmt).await; - match r { - Ok(res) => results.push(res), - Err(e) if multi => return Err(format!("Statement {} failed: {e}", idx + 1)), - Err(e) => return Err(e), - } + // Other engines: execute sequentially, one result set per statement, each + // stoppable on the server (run_one_cancellable). + let stop = super::stop::Stop::from_rx(cancel_rx); + let multi = stmts.len() > 1; + let mut results: Vec = Vec::with_capacity(stmts.len()); + let mut result = Ok(()); + for (idx, stmt) in stmts.iter().enumerate() { + match run_one_cancellable(&conn, stmt, &stop).await { + Ok(res) => results.push(res), + Err(e) if e.starts_with(QUERY_CANCELLED) => { + result = Err(e); + break; } - Ok(results) - } => r, - _ = async { let _ = cancel_rx.await; } => { - if let Some(h) = &oracle_h { - super::oracle::cancel(h).await; + Err(e) if multi => { + result = Err(format!("Statement {} failed: {e}", idx + 1)); + break; + } + Err(e) => { + result = Err(e); + break; } - Err(QUERY_CANCELLED.to_string()) } - }; + } + let result = result.map(|()| results); super::connection::unregister_cancel(&state, &cancel_key); result } @@ -4549,6 +4876,10 @@ async fn run_one_other(conn: &ActiveConnection, stmt: &str) -> Result super::mysql::execute_sql(pool, stmt, None).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(cfg, stmt).await, ActiveConnection::Posthog(cfg) => super::posthog::query(cfg, stmt).await, + ActiveConnection::Spanner(h) => super::spanner::query(h, stmt).await, + ActiveConnection::Bigquery(h) => super::bigquery::query(h, stmt).await, + ActiveConnection::Snowflake(h) => super::snowflake::query(h, stmt).await, + ActiveConnection::Odbc(h) => super::odbc::query(h, stmt).await, ActiveConnection::Redis(cfg) => super::redis::query(cfg, stmt).await, ActiveConnection::Dynamodb(cfg) => super::dynamodb::query(cfg, stmt).await, ActiveConnection::Doc(d) => super::docdb::query(d, stmt).await, @@ -4558,6 +4889,128 @@ async fn run_one_other(conn: &ActiveConnection, stmt: &str) -> Result Result { + if stop.fired() { + return Err(QUERY_CANCELLED.into()); + } + match conn { + ActiveConnection::Postgres(_) => unreachable!("Postgres runs through its own path"), + // KILL QUERY on the statement's connection id. + ActiveConnection::Mysql(pool) => super::mysql::execute_sql(pool, stmt, Some(stop.receiver())).await, + // sqlite3_interrupt / DuckDB's InterruptHandle on the running connection. + ActiveConnection::Sqlite(pool) => super::sqlite::execute_sql_cancellable(pool, stmt, stop.receiver()).await, + ActiveConnection::Duckdb(h) => super::duckdb::execute_sql_cancellable(h, stmt, stop.receiver()).await, + // KILL QUERY WHERE query_id. + ActiveConnection::Clickhouse(cfg) => super::clickhouse::query_cancellable(cfg, stmt, stop.receiver()).await, + // OCIBreak; the call then fails with ORA-01013. + ActiveConnection::Oracle(h) => { + let run = super::oracle::execute_sql(h, stmt); + tokio::pin!(run); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + super::oracle::cancel(h).await; + let _ = run.await; + Err(QUERY_CANCELLED.to_string()) + } + } + } + // KILL the session from a second connection, then a fresh client: + // the dropped reply would otherwise be read by the next query. + ActiveConnection::Mssql(h) => { + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(super::mssql::execute_sql(h, stmt)); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + super::mssql::cancel(h).await; + // The killed batch fails at once; give it a moment, then + // let go of the client either way. + let finished = tokio::time::timeout(std::time::Duration::from_secs(5), &mut run).await; + if let Ok(Ok(r)) = finished { + // It completed before the KILL landed: that is the result. + return Ok(r); + } + drop(run); + match super::mssql::reset(h).await { + Ok(()) => Err(QUERY_CANCELLED.to_string()), + Err(e) => Err(format!("{QUERY_CANCELLED}. Reopening the connection afterwards failed: {e}")), + } + } + } + } + // Cancel by client_query_id / X-Opaque-Id on the server. + ActiveConnection::Posthog(cfg) => super::posthog::query_cancellable(cfg, stmt, stop).await, + ActiveConnection::Doc(super::docdb::DocConn::Elastic(cfg)) => super::elastic::query_cancellable(cfg, stmt, stop).await, + // jobs.cancel on the query's job. + ActiveConnection::Bigquery(h) => super::bigquery::query_cancellable(h, stmt, stop).await, + ActiveConnection::Snowflake(h) => super::snowflake::query_cancellable(h, stmt, stop).await, + // SQLCancel on the running statement. + ActiveConnection::Odbc(h) => super::odbc::query_cancellable(h, stmt, stop.receiver()).await, + // No server-side stop exists: stop waiting, and say the server may not. + other => tokio::select! { + r = run_one_other(other, stmt) => r, + _ = stop.wait() => Err(QUERY_ABANDONED.into()), + }, + } +} + +/// Stream one row-returning statement into `sink`, on the engines whose +/// drivers read rows as they arrive. None: this engine or statement doesn't +/// stream, so the caller runs it the ordinary way. +async fn stream_one( + conn: &ActiveConnection, + stmt: &str, + sink: &mut RowSink, + stop: &super::stop::Stop, +) -> Option> { + let reads = is_row_returning_sql(stmt); + Some(match conn { + ActiveConnection::Mysql(pool) if reads => super::mysql::stream_into(pool, stmt, sink, stop.receiver()).await, + ActiveConnection::Sqlite(pool) if reads || super::sql_util::statement_head(stmt) == "pragma" => { + super::sqlite::stream_into(pool, stmt, sink, stop.receiver()).await + } + ActiveConnection::Duckdb(h) if super::duckdb::reads(stmt) => super::duckdb::stream_into(h, stmt, sink, stop.receiver()).await, + ActiveConnection::Mssql(h) if super::mssql::reads(stmt) => { + // Boxed, so `drop(run)` below really ends the future and lets go of + // what it holds (a connection, a stream); a stack pin outlived it. + let mut run = Box::pin(super::mssql::stream_into(h, stmt, sink)); + tokio::select! { + r = &mut run => r, + _ = stop.wait() => { + super::mssql::cancel(h).await; + let finished = tokio::time::timeout(std::time::Duration::from_secs(5), &mut run).await; + if let Ok(Ok(r)) = finished { + return Some(Ok(r)); + } + drop(run); + Err(match super::mssql::reset(h).await { + Ok(()) => QUERY_CANCELLED.to_string(), + Err(e) => format!("{QUERY_CANCELLED}. Reopening the connection afterwards failed: {e}"), + }) + } + } + } + ActiveConnection::Doc(super::docdb::DocConn::Mongo(m)) if super::mongo::streams(stmt) => super::mongo::stream_into(m, stmt, sink, stop).await, + ActiveConnection::Oracle(h) if super::oracle::reads(stmt) => super::oracle::stream_into(h, stmt, sink, stop).await, + ActiveConnection::Clickhouse(cfg) if super::clickhouse::reads(stmt) => super::clickhouse::stream_into(cfg, stmt, sink, stop).await, + ActiveConnection::Bigquery(h) if super::bigquery::reads(stmt) => super::bigquery::stream_into(h, stmt, sink, stop).await, + ActiveConnection::Snowflake(h) if super::snowflake::reads(stmt) => super::snowflake::stream_into(h, stmt, sink, stop).await, + ActiveConnection::Odbc(h) if super::odbc::reads(stmt) => super::odbc::stream_into(h, stmt, sink, stop.receiver()).await, + _ => return None, + }) +} + /// One statement of a console run: its result, or why it failed. #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -4609,14 +5062,23 @@ pub async fn execute_sql_script( return Err("Query is empty".into()); } log::info!("console run: {} statement(s)", stmts.len()); + let tunnel = super::ssh_tunnel::RunWatch::start(); let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); let cancel_key = query_id.unwrap_or_else(|| "default".to_string()); super::connection::register_cancel(&state, &cancel_key, cancel_tx); - let outcomes = match &conn { + let mut outcomes = match &conn { ActiveConnection::Postgres(pool) => run_script_pg(pool, &stmts, cancel_rx, sink).await, - other => run_script_other(other, &stmts, cancel_rx).await, + other => run_script_other(other, &stmts, cancel_rx, sink).await, }; super::connection::unregister_cancel(&state, &cancel_key); + // A script that failed because its tunnel went away: say whether it got + // as far as the server. Any write in the script makes the result unknown. + let writes = stmts.iter().any(|s| !is_row_returning_sql(s)); + for o in &mut outcomes { + if let Some(e) = o.error.take() { + o.error = Some(tunnel.explain(e, writes)); + } + } Ok(outcomes) } @@ -4676,30 +5138,37 @@ async fn run_script_other( conn: &ActiveConnection, stmts: &[String], cancel_rx: tokio::sync::oneshot::Receiver<()>, + sink: Option<&mut RowSink>, ) -> Vec { - // A Mutex for Send; never held across an await. - let out = std::sync::Mutex::new(Vec::with_capacity(stmts.len())); - let run = async { - for stmt in stmts { - let t = std::time::Instant::now(); - let r = run_one_other(conn, stmt).await; + let stop = super::stop::Stop::from_rx(cancel_rx); + // One row-returning statement on an engine with a cursor streams into the + // sink (and the result store), as Postgres does, instead of arriving whole. + if let (Some(sink), [stmt]) = (sink, stmts) { + let t = std::time::Instant::now(); + if let Some(r) = stream_one(conn, stmt, sink, &stop).await { let ms = t.elapsed().as_millis() as u64; - out.lock().unwrap().push(match r { + return vec![match r { Ok(res) => StatementOutcome::ok(res), Err(e) => StatementOutcome::failed(stmt, ms, e.into()), - }); + }]; } - }; - tokio::select! { - _ = run => {} - _ = async { let _ = cancel_rx.await; } => { - if let ActiveConnection::Oracle(h) = conn { - super::oracle::cancel(h).await; + } + let mut out = Vec::with_capacity(stmts.len()); + for stmt in stmts { + let t = std::time::Instant::now(); + let r = run_one_cancellable(conn, stmt, &stop).await; + let ms = t.elapsed().as_millis() as u64; + match r { + Ok(res) => out.push(StatementOutcome::ok(res)), + // Stopped: this statement says so, and nothing after it runs. + Err(e) if stop.fired() && e.starts_with(QUERY_CANCELLED) => { + out.push(StatementOutcome::failed(stmt, ms, e.into())); + break; } - out.lock().unwrap().push(StatementOutcome::failed("", 0, QUERY_CANCELLED.into())); + Err(e) => out.push(StatementOutcome::failed(stmt, ms, e.into())), } } - out.into_inner().unwrap_or_default() + out } // ── D1 / LibSQL helpers (SQLite-over-HTTP) ──────────────────────────────────── @@ -5445,6 +5914,10 @@ async fn dispatch_stats_sql(conn: &ActiveConnection, sql: &str) -> Result super::libsql::query(cfg, sql, vec![]).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(cfg, sql).await, ActiveConnection::Posthog(cfg) => super::posthog::query(cfg, sql).await, + ActiveConnection::Spanner(h) => super::spanner::query(h, sql).await, + ActiveConnection::Bigquery(h) => super::bigquery::query(h, sql).await, + ActiveConnection::Snowflake(h) => super::snowflake::query(h, sql).await, + ActiveConnection::Odbc(h) => super::odbc::query(h, sql).await, ActiveConnection::Redis(_) => Err("Column statistics are not supported on Redis".into()), ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Err("Column statistics are not supported on DynamoDB".into()), ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(h, sql).await, @@ -5467,13 +5940,84 @@ pub async fn ping_connection(state: Db<'_>) -> Result<(), String> { } ActiveConnection::Mysql(pool) => super::connection::keepalive_idle(&pool).await, // HTTP-based: stateless, no persistent TCP connection to validate - ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Clickhouse(_) | ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Ok(()), + ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Clickhouse(_) | ActiveConnection::Redis(_) | ActiveConnection::Posthog(_) | ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) | ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) | ActiveConnection::Odbc(_) => Ok(()), ActiveConnection::Duckdb(h) => super::duckdb::execute_sql(&h, "SELECT 1").await.map(|_| ()), ActiveConnection::Mssql(h) => super::mssql::execute_sql(&h, "SELECT 1").await.map(|_| ()), ActiveConnection::Oracle(h) => super::oracle::ping(&h).await, } } +/// What a write says it did. "1 row affected" / "1,000 rows affected"; for a +/// schema statement that reports no rows (DuckDB's CREATE TABLE AS among +/// them), "Done", since "0 row(s) affected" read as if nothing happened. +pub(crate) fn affected_message(sql: &str, n: i64) -> String { + let first = sql.trim_start().split(|c: char| !c.is_ascii_alphabetic()).next().unwrap_or("").to_ascii_uppercase(); + const SCHEMA: [&str; 16] = ["CREATE", "ALTER", "DROP", "TRUNCATE", "COMMENT", "GRANT", "REVOKE", "RENAME", "ATTACH", "DETACH", "VACUUM", "ANALYZE", "PRAGMA", "SET", "USE", "REINDEX"]; + if n == 0 && SCHEMA.contains(&first.as_str()) { + return "Done".into(); + } + let digits = n.unsigned_abs().to_string(); + let mut grouped = String::new(); + for (i, ch) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i) % 3 == 0 { + grouped.push(','); + } + grouped.push(ch); + } + format!("{grouped} {} affected", if n == 1 { "row" } else { "rows" }) +} + +#[cfg(test)] +mod pg_empty_result_tests { + /// Against Postgres (STROKE_TEST_POSTGIS): a SELECT that matches nothing + /// still names its columns, on the one-statement and the script path. + #[tokio::test] + async fn live_empty_select_keeps_its_columns() { + let Ok(url) = std::env::var("STROKE_TEST_POSTGIS") else { return }; + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + let one = super::execute_sql_pg(&pool, "SELECT 1::int AS n, 'x'::text AS label WHERE false", None).await.unwrap(); + assert!(one.rows.is_empty()); + let names: Vec<_> = one.columns.iter().map(|c| (c.name.as_str(), c.data_type.as_str())).collect(); + assert_eq!(names, [("n", "int4"), ("label", "text")]); + let multi = super::execute_sql_multi_pg(&pool, &["SELECT 1".into(), "SELECT 2::int8 AS big WHERE false".into()], None).await.unwrap(); + assert_eq!(multi[1].columns.iter().map(|c| c.name.as_str()).collect::>(), ["big"]); + } +} + +#[cfg(test)] +mod pg_type_label_tests { + #[test] + fn labels_carry_no_placeholder_length() { + assert_eq!(super::pg_type_label("VARCHAR"), "varchar"); + assert_eq!(super::pg_type_label("BPCHAR"), "bpchar"); + assert_eq!(super::pg_type_label("INT4"), "int4"); + } +} + +#[cfg(test)] +mod ensure_column_tests { + use super::ensure_column; + + #[test] + fn says_when_the_table_is_gone() { + let cols = vec!["id".to_string(), "name".to_string()]; + assert!(ensure_column("id", &cols).is_ok()); + assert_eq!(ensure_column("nope", &cols).unwrap_err(), "Unknown column: nope"); + assert!(ensure_column("id", &[]).unwrap_err().contains("no longer exists")); + } +} + +#[cfg(test)] +mod affected_message_tests { + #[test] + fn says_what_a_write_did() { + assert_eq!(super::affected_message("UPDATE t SET a = 1", 1), "1 row affected"); + assert_eq!(super::affected_message("delete from t", 1234567), "1,234,567 rows affected"); + assert_eq!(super::affected_message(" create table x as select 1", 0), "Done"); + assert_eq!(super::affected_message("INSERT INTO t SELECT 1 WHERE false", 0), "0 rows affected"); + } +} + #[cfg(test)] mod split_sql_tests { use super::split_sql_statements; @@ -5794,7 +6338,7 @@ mod nosql_console_live { #[ignore] async fn nosql_console_live() { // MongoDB - let m = crate::db::mongo::connect(&crate::db::mongo::MongoConfig { name: "t".into(), uri: "mongodb://localhost:27017".into(), database: Some("shop".into()) }).await.unwrap(); + let m = crate::db::mongo::connect(&crate::db::mongo::MongoConfig { ssh: None, name: "t".into(), uri: "mongodb://localhost:27017".into(), database: Some("shop".into()) }).await.unwrap(); let mc = ActiveConnection::Doc(DocConn::Mongo(m)); let r = run(&mc, "db.users.find({}).limit(3)").await; assert_eq!(r.rows.len(), 3); @@ -5812,13 +6356,13 @@ mod nosql_console_live { assert_eq!(r.rows.len(), 3); // Cassandra (CQL) - let s = crate::db::cassandra::connect(&crate::db::cassandra::CassandraConfig { name: "t".into(), hosts: "127.0.0.1".into(), user: None, password: None, keyspace: Some("shop".into()) }).await.unwrap(); + let s = crate::db::cassandra::connect(&crate::db::cassandra::CassandraConfig { ssh: None, name: "t".into(), hosts: "127.0.0.1".into(), user: None, password: None, keyspace: Some("shop".into()) }).await.unwrap(); let cc = ActiveConnection::Doc(DocConn::Cassandra(s)); assert!(!run(&cc, "SELECT * FROM users LIMIT 5").await.rows.is_empty(), "unqualified name uses the keyspace"); assert!(!run(&cc, "SELECT * FROM shop.orders_by_user LIMIT 5").await.columns.is_empty()); // CouchDB (Mango shell syntax) - let couch = ActiveConnection::Doc(DocConn::Couch(crate::db::couchdb::CouchConfig { name: "t".into(), url: "http://localhost:5984".into(), user: Some("admin".into()), password: Some("admin".into()) })); + let couch = ActiveConnection::Doc(DocConn::Couch(crate::db::couchdb::CouchConfig { ssh: None, via: None, name: "t".into(), url: "http://localhost:5984".into(), user: Some("admin".into()), password: Some("admin".into()) })); assert_eq!(run(&couch, r#"products.find({"price": {"$gt": 50}})"#).await.rows.len(), 2); // Firestore (emulator) @@ -5834,7 +6378,7 @@ mod nosql_console_live { assert!(run(&cc, r#"SELECT * FROM "shop"."users" LIMIT 2"#).await.rows.len() <= 2); // Redis - let rc = ActiveConnection::Redis(crate::db::connection::RedisConfig { name: "t".into(), host: "127.0.0.1".into(), port: 6391, password: None, db: 0, tls: false }); + let rc = ActiveConnection::Redis(crate::db::connection::RedisConfig { ssh: None, via: None, name: "t".into(), host: "127.0.0.1".into(), port: 6391, password: None, db: 0, tls: false }); assert!(!run(&rc, "DBSIZE").await.rows.is_empty()); } } @@ -6019,3 +6563,438 @@ pub async fn create_search_index( } Ok(created) } + +/// Big results on engines other than Postgres stream to the result store +/// instead of arriving whole. +#[cfg(test)] +mod stream_tests { + use super::*; + + fn rss_mb() -> u64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| s.lines().find(|l| l.starts_with("VmRSS")).map(|l| l.split_whitespace().nth(1).unwrap_or("0").parse::().unwrap_or(0) / 1024)) + .unwrap_or(0) + } + + fn sink_into(store: &super::super::result_store::ResultStore, id: &str) -> RowSink { + let channel = tauri::ipc::Channel::::new(|_| Ok(())); + RowSink::with_spool(channel, Some(store.create(id).unwrap())) + } + + const N: usize = 2_000_000; + + async fn check(store: &super::super::result_store::ResultStore, id: &str, r: SqlResult, before: u64, limit_mb: u64) { + assert!(r.rows.is_empty(), "rows went to the store, not the reply"); + assert_eq!(r.row_count, Some(N as i64)); + let stored = store.get(id).unwrap(); + assert_eq!(stored.len(), N); + assert!(stored.is_done()); + let deep: Vec = serde_json::from_str(&stored.read_window(N - 3, 3).unwrap()).unwrap(); + assert_eq!(deep[2][0], serde_json::json!(N as i64)); + let grew = rss_mb().saturating_sub(before); + assert!(grew < limit_mb, "{id}: memory grew {grew} MB while streaming"); + } + + #[tokio::test] + async fn sqlite_streams_a_large_result_to_the_store() { + let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap(); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "sqlite-big"); + let before = rss_mb(); + let sql = format!("WITH RECURSIVE g(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM g WHERE x < {N}) SELECT x AS id, hex(randomblob(32)) AS v FROM g"); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let r = super::super::sqlite::stream_into(&pool, &sql, &mut sink, rx).await.unwrap(); + // Collected, these rows are ~150 MB of JSON plus the values behind it. + check(&store, "sqlite-big", r, before, 120).await; + } + + /// A fake ClickHouse HTTP endpoint answering in + /// JSONCompactEachRowWithNamesAndTypes, written in uneven chunks so lines + /// split across reads. `tail` is appended after the rows. + async fn fake_clickhouse(rows: usize, tail: &'static str) -> u16 { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut s, _) = l.accept().await.unwrap(); + let mut buf = vec![0u8; 65536]; + let _ = s.read(&mut buf).await; + s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n").await.unwrap(); + let mut out = String::from("[\"id\",\"v\"]\n[\"UInt64\",\"Nullable(String)\"]\n"); + for i in 1..=rows { + out.push_str(&format!("[{i},\"{:064x}\"]\n", i)); + if out.len() > 7_919 { + let cut = out.len() / 2 + 3; + s.write_all(&out.as_bytes()[..cut]).await.unwrap(); + out = out[cut..].to_string(); + } + } + out.push_str(tail); + s.write_all(out.as_bytes()).await.unwrap(); + }); + port + } + + fn fake_clickhouse_cfg(port: u16) -> super::super::connection::ClickhouseConfig { + super::super::connection::ClickhouseConfig { + name: "t".into(), host: "127.0.0.1".into(), port, database: "default".into(), + user: "default".into(), password: String::new(), secure: false, ssh: None, via: None, + } + } + + #[tokio::test] + async fn clickhouse_streams_a_large_result_to_the_store() { + let port = fake_clickhouse(N, "").await; + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "ch-big"); + let before = rss_mb(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let r = super::super::clickhouse::stream_into(&fake_clickhouse_cfg(port), "SELECT id, v FROM t", &mut sink, &stop).await.unwrap(); + assert_eq!(r.columns.len(), 2); + assert_eq!(r.columns[1].data_type, "String"); + assert!(r.columns[1].nullable); + // Collected as one JSONCompact document this was the body text plus + // the parsed tree: several hundred MB. + check(&store, "ch-big", r, before, 120).await; + } + + // STROKE_TEST_CH=18123:password cargo test --lib stream_tests::clickhouse_live + fn live_clickhouse() -> Option { + let spec = std::env::var("STROKE_TEST_CH").ok()?; + let (port, pw) = spec.split_once(':')?; + let mut cfg = fake_clickhouse_cfg(port.parse().ok()?); + cfg.password = pw.into(); + Some(cfg) + } + + /// Decimals keep their scale and every digit, collected, streamed and + /// read-only: as JSON numbers 12.50 came back 12.5, and a Decimal(38) + /// past a double's precision came back rounded. + #[tokio::test] + async fn clickhouse_live_decimals_keep_scale() { + let Some(cfg) = live_clickhouse() else { return }; + let sql = "SELECT toDecimal64(12.5, 2) AS p, toDecimal128('12345678901234567890.12', 2) AS big"; + let want = [Value::from("12.50"), Value::from("12345678901234567890.12")]; + let r = super::super::clickhouse::query(&cfg, sql).await.unwrap(); + assert_eq!(r.rows[0], want, "collected"); + let r = super::super::clickhouse::query_readonly(&cfg, sql).await.unwrap(); + assert_eq!(r.rows[0], want, "read-only"); + assert!(super::super::clickhouse::query_readonly(&cfg, "CREATE TABLE stroke_ro_probe (x UInt8) ENGINE = Memory").await.is_err(), "read-only must still refuse DDL"); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "ch-dec"); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + super::super::clickhouse::stream_into(&cfg, sql, &mut sink, &stop).await.unwrap(); + let row: Vec = serde_json::from_str::>>(&store.get("ch-dec").unwrap().read_window(0, 1).unwrap()).unwrap().remove(0); + assert_eq!(row, want, "streamed"); + } + + #[tokio::test] + async fn clickhouse_live_streams_and_stops() { + let Some(cfg) = live_clickhouse() else { return }; + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "ch-live"); + let before = rss_mb(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let sql = format!("SELECT number + 1 AS id, hex(MD5(toString(number))) AS v FROM numbers({N})"); + let r = super::super::clickhouse::stream_into(&cfg, &sql, &mut sink, &stop).await.unwrap(); + assert_eq!(r.columns[0].name, "id"); + assert_eq!(r.row_count, Some(N as i64)); + let stored = store.get("ch-live").unwrap(); + assert_eq!(stored.len(), N); + // UInt64 arrives quoted (output_format_json_quote_64bit_integers), as + // it did collected: values past 2^53 stay exact in the grid. + let deep: Vec = serde_json::from_str(&stored.read_window(N - 1, 1).unwrap()).unwrap(); + assert_eq!(deep[0][0], serde_json::json!(N.to_string())); + let grew = rss_mb().saturating_sub(before); + assert!(grew < 120, "memory grew {grew} MB while streaming"); + + // Stop: the server must not keep running the query. + let mut sink = sink_into(&store, "ch-stop"); + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(800)).await; let _ = tx.send(()); }); + let marker = "stroke_live_stop_marker"; + let long = format!("SELECT count() AS {marker} FROM numbers(100000000000) WHERE sipHash64(number) = 1"); + let t0 = std::time::Instant::now(); + let e = super::super::clickhouse::stream_into(&cfg, &long, &mut sink, &stop).await.unwrap_err(); + assert_eq!(e, QUERY_CANCELLED); + assert!(t0.elapsed() < std::time::Duration::from_secs(15)); + let left = super::super::clickhouse::query(&cfg, &format!("SELECT count() FROM system.processes WHERE query LIKE '%{marker}%' AND query NOT LIKE '%system.processes%'")).await.unwrap(); + assert_eq!(left.rows[0][0].as_str().map(|s| s.to_string()).unwrap_or(left.rows[0][0].to_string()), "0", "query still running on the server"); + } + + // STROKE_TEST_ORACLE=user/pw@//host:1521/FREEPDB1 STROKE_ORACLE_CLIENT_DIR=... cargo test --lib stream_tests::oracle_live + #[tokio::test] + async fn oracle_live_streams_and_stops() { + let Ok(url) = std::env::var("STROKE_TEST_ORACLE") else { return }; + let (creds, cs) = url.split_once('@').unwrap(); + let (user, password) = creds.split_once('/').unwrap(); + let cfg = super::super::connection::OracleConfig { + ssh: None, name: "live".into(), host: String::new(), port: 1521, service_name: String::new(), sid: String::new(), + connect_string: cs.into(), user: user.into(), password: password.into(), + client_lib_dir: std::env::var("STROKE_ORACLE_CLIENT_DIR").unwrap_or_default(), + }; + super::super::oracle::prepare_client(&cfg.client_lib_dir).await.unwrap(); + let h = super::super::oracle::connect(&cfg).await.unwrap(); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "ora-big"); + let before = rss_mb(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let sql = format!("SELECT a.n * 1000 + b.n + 1 AS id, RPAD('v', 64, 'x') AS v FROM (SELECT level - 1 AS n FROM dual CONNECT BY level <= {}) a CROSS JOIN (SELECT level - 1 AS n FROM dual CONNECT BY level <= 1000) b ORDER BY 1", N / 1000); + let r = super::super::oracle::stream_into(&h, &sql, &mut sink, &stop).await.unwrap(); + assert_eq!(r.columns[0].name, "ID"); + assert_eq!(r.row_count, Some(N as i64)); + let stored = store.get("ora-big").unwrap(); + assert_eq!(stored.len(), N); + let grew = rss_mb().saturating_sub(before); + assert!(grew < 120, "memory grew {grew} MB while streaming"); + + // Stop mid-stream: the call breaks and the session stays usable. + let mut sink = sink_into(&store, "ora-stop"); + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(700)).await; let _ = tx.send(()); }); + let slow = "SELECT COUNT(*) FROM (SELECT level n FROM dual CONNECT BY level <= 3000) a, (SELECT level n FROM dual CONNECT BY level <= 3000) b, (SELECT level n FROM dual CONNECT BY level <= 3000) c"; + let t0 = std::time::Instant::now(); + let e = super::super::oracle::stream_into(&h, slow, &mut sink, &stop).await.unwrap_err(); + assert_eq!(e, QUERY_CANCELLED); + assert!(t0.elapsed() < std::time::Duration::from_secs(10)); + super::super::oracle::ping(&h).await.unwrap(); + } + + // STROKE_TEST_MONGO=mongodb://127.0.0.1:27018 cargo test --lib stream_tests::mongo_live + #[tokio::test] + async fn mongo_live_streams_past_the_console_cap() { + let Ok(uri) = std::env::var("STROKE_TEST_MONGO") else { return }; + use mongodb::bson::doc; + const M: usize = 400_000; + let m = super::super::mongo::connect(&super::super::mongo::MongoConfig { ssh: None, name: "t".into(), uri, database: Some("stroke_stream".into()) }).await.unwrap(); + let c = m.client.database("stroke_stream").collection::("big"); + let _ = c.drop().await; + let mut batch = Vec::with_capacity(10_000); + for i in 0..M { + let mut d = doc! { "_id": i as i64 + 1, "n": i as i64, "v": format!("{:064x}", i) }; + // A field the first 1,000 documents never had. + if i == 250_000 { d.insert("late", "here"); } + batch.push(d); + if batch.len() == 10_000 { c.insert_many(std::mem::take(&mut batch)).await.unwrap(); } + } + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "mongo-big"); + let before = rss_mb(); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let stmt = "db.big.find({}).sort({_id: 1})"; + assert!(super::super::mongo::streams(stmt)); + assert!(!super::super::mongo::streams("db.big.find({}).limit(10)")); + let r = super::super::mongo::stream_into(&m, stmt, &mut sink, &stop).await.unwrap(); + assert_eq!(r.row_count, Some(M as i64), "past the 5,000-document cap"); + assert_eq!(r.columns.last().unwrap().name, super::super::mongo::OTHER_FIELDS); + let stored = store.get("mongo-big").unwrap(); + assert_eq!(stored.len(), M); + let late: Vec> = serde_json::from_str(&stored.read_window(250_000, 1).unwrap()).unwrap(); + assert_eq!(late[0].last().unwrap(), &serde_json::json!({ "late": "here" })); + let grew = rss_mb().saturating_sub(before); + assert!(grew < 120, "memory grew {grew} MB while streaming"); + // Stop while the server is still working: the tagged operation is killed. + let slow = "db.big.aggregate([{$group: {_id: {$mod: [\"$n\", 7]}, s: {$sum: {$function: {body: 'function(n){var x=0; for (var i=0;i<20000;i++){x+=i;} return x;}', args: [\"$n\"], lang: 'js'}}}}}])"; + assert!(super::super::mongo::streams(slow)); + let mut sink = sink_into(&store, "mongo-stop"); + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(1500)).await; let _ = tx.send(()); }); + let t0 = std::time::Instant::now(); + let e = super::super::mongo::stream_into(&m, slow, &mut sink, &stop).await.unwrap_err(); + assert_eq!(e, QUERY_CANCELLED); + assert!(t0.elapsed() < std::time::Duration::from_secs(15)); + tokio::time::sleep(std::time::Duration::from_millis(1000)).await; + let admin = m.client.database("admin"); + let left: Vec = futures::TryStreamExt::try_collect(admin.aggregate(vec![ + doc! { "$currentOp": {} }, + doc! { "$match": { "command.aggregate": "big" } }, + ]).await.unwrap()).await.unwrap(); + assert!(left.is_empty(), "the aggregate still runs on the server: {left:?}"); + let _ = c.drop().await; + } + + /// Explain on the document engines, against real servers: + /// STROKE_TEST_MONGO=mongodb://127.0.0.1:27018 STROKE_TEST_ES=http://127.0.0.1:19200 + /// STROKE_TEST_COUCH=http://admin:admin@127.0.0.1:15984 cargo test --lib live_doc_plans + #[tokio::test] + async fn live_doc_plans() { + fn types(n: &Value, out: &mut Vec) { + out.push(n["Node Type"].as_str().unwrap_or("").to_string()); + for k in n["Plans"].as_array().into_iter().flatten() { + types(k, out); + } + } + if let Ok(uri) = std::env::var("STROKE_TEST_MONGO") { + use mongodb::bson::doc; + let m = super::super::mongo::connect(&super::super::mongo::MongoConfig { ssh: None, name: "t".into(), uri, database: Some("stroke_plan".into()) }).await.unwrap(); + let c = m.client.database("stroke_plan").collection::("t"); + let _ = c.drop().await; + c.insert_many((0..2000).map(|i| doc! { "n": i, "k": i % 10 })).await.unwrap(); + c.create_index(mongodb::IndexModel::builder().keys(doc! { "n": 1 }).build()).await.unwrap(); + let p = super::super::mongo::explain_plan(&m, "db.t.find({n: {$gt: 1500}}).sort({n: 1})").await.unwrap(); + let mut t = vec![]; + types(&p, &mut t); + assert!(t.iter().any(|s| s == "IXSCAN"), "{p}"); + assert!(p.to_string().contains("n_1"), "{p}"); + let p = super::super::mongo::explain_plan(&m, "db.t.find({k: 3})").await.unwrap(); + assert!(p.to_string().contains("COLLSCAN"), "{p}"); + assert!(p.to_string().contains("Rows Removed by Filter"), "{p}"); + let p = super::super::mongo::explain_plan(&m, "db.t.aggregate([{$match: {k: 3}}, {$group: {_id: null, s: {$sum: \"$n\"}}}])").await.unwrap(); + assert!(p["Node Type"].is_string(), "{p}"); + println!("mongo aggregate plan: {p}"); + let _ = c.drop().await; + } + if let Ok(url) = std::env::var("STROKE_TEST_ES") { + let cfg = super::super::elastic::EsConfig { ssh: None, via: None, name: "t".into(), url, user: None, password: None, api_key: None, flavor: None, insecure: true }; + let cfg = super::super::elastic::connect(cfg).await.unwrap(); + super::super::elastic::request(&cfg, "PUT", "stroke_plan/_doc/1?refresh=wait_for", Some(&serde_json::json!({"level": "error", "ms": 12}))).await.unwrap(); + let p = super::super::elastic::explain_plan(&cfg, r#"stroke_plan.search({"query": {"bool": {"must": [{"term": {"level.keyword": "error"}}], "filter": [{"range": {"ms": {"gte": 5}}}]}}})"#).await.unwrap(); + let mut t = vec![]; + types(&p, &mut t); + assert_eq!(t[0], "Search"); + assert!(t.iter().any(|s| s == "Shard"), "{p}"); + assert!(t.iter().any(|s| s == "BooleanQuery"), "{p}"); + assert_eq!(p["Actual Rows"], serde_json::json!(1)); + let p = super::super::elastic::explain_plan(&cfg, "GET stroke_plan/_search\n{\"query\": {\"match_all\": {}}}").await.unwrap(); + assert!(p.to_string().contains("MatchAllDocsQuery"), "{p}"); + let _ = super::super::elastic::request(&cfg, "DELETE", "stroke_plan", None).await; + } + if let Ok(url) = std::env::var("STROKE_TEST_COUCH") { + let cfg = super::super::couchdb::CouchConfig { ssh: None, via: None, name: "t".into(), url, user: Some("admin".into()), password: Some("admin".into()) }; + // Set up outside (creating databases is refused here): stroke_plan + // with a "by-level" index on level. + let p = super::super::couchdb::explain_plan(&cfg, r#"stroke_plan.find({"other": 1})"#).await.unwrap(); + assert!(p.to_string().contains("All documents scan"), "{p}"); + let p = super::super::couchdb::explain_plan(&cfg, r#"stroke_plan.find({"level": "error"})"#).await.unwrap(); + assert!(p.to_string().contains("by-level"), "{p}"); + } + } + + #[tokio::test] + async fn clickhouse_error_after_the_first_rows_is_reported() { + let port = fake_clickhouse(500, "Code: 241. DB::Exception: Memory limit exceeded\n").await; + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "ch-err"); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + let e = super::super::clickhouse::stream_into(&fake_clickhouse_cfg(port), "SELECT 1", &mut sink, &stop).await.unwrap_err(); + assert!(e.contains("Memory limit exceeded"), "{e}"); + } + + #[tokio::test] + async fn duckdb_streams_a_large_result_to_the_store() { + let cfg = super::super::connection::DuckdbConfig { name: "t".into(), file_path: ":memory:".into() }; + let h = super::super::connection::open_duckdb(&cfg).await.unwrap(); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "duck-big"); + let before = rss_mb(); + let sql = format!("SELECT range + 1 AS id, md5(range::varchar) || md5((range * 7)::varchar) AS v FROM range({N})"); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let r = super::super::duckdb::stream_into(&h, &sql, &mut sink, rx).await.unwrap(); + // DuckDB executes in streaming mode (duckdb::for_each_row_streaming), + // so neither side holds the result: this side keeps one 1,000-row + // batch. Materialized, DuckDB alone held 214 MB of it; collected, the + // same result grew memory 931 MB (duckdb_collected_for_comparison). + check(&store, "duck-big", r, before, 120).await; + } + + /// An error raised after rows have streamed comes back as an error. The + /// driver's own streaming iterator panics there, which with panic=abort + /// would close the app. + #[tokio::test] + async fn duckdb_mid_stream_error_is_an_error() { + let cfg = super::super::connection::DuckdbConfig { name: "t".into(), file_path: ":memory:".into() }; + let h = super::super::connection::open_duckdb(&cfg).await.unwrap(); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "duck-err"); + let (_tx, rx) = tokio::sync::oneshot::channel(); + let sql = "SELECT CASE WHEN range = 250000 THEN error('boom at 250000') ELSE range END AS v FROM range(400000)"; + let e = super::super::duckdb::stream_into(&h, sql, &mut sink, rx).await.unwrap_err(); + assert!(e.contains("boom at 250000"), "{e}"); + } + + /// Stop on a streamed DuckDB query reads as a cancel, and the retry that + /// recovers errors from DuckDB's spurious interrupts never reruns it. + #[tokio::test] + async fn duckdb_stop_on_a_stream_cancels_it() { + let cfg = super::super::connection::DuckdbConfig { name: "t".into(), file_path: ":memory:".into() }; + let h = super::super::connection::open_duckdb(&cfg).await.unwrap(); + let store = super::super::result_store::ResultStore::default(); + let mut sink = sink_into(&store, "duck-stop"); + let (tx, rx) = tokio::sync::oneshot::channel(); + let sql = "SELECT a.range * b.range AS v FROM range(100000) a, range(100000) b"; + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let _ = tx.send(()); + }); + let t0 = std::time::Instant::now(); + let e = super::super::duckdb::stream_into(&h, sql, &mut sink, rx).await.unwrap_err(); + assert_eq!(e, QUERY_CANCELLED); + assert!(t0.elapsed() < std::time::Duration::from_secs(10), "{:?}", t0.elapsed()); + } + + // For the record: what the same DuckDB result costs collected. + #[tokio::test] + #[ignore] + async fn duckdb_collected_for_comparison() { + let cfg = super::super::connection::DuckdbConfig { name: "t".into(), file_path: ":memory:".into() }; + let h = super::super::connection::open_duckdb(&cfg).await.unwrap(); + let before = rss_mb(); + let sql = format!("SELECT range + 1 AS id, md5(range::varchar) || md5((range * 7)::varchar) AS v FROM range({N})"); + let r = super::super::duckdb::execute_sql(&h, &sql).await.unwrap(); + let json = serde_json::to_string(&r).unwrap(); + println!("collected: rows {} json {} MB, rss grew {} MB", r.rows.len(), json.len() >> 20, rss_mb().saturating_sub(before)); + } + + #[test] + fn budget_stops_a_collected_result() { + let mut b = CollectBudget::default(); + let row = vec![Value::String("x".repeat(1 << 20))]; + let taken = (0..1000).take_while(|_| b.take(&row)).count(); + assert!((500..=512).contains(&taken), "{taken}"); + assert!(budget_message(taken).contains("SQL console streams")); + } +} + +#[cfg(test)] +mod on_conn_tunnel_tests { + // Live: Data Diff's own connection goes through the saved connection's SSH + // tunnel. The throwaway sshd logs each login, so one more login is the + // proof it went through; the ssh is gone again afterwards. + // STROKE_TEST_SSH=… STROKE_TEST_SSH_KEY=… STROKE_TEST_KNOWN_HOSTS=… + // STROKE_TEST_PG_PORT=5433 STROKE_TEST_SSHD_LOG=/path/sshd.log + #[tokio::test] + async fn data_diff_goes_through_the_tunnel() { + let (Ok(target), Ok(key), Ok(pg_port), Ok(log)) = ( + std::env::var("STROKE_TEST_SSH"), + std::env::var("STROKE_TEST_SSH_KEY"), + std::env::var("STROKE_TEST_PG_PORT"), + std::env::var("STROKE_TEST_SSHD_LOG"), + ) else { + return; + }; + let logins = || std::fs::read_to_string(&log).unwrap_or_default().matches("Accepted publickey").count(); + let (user, hostport) = target.split_once('@').unwrap(); + let (host, port) = hostport.split_once(':').unwrap(); + let cfg = serde_json::json!({ + "type": "postgres", "name": "t", "host": "127.0.0.1", "port": pg_port.parse::().unwrap(), + "database": "postgres", "user": "postgres", "password": "", "ssl": false, + "ssh": { "host": host, "port": port.parse::().unwrap(), "username": user, "privateKeyPath": key, "keepalive": 30 } + }); + let config: crate::db::connection::AnyConnectionConfig = serde_json::from_value(cfg).unwrap(); + let before = logins(); + let r = super::execute_sql_on_conn(config, "SELECT 7 AS n").await.unwrap(); + assert_eq!(r.rows[0][0], serde_json::json!(7)); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + assert_eq!(logins(), before + 1, "the query went through one SSH login"); + } +} diff --git a/src-tauri/src/db/redis.rs b/src-tauri/src/db/redis.rs index 73339a0e..b3db5215 100644 --- a/src-tauri/src/db/redis.rs +++ b/src-tauri/src/db/redis.rs @@ -30,6 +30,22 @@ static POOL: std::sync::LazyLock( + &'a self, + _host: &'b str, + _port: u16, + ) -> ::redis::RedisFuture<'a, Box + Send + 'a>> { + let addr = self.0; + Box::pin(async move { Ok(Box::new(std::iter::once(addr)) as Box + Send>) }) + } +} + fn url_for(cfg: &RedisConfig) -> String { let scheme = if cfg.tls { "rediss" } else { "redis" }; let auth = match cfg.password.as_deref().map(str::trim).filter(|p| !p.is_empty()) { @@ -39,13 +55,21 @@ fn url_for(cfg: &RedisConfig) -> String { format!("{scheme}://{auth}{}:{}/{}", cfg.host, cfg.port, cfg.db) } -async fn dial(url: &str) -> Result<::redis::aio::MultiplexedConnection, String> { - let client = ::redis::Client::open(url).map_err(|e| format!("Redis connection failed: {e}"))?; +fn connection_config(via: Option) -> ::redis::AsyncConnectionConfig { // Bounded: with no timeout an unreachable host (or a TLS port spoken to in // plain TCP) left the connect awaiting until the OS gave up. let config = ::redis::AsyncConnectionConfig::new() .set_connection_timeout(Some(std::time::Duration::from_secs(10))) .set_response_timeout(Some(std::time::Duration::from_secs(30))); + match via { + Some(addr) => config.set_dns_resolver(ViaTunnel(addr)), + None => config, + } +} + +async fn dial(url: &str, via: Option) -> Result<::redis::aio::MultiplexedConnection, String> { + let client = ::redis::Client::open(url).map_err(|e| format!("Redis connection failed: {e}"))?; + let config = connection_config(via); client .get_multiplexed_async_connection_with_config(&config) .await @@ -55,7 +79,11 @@ async fn dial(url: &str) -> Result<::redis::aio::MultiplexedConnection, String> /// A multiplexed connection for this config: the cached one when it is still /// alive, otherwise a new one (which then becomes the cached one). async fn open(cfg: &RedisConfig) -> Result<::redis::aio::MultiplexedConnection, String> { - let url = url_for(cfg); + // Keyed by the tunnel too: the same server reached two ways is two connections. + let url = match cfg.via { + Some(via) => format!("{}#via={via}", url_for(cfg)), + None => url_for(cfg), + }; let mut pool = POOL.lock().await; if let Some(entry) = pool.get_mut(&url) { let fresh = entry.last_used.elapsed() < IDLE_CHECK; @@ -73,7 +101,7 @@ async fn open(cfg: &RedisConfig) -> Result<::redis::aio::MultiplexedConnection, // Dial without holding the lock for the whole handshake would let two // commands race to open two connections; holding it is the simpler bound, // and it only ever waits on the first connect for a given host. - let conn = dial(&url).await?; + let conn = dial(&url_for(cfg), cfg.via).await?; pool.insert(url, Cached { conn: conn.clone(), last_used: Instant::now() }); Ok(conn) } @@ -81,7 +109,11 @@ async fn open(cfg: &RedisConfig) -> Result<::redis::aio::MultiplexedConnection, /// Drop the cached connection for a config (disconnect, or a failed PING in /// `ping`), so the next command dials fresh. pub async fn forget(cfg: &RedisConfig) { - POOL.lock().await.remove(&url_for(cfg)); + let mut pool = POOL.lock().await; + pool.remove(&url_for(cfg)); + if let Some(via) = cfg.via { + pool.remove(&format!("{}#via={via}", url_for(cfg))); + } } /// Connectivity/credential check - issues a `PING`. @@ -784,6 +816,9 @@ where if channels.is_empty() && patterns.is_empty() { return Err("Name a channel or a pattern to subscribe to".into()); } + if let Some(via) = cfg.via { + return subscribe_via(cfg, via, id, channels, patterns, emit).await; + } let client = ::redis::Client::open(url_for(cfg)).map_err(|e| format!("Redis connection failed: {e}"))?; let mut ps = client.get_async_pubsub().await.map_err(|e| format!("Could not open a pub/sub connection: {e}"))?; for c in &channels { @@ -810,6 +845,55 @@ where Ok(()) } +/// `subscribe` through an SSH tunnel. The dedicated pub/sub connection in +/// redis-rs always uses the system resolver, so it would dial the server's +/// name directly instead of the tunnel. A RESP3 connection takes the tunnel's +/// resolver and delivers messages as push frames (Redis 6+). +async fn subscribe_via(cfg: &RedisConfig, via: std::net::SocketAddr, id: String, channels: Vec, patterns: Vec, emit: F) -> Result<(), String> +where + F: Fn(PubSubMessage) + Send + 'static, +{ + let url = format!("{}?protocol=resp3", url_for(cfg)); + let client = ::redis::Client::open(url).map_err(|e| format!("Redis connection failed: {e}"))?; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<::redis::PushInfo>(); + let config = connection_config(Some(via)).set_push_sender(tx); + let mut conn = client + .get_multiplexed_async_connection_with_config(&config) + .await + .map_err(|e| format!("Could not open a pub/sub connection: {e}"))?; + for c in &channels { + conn.subscribe(c).await.map_err(|e| format!("SUBSCRIBE {c} failed (subscriptions through an SSH tunnel need Redis 6 or later): {e}"))?; + } + for p in &patterns { + conn.psubscribe(p).await.map_err(|e| format!("PSUBSCRIBE {p} failed (subscriptions through an SSH tunnel need Redis 6 or later): {e}"))?; + } + unsubscribe(&id); + let task = tokio::spawn(async move { + // Held for the subscription's life: dropping it closes the connection. + let _conn = conn; + while let Some(push) = rx.recv().await { + let text = |v: Option<&::redis::Value>| v.map(value_to_string).unwrap_or_default(); + let payload = |v: Option<&::redis::Value>| match v { + Some(::redis::Value::BulkString(b)) => bytes_to_display(b), + other => text(other), + }; + let (channel, pattern, body) = match push.kind { + ::redis::PushKind::Message => (text(push.data.first()), None, payload(push.data.get(1))), + ::redis::PushKind::PMessage => (text(push.data.get(1)), Some(text(push.data.first())), payload(push.data.get(2))), + _ => continue, + }; + emit(PubSubMessage { + channel, + pattern, + payload: body, + at: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0), + }); + } + }); + SUBS.lock().map_err(|_| "Subscription registry poisoned")?.insert(id, task.abort_handle()); + Ok(()) +} + pub fn unsubscribe(id: &str) { if let Ok(mut m) = SUBS.lock() { if let Some(h) = m.remove(id) { @@ -951,7 +1035,7 @@ mod redis_live { use super::*; fn cfg() -> RedisConfig { - RedisConfig { + RedisConfig { ssh: None, via: None, name: "it".into(), host: "127.0.0.1".into(), port: std::env::var("STROKE_REDIS_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(6391), @@ -1039,3 +1123,26 @@ mod redis_live { apply(&c, vec![op(&["FLUSHDB"])]).await.unwrap(); } } + +#[cfg(test)] +mod via_tests { + // Through a tunnel the URL keeps the server's real name (TLS checks it) + // and only the TCP connection goes to the tunnel. Proven with a name that + // does not resolve: any lookup of it would fail the connect. + // STROKE_TEST_FAKE_RESP=127.0.0.1:16390 cargo test --lib redis::via_tests + #[tokio::test] + async fn dials_the_tunnel_and_keeps_the_name() { + let Ok(addr) = std::env::var("STROKE_TEST_FAKE_RESP") else { return }; + let cfg = crate::db::connection::RedisConfig { + name: "t".into(), + host: "redis.stroke.test".into(), + port: 6379, + password: None, + db: 0, + tls: false, + ssh: None, + via: Some(addr.parse().unwrap()), + }; + super::ping(&cfg).await.expect("PING through the tunnel address"); + } +} diff --git a/src-tauri/src/db/result_store.rs b/src-tauri/src/db/result_store.rs index 6aca5b9b..8ed0330f 100644 --- a/src-tauri/src/db/result_store.rs +++ b/src-tauri/src/db/result_store.rs @@ -28,6 +28,36 @@ use std::sync::{Arc, Mutex, RwLock}; /// only bounds what a window that forgot to drop could leave behind on disk. const MAX_RESULTS: usize = 16; +/// A run won't start spooling with less free than this in the temp folder. +const MIN_FREE: u64 = 1 << 30; + +/// Free bytes on the volume holding `dir`, where the platform says. +#[cfg(unix)] +fn free_bytes(dir: &std::path::Path) -> Option { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(dir.as_os_str().as_bytes()).ok()?; + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: a valid C string and a zeroed out-struct, as statvfs expects. + if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 { + return None; + } + Some(st.f_bavail as u64 * st.f_frsize as u64) +} + +#[cfg(not(unix))] +fn free_bytes(_dir: &std::path::Path) -> Option { + None +} + +/// A write that failed because the disk is full, said so. +fn write_error(e: std::io::Error, rows: usize) -> String { + if e.kind() == std::io::ErrorKind::StorageFull { + format!("The disk filled up while the result streamed to it, after {rows} rows. Free some space and run it again, or add a LIMIT.") + } else { + format!("Could not write the result file: {e}") + } +} + /// Every stored result, by the run id the console sent with its query. pub struct ResultStore { results: Mutex)>>, @@ -60,6 +90,15 @@ fn remove_other_spools(dir: &std::path::Path) { impl ResultStore { /// A new, empty result for run `id`, replacing any earlier one with that id. pub fn create(&self, id: &str) -> Result { + if let Some(free) = free_bytes(&self.dir) { + if free < MIN_FREE { + return Err(format!( + "Only {} MB free in {}, where results stream to disk. Free some space, or turn off Settings → Database → Stream results to hold results in memory instead.", + free >> 20, + self.dir.display() + )); + } + } let safe: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect(); let path = self.dir.join(format!("{}-{safe}.jsonl", std::process::id())); let write = File::create(&path).map_err(|e| format!("Could not create the result file: {e}"))?; @@ -372,7 +411,8 @@ impl SpoolWriter { self.scratch.clear(); serde_json::to_writer(&mut self.scratch, row).map_err(|e| e.to_string())?; self.scratch.push(b'\n'); - self.file.write_all(&self.scratch).map_err(|e| format!("Could not write the result file: {e}"))?; + let rows = self.result.offsets.read().unwrap().len() + self.pending.len(); + self.file.write_all(&self.scratch).map_err(|e| write_error(e, rows))?; self.pending.push(self.pos); self.pos += self.scratch.len() as u64; Ok(self.scratch.len()) @@ -380,7 +420,8 @@ impl SpoolWriter { /// Make every row written so far readable. Returns how many rows are. pub fn flush(&mut self) -> Result { - self.file.flush().map_err(|e| format!("Could not write the result file: {e}"))?; + let rows = self.result.offsets.read().unwrap().len() + self.pending.len(); + self.file.flush().map_err(|e| write_error(e, rows))?; let mut offsets = self.result.offsets.write().unwrap(); offsets.append(&mut self.pending); self.result.end.store(self.pos, AtomicOrdering::Release); @@ -915,3 +956,13 @@ mod tests { assert_eq!(window(&r, 0, 4), rows); } } + +#[cfg(all(test, unix))] +mod disk_tests { + #[test] + fn reads_free_space_and_names_a_full_disk() { + assert!(super::free_bytes(&std::env::temp_dir()).is_some_and(|b| b > 0)); + let full = std::io::Error::from(std::io::ErrorKind::StorageFull); + assert!(super::write_error(full, 1234).contains("disk filled up") ); + } +} diff --git a/src-tauri/src/db/schema.rs b/src-tauri/src/db/schema.rs index 3495ccc2..67b0fa2f 100644 --- a/src-tauri/src/db/schema.rs +++ b/src-tauri/src/db/schema.rs @@ -285,6 +285,39 @@ pub async fn table_row_counts( } Ok(counts) } + ActiveConnection::Spanner(h) => { + let mut counts = Vec::with_capacity(tables.len()); + for name in tables { + let row_count = super::spanner::count_rows(&h, &schema, &name).await.unwrap_or_else(|e| { + eprintln!("[row count] {schema}.{name}: {e}"); + -1 + }); + counts.push(TableRowCount { name, row_count }); + } + Ok(counts) + } + ActiveConnection::Bigquery(h) => { + let mut counts = Vec::with_capacity(tables.len()); + for name in tables { + let row_count = super::bigquery::count_rows(&h, &schema, &name).await.unwrap_or_else(|e| { + eprintln!("[row count] {schema}.{name}: {e}"); + -1 + }); + counts.push(TableRowCount { name, row_count }); + } + Ok(counts) + } + // SHOW TABLES carries every table's row count: one call, no warehouse. + ActiveConnection::Snowflake(h) => { + let listed = super::snowflake::list_tables(&h, &schema).await.unwrap_or_default(); + Ok(tables + .into_iter() + .map(|name| { + let row_count = listed.iter().find(|t| t.name == name).map(|t| t.row_count).unwrap_or(-1); + TableRowCount { name, row_count } + }) + .collect()) + } _ => Ok(Vec::new()), } } @@ -373,11 +406,14 @@ async fn list_indexes_pg(pool: &PgPool, schema: &str) -> Result, // ── SQLite / D1 ─────────────────────────────────────────────────────────────── +// SQLite reserves the sqlite_ prefix (CREATE TABLE sqlite_x is an error), so +// sqlite_sequence and sqlite_stat1 are never the user's: they stay out of the +// table lists, as libSQL's already did. Escaped: `_` alone matches any letter. async fn list_tables_sqlite(pool: &sqlx::SqlitePool) -> Result, String> { // The catalog's rowid grows as objects are created, so it doubles as the // creation order SQLite otherwise does not keep. let rows = sqlx::query( - "SELECT name, type, rowid FROM sqlite_master WHERE type IN ('table','view') ORDER BY name", + "SELECT name, type, rowid FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", ) .fetch_all(pool) .await @@ -522,7 +558,7 @@ async fn list_indexes_sqlite_master(pool: &sqlx::SqlitePool) -> Result Result, String> { let result = super::d1::query( cfg, - "SELECT name, type, rowid AS seq FROM sqlite_master WHERE type IN ('table','view') ORDER BY name", + "SELECT name, type, rowid AS seq FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", vec![], ) .await?; @@ -658,7 +694,7 @@ async fn list_indexes_d1_master(cfg: &super::connection::D1Config) -> Result Result, String> { let result = super::libsql::query( cfg, - "SELECT name, type, rowid AS seq FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name", + "SELECT name, type, rowid AS seq FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name", vec![], ).await?; let name_idx = result.columns.iter().position(|c| c.name == "name").unwrap_or(0); @@ -1139,11 +1175,20 @@ async fn list_sequences_pg(pool: &PgPool, schema: &str) -> Result) -> Result, String> { - match require_conn(&state)? { + schemas_of(&require_conn(&state)?).await +} + +/// The schemas of a connection, its own first where the engine knows it. +pub async fn schemas_of(conn: &ActiveConnection) -> Result, String> { + match conn.clone() { ActiveConnection::Postgres(pool) => list_schemas_pg(&pool).await, ActiveConnection::Mysql(pool) => list_schemas_mysql(&pool).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::list_schemas(&cfg).await, ActiveConnection::Posthog(cfg) => super::posthog::list_schemas(&cfg).await, + ActiveConnection::Spanner(h) => super::spanner::list_schemas(&h).await, + ActiveConnection::Bigquery(h) => super::bigquery::list_schemas(&h).await, + ActiveConnection::Snowflake(h) => super::snowflake::list_schemas(&h).await, + ActiveConnection::Odbc(h) => super::odbc::list_schemas(&h).await, ActiveConnection::Redis(_) => Ok(vec![]), ActiveConnection::Dynamodb(_) => Ok(vec![super::docdb::FLAT_SCHEMA.to_string()]), ActiveConnection::Doc(d) => super::docdb::list_schemas(&d).await, @@ -1176,6 +1221,10 @@ pub async fn list_tables(state: Db<'_>, schema: String) -> Result ActiveConnection::LibSql(cfg) => list_tables_libsql(&cfg).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::list_tables(&cfg, &schema).await, ActiveConnection::Posthog(cfg) => super::posthog::list_tables(&cfg).await, + ActiveConnection::Spanner(h) => super::spanner::list_tables(&h, &schema).await, + ActiveConnection::Bigquery(h) => super::bigquery::list_tables(&h, &schema).await, + ActiveConnection::Snowflake(h) => super::snowflake::list_tables(&h, &schema).await, + ActiveConnection::Odbc(h) => super::odbc::list_tables(&h, &schema).await, ActiveConnection::Redis(cfg) => super::redis::list_tables(&cfg).await, ActiveConnection::Dynamodb(cfg) => super::dynamodb::list_tables(&cfg).await, ActiveConnection::Doc(d) => super::docdb::list_tables_in(&d, &schema).await, @@ -1213,6 +1262,11 @@ pub async fn list_indexes_for( ActiveConnection::LibSql(cfg) => list_indexes_libsql(&cfg).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::list_indexes(&cfg, &schema).await, ActiveConnection::Posthog(cfg) => super::posthog::list_indexes(&cfg).await, + ActiveConnection::Spanner(h) => super::spanner::list_indexes(&h, &schema).await, + // BigQuery has no indexes to browse (search indexes aside). + ActiveConnection::Bigquery(_) => Ok(vec![]), + ActiveConnection::Snowflake(_) => Ok(vec![]), + ActiveConnection::Odbc(_) => Ok(vec![]), ActiveConnection::Redis(cfg) => super::redis::list_indexes(&cfg).await, ActiveConnection::Dynamodb(cfg) => match table { Some(t) => Ok(super::dynamodb::describe_shape(&cfg, &t).await?.1), @@ -1397,6 +1451,10 @@ pub async fn get_table_column_structure( super::clickhouse::get_column_structure(&cfg, &schema, &table).await } ActiveConnection::Posthog(cfg) => super::posthog::get_column_structure(&cfg, &table).await, + ActiveConnection::Spanner(h) => super::spanner::get_column_structure(&h, &schema, &table).await, + ActiveConnection::Bigquery(h) => super::bigquery::get_column_structure(&h, &schema, &table).await, + ActiveConnection::Snowflake(h) => super::snowflake::get_column_structure(&h, &schema, &table).await, + ActiveConnection::Odbc(h) => super::odbc::get_column_structure(&h, &schema, &table).await, ActiveConnection::Redis(cfg) => { super::redis::get_column_structure(&cfg, &table).await } @@ -1727,6 +1785,11 @@ pub async fn get_schema_column_structure( ActiveConnection::Doc(d) => return super::docdb::schema_columns_in(&d, &schema).await, ActiveConnection::Dynamodb(_) | ActiveConnection::Redis(_) => return Ok(vec![]), ActiveConnection::Oracle(h) => return super::oracle::schema_column_structure(&h, &schema).await, + // Spanner's schemas are '' and 'default', which the identifier check refuses. + ActiveConnection::Spanner(h) => return super::spanner::schema_column_structure(&h, &schema).await, + ActiveConnection::Bigquery(h) => return super::bigquery::schema_column_structure(&h, &schema).await, + ActiveConnection::Snowflake(h) => return super::snowflake::schema_column_structure(&h, &schema).await, + ActiveConnection::Odbc(h) => return super::odbc::schema_column_structure(&h, &schema).await, _ => {} } validate_ident(&schema)?; @@ -2219,7 +2282,7 @@ async fn get_incoming_fks_mysql(pool: &MySqlPool, schema: &str, table: &str) -> async fn get_incoming_fks_sqlite(pool: &sqlx::SqlitePool, table: &str) -> Result, String> { let tables: Vec = sqlx::query( - "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'" ).fetch_all(pool).await.unwrap_or_default() .iter().filter_map(|r| r.try_get::(0).ok()).collect(); @@ -2381,7 +2444,7 @@ async fn get_incoming_fks_d1(cfg: &super::connection::D1Config, table: &str) -> } let tables: Vec = super::d1::query( cfg, - "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'", + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'", vec![], ) .await @@ -2415,7 +2478,7 @@ async fn get_incoming_fks_libsql(cfg: &super::connection::LibSqlConfig, table: & } let tables: Vec = super::libsql::query( cfg, - "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'", + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'", vec![], ) .await @@ -2509,6 +2572,18 @@ pub async fn get_incoming_foreign_keys( if let ActiveConnection::Oracle(h) = require_conn(&state)? { return super::oracle::incoming_foreign_keys(&h, &schema, &table).await; } + if let ActiveConnection::Spanner(h) = require_conn(&state)? { + return super::spanner::incoming_foreign_keys(&h, &schema, &table).await; + } + if let ActiveConnection::Bigquery(h) = require_conn(&state)? { + return super::bigquery::incoming_foreign_keys(&h, &schema, &table).await; + } + if let ActiveConnection::Snowflake(h) = require_conn(&state)? { + return super::snowflake::incoming_foreign_keys(&h, &schema, &table).await; + } + if let ActiveConnection::Odbc(h) = require_conn(&state)? { + return super::odbc::incoming_foreign_keys(&h, &schema, &table).await; + } validate_ident(&schema)?; validate_ident(&table)?; match require_conn(&state)? { @@ -2527,6 +2602,28 @@ pub async fn get_incoming_foreign_keys( // ── DDL reconstruction ──────────────────────────────────────────────────────── async fn get_ddl_pg(pool: &PgPool, schema: &str, table: &str) -> Result { + // A view came back as CREATE TABLE built from its columns, so the schema + // diagram's DDL script would have made tables where geography_columns and + // geometry_columns are views. Views and materialized views get their own + // definition. + let view = sqlx::query( + r#"SELECT c.relkind::text, pg_catalog.pg_get_viewdef(c.oid, true) + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('v', 'm')"#, + ) + .bind(schema) + .bind(table) + .fetch_optional(pool) + .await + .map_err(|e| format!("DDL view query failed: {e}"))?; + if let Some(row) = view { + let kind: String = row.try_get(0).unwrap_or_default(); + let def: String = row.try_get(1).unwrap_or_default(); + let q = |s: &str| format!("\"{}\"", s.replace('"', "\"\"")); + let keyword = if kind == "m" { "MATERIALIZED VIEW" } else { "VIEW" }; + return Ok(format!("CREATE {keyword} {}.{} AS\n{};", q(schema), q(table), def.trim().trim_end_matches(';'))); + } let col_rows = sqlx::query( r#"SELECT a.attname, @@ -2626,8 +2723,10 @@ async fn get_ddl_mysql(pool: &MySqlPool, schema: &str, table: &str) -> Result get_ddl_libsql(&cfg, &table).await, ActiveConnection::Clickhouse(cfg) => super::clickhouse::get_ddl(&cfg, &schema, &table).await, ActiveConnection::Posthog(cfg) => super::posthog::get_ddl(&cfg, &table).await, + ActiveConnection::Spanner(h) => super::spanner::get_ddl(&h, &schema, &table).await, + ActiveConnection::Bigquery(h) => super::bigquery::get_ddl(&h, &schema, &table).await, + ActiveConnection::Snowflake(h) => super::snowflake::get_ddl(&h, &schema, &table).await, + ActiveConnection::Odbc(h) => super::odbc::get_ddl(&h, &schema, &table).await, ActiveConnection::Redis(cfg) => super::redis::get_ddl(&cfg, &table).await, ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Ok(String::new()), ActiveConnection::Duckdb(h) => super::duckdb::get_ddl(&h, &table).await, @@ -2706,6 +2809,8 @@ pub async fn get_table_ddl( /// List schemas for an arbitrary saved connection without changing global state. pub async fn list_schemas_on_conn(config: AnyConnectionConfig) -> Result, String> { + // Its own connection, through the saved connection's SSH tunnel if any. + let (config, _tunnel) = super::connection::tunnel_any(config).await?; use super::connection::{open_mysql, open_pg}; match config { AnyConnectionConfig::Postgres(c) => { @@ -2734,6 +2839,8 @@ pub async fn list_tables_on_conn( config: AnyConnectionConfig, schema: String, ) -> Result, String> { + // Its own connection, through the saved connection's SSH tunnel if any. + let (config, _tunnel) = super::connection::tunnel_any(config).await?; use super::connection::{open_mysql, open_pg, open_sqlite}; let to_names = |ts: Vec| ts.into_iter().map(|t| t.name).collect::>(); match config { @@ -2786,6 +2893,8 @@ pub async fn get_table_ddl_on_conn( schema: String, table: String, ) -> Result { + // Its own connection, through the saved connection's SSH tunnel if any. + let (config, _tunnel) = super::connection::tunnel_any(config).await?; use super::connection::{open_mysql, open_pg, open_sqlite}; if let AnyConnectionConfig::Oracle(c) = &config { let h = super::connection::open_oracle(c).await?; @@ -2849,6 +2958,18 @@ mod create_order_tests { assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::>(), ["alpha", "mid", "zeta"]); assert!(tables.iter().all(|t| t.created_at.is_none())); } + + /// sqlite_sequence is SQLite's, not the user's; a table merely starting with + /// "sqlite" is the user's. + #[tokio::test] + async fn sqlite_internal_tables_stay_out_of_the_list() { + let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap(); + for sql in ["CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT)", "INSERT INTO books DEFAULT VALUES", "CREATE TABLE sqlitex (id INTEGER)"] { + sqlx::query(sql).execute(&pool).await.unwrap(); + } + let names: Vec = super::list_tables_sqlite(&pool).await.unwrap().into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["books", "sqlitex"]); + } } #[cfg(test)] @@ -3077,3 +3198,23 @@ mod sqlite_tree_catalog { assert!(t[0].columns[0].is_primary_key && !t[0].columns[0].is_nullable); } } + +#[cfg(test)] +mod pg_view_ddl_tests { + /// Against Postgres (STROKE_TEST_POSTGIS): a view's DDL is its CREATE VIEW, + /// and running it recreates the view. + #[tokio::test] + async fn live_view_ddl_is_a_view() { + let Ok(url) = std::env::var("STROKE_TEST_POSTGIS") else { return }; + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + sqlx::raw_sql("DROP VIEW IF EXISTS public.stroke_ddl_v; CREATE VIEW public.stroke_ddl_v AS SELECT 1 AS one, 'x'::text AS two") + .execute(&pool).await.unwrap(); + let ddl = super::get_ddl_pg(&pool, "public", "stroke_ddl_v").await.unwrap(); + assert!(ddl.starts_with("CREATE VIEW \"public\".\"stroke_ddl_v\" AS"), "{ddl}"); + sqlx::raw_sql("DROP VIEW public.stroke_ddl_v").execute(&pool).await.unwrap(); + sqlx::raw_sql(&ddl).execute(&pool).await.unwrap(); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM public.stroke_ddl_v").fetch_one(&pool).await.unwrap(); + assert_eq!(n, 1); + sqlx::raw_sql("DROP VIEW public.stroke_ddl_v").execute(&pool).await.unwrap(); + } +} diff --git a/src-tauri/src/db/snowflake.rs b/src-tauri/src/db/snowflake.rs new file mode 100644 index 00000000..b28c7353 --- /dev/null +++ b/src-tauri/src/db/snowflake.rs @@ -0,0 +1,1210 @@ +//! Snowflake over its SQL REST API (v2). Beta. +//! +//! The SQL API takes key-pair authentication (a JWT signed with the user's +//! RSA key, whose public half is registered on the user) or a programmatic +//! access token. It does not take passwords. +//! +//! Metadata comes from SHOW and DESCRIBE, which run in Snowflake's cloud +//! services without a warehouse: schemas, tables with their row counts, +//! columns with their primary keys, and foreign keys both ways. Queries and +//! the grid need the connection's warehouse. +//! +//! Every statement is submitted asynchronously and its handle kept, so Stop +//! cancels it on Snowflake; results arrive in partitions, which the console +//! streams. Values in the grid are bound as parameters (`?`). + +use super::query::{ColumnInfo, ForeignKeyInfo, RowFilter, SqlResult, TableRows}; +use super::schema::{ColumnStructureRow, TableInfo}; +use base64::{engine::general_purpose::STANDARD as B64, engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine as _}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SnowflakeConfig { + pub name: String, + /// The account identifier: `myorg-myaccount`, or a locator such as + /// `xy12345.us-east-2.aws`. + pub account: String, + pub user: String, + /// "keypair" (a private key file) or "token" (a programmatic access token). + #[serde(default = "default_auth")] + pub auth: String, + #[serde(default)] + pub private_key_file: Option, + /// The programmatic access token, for `auth = "token"`. + #[serde(default)] + pub password: Option, + #[serde(default)] + pub warehouse: Option, + pub database: String, + /// The schema bare table names mean; PUBLIC when blank. + #[serde(default)] + pub schema: Option, + #[serde(default)] + pub role: Option, + /// The API's base URL, for private link or a test server. Derived from + /// the account when blank. + #[serde(default)] + pub host: Option, +} + +fn default_auth() -> String { + "keypair".into() +} + +pub struct SnowflakeConn { + pub cfg: SnowflakeConfig, + /// The signed JWT and when it was made; Snowflake takes one for an hour. + jwt: Mutex>, +} + +pub type SnowflakeHandle = Arc; + +/// Rows one console statement collects when it does not stream. +const MAX_ROWS: usize = 100_000; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .timeout(Duration::from_secs(120)) + .connect_timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default() + }) +} + +fn opt(s: &Option) -> Option<&str> { + s.as_deref().map(str::trim).filter(|s| !s.is_empty()) +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +fn base_url(cfg: &SnowflakeConfig) -> String { + match opt(&cfg.host) { + Some(h) if h.contains("://") => h.trim_end_matches('/').to_string(), + Some(h) => format!("https://{}", h.trim_end_matches('/')), + None => format!("https://{}.snowflakecomputing.com", cfg.account.trim().to_ascii_lowercase()), + } +} + +// ── Key-pair sign-in ────────────────────────────────────────────────────────── + +fn pem_to_der(pem: &str) -> Result<(String, Vec), String> { + let label = pem + .lines() + .find_map(|l| l.trim().strip_prefix("-----BEGIN ").and_then(|r| r.strip_suffix("-----"))) + .unwrap_or("") + .to_string(); + let body: String = pem.lines().map(str::trim).filter(|l| !l.starts_with("-----") && !l.is_empty()).collect(); + let der = B64.decode(body).map_err(|e| format!("The private key file is not valid PEM: {e}"))?; + Ok((label, der)) +} + +fn der_len(n: usize) -> Vec { + if n < 0x80 { + vec![n as u8] + } else { + let bytes: Vec = n.to_be_bytes().iter().copied().skip_while(|b| *b == 0).collect(); + let mut out = vec![0x80 | bytes.len() as u8]; + out.extend(bytes); + out + } +} + +/// The SubjectPublicKeyInfo DER of an RSA public key (PKCS#1 RSAPublicKey), +/// which is what Snowflake fingerprints. +fn spki_der(rsa_public_key: &[u8]) -> Vec { + // SEQUENCE { OID 1.2.840.113549.1.1.1, NULL } + let alg: &[u8] = &[0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]; + let mut bit = vec![0x03]; + bit.extend(der_len(rsa_public_key.len() + 1)); + bit.push(0x00); + bit.extend_from_slice(rsa_public_key); + let mut out = vec![0x30]; + out.extend(der_len(alg.len() + bit.len())); + out.extend_from_slice(alg); + out.extend(bit); + out +} + +/// The account as the JWT names it: upper case, the locator without its +/// region, and an organization's `org.account` written `org-account`. +fn jwt_account(account: &str) -> String { + let a = account.trim(); + let a = a.strip_suffix(".snowflakecomputing.com").unwrap_or(a); + let first = if a.contains('-') && !a.contains('.') { a } else { a.split('.').next().unwrap_or(a) }; + first.replace('.', "-").to_ascii_uppercase() +} + +/// A key-pair JWT: `iss` is ACCOUNT.USER.SHA256:. +pub fn sign_jwt(account: &str, user: &str, private_key_pem: &str, iat: u64) -> Result { + let (label, der) = pem_to_der(private_key_pem)?; + if label.contains("ENCRYPTED") { + return Err("The private key is encrypted with a passphrase. Export it unencrypted (openssl pkcs8 -topk8 -nocrypt) or use an access token.".into()); + } + let key = if label.contains("RSA PRIVATE KEY") { + ring::signature::RsaKeyPair::from_der(&der) + } else { + ring::signature::RsaKeyPair::from_pkcs8(&der) + } + .map_err(|e| format!("The private key was rejected: {e}. Snowflake key pairs are RSA keys of 2048 bits or more."))?; + use ring::signature::KeyPair; + let fp = B64.encode(ring::digest::digest(&ring::digest::SHA256, &spki_der(key.public_key().as_ref())).as_ref()); + let qualified = format!("{}.{}", jwt_account(account), user.trim().to_ascii_uppercase()); + let header = B64URL.encode(br#"{"alg":"RS256","typ":"JWT"}"#); + let claims = B64URL.encode(json!({ "iss": format!("{qualified}.SHA256:{fp}"), "sub": qualified, "iat": iat, "exp": iat + 3540 }).to_string()); + let input = format!("{header}.{claims}"); + let mut sig = vec![0u8; key.public().modulus_len()]; + key.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), input.as_bytes(), &mut sig) + .map_err(|_| "Could not sign with the private key".to_string())?; + Ok(format!("{input}.{}", B64URL.encode(sig))) +} + +/// The Authorization header's token and its type. +fn credentials(h: &SnowflakeConn) -> Result<(String, &'static str), String> { + if h.cfg.auth == "token" { + let t = opt(&h.cfg.password).ok_or("Enter the programmatic access token")?; + return Ok((t.to_string(), "PROGRAMMATIC_ACCESS_TOKEN")); + } + let mut g = h.jwt.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((jwt, at)) = g.as_ref() { + if now() < at + 3000 { + return Ok((jwt.clone(), "KEYPAIR_JWT")); + } + } + let path = opt(&h.cfg.private_key_file).ok_or("Choose the private key file")?; + let pem = std::fs::read_to_string(path).map_err(|e| format!("Could not read the private key file {path}: {e}"))?; + let iat = now(); + let jwt = sign_jwt(&h.cfg.account, &h.cfg.user, &pem, iat)?; + *g = Some((jwt.clone(), iat)); + Ok((jwt, "KEYPAIR_JWT")) +} + +// ── Requests ────────────────────────────────────────────────────────────────── + +async fn call(h: &SnowflakeConn, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result<(u16, Value), String> { + let (token, kind) = credentials(h)?; + let url = format!("{}{}", base_url(&h.cfg), path); + let mut req = client() + .request(method, &url) + .bearer_auth(token) + .header("X-Snowflake-Authorization-Token-Type", kind) + .header("Accept", "application/json") + .header("User-Agent", "Stroke/1.0"); + if let Some(b) = body { + req = req.json(b); + } + let resp = req.send().await.map_err(|e| { + if e.is_connect() { + format!("Could not reach Snowflake at {}: check the account identifier", base_url(&h.cfg)) + } else { + format!("Snowflake request failed: {e}") + } + })?; + let status = resp.status().as_u16(); + let text = resp.text().await.map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if status >= 400 { + let msg = v["message"].as_str().filter(|m| !m.is_empty()).map(String::from).unwrap_or_else(|| { + let t = text.trim(); + if t.is_empty() { format!("Snowflake answered HTTP {status}") } else { t.chars().take(300).collect() } + }); + return Err(match status { + 401 => format!("Snowflake refused the sign-in: {msg}"), + 403 => format!("No permission: {msg}"), + _ => msg, + }); + } + Ok((status, v)) +} + +/// A statement Snowflake accepted: its handle, for polling, partitions and Stop. +struct Statement { + handle: String, +} + +fn fresh_request_id() -> String { + uuid_like() +} + +/// A random UUID-shaped request id (Snowflake wants a UUID). +fn uuid_like() -> String { + let mut b = [0u8; 16]; + ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut b).ok(); + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + let h: String = b.iter().map(|x| format!("{x:02x}")).collect(); + format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32]) +} + +/// Bound values, as Snowflake's `bindings` (positional `?`). +#[derive(Default, Clone)] +struct Binds(Map); + +impl Binds { + fn bind(&mut self, ty: &str, value: String) -> &'static str { + let n = self.0.len() + 1; + self.0.insert(n.to_string(), json!({ "type": ty, "value": value })); + "?" + } + fn text(&mut self, s: &str) -> &'static str { + self.bind("TEXT", s.to_string()) + } +} + +/// Submit a statement asynchronously; Snowflake answers at once with a handle. +async fn submit(h: &SnowflakeConn, sql: &str, binds: &Binds) -> Result<(Statement, Option), String> { + let mut body = json!({ "statement": sql, "timeout": 0, "database": h.cfg.database.trim() }); + if let Some(w) = opt(&h.cfg.warehouse) { + body["warehouse"] = json!(w); + } + if let Some(s) = opt(&h.cfg.schema) { + body["schema"] = json!(s); + } + if let Some(r) = opt(&h.cfg.role) { + body["role"] = json!(r); + } + if !binds.0.is_empty() { + body["bindings"] = Value::Object(binds.0.clone()); + } + let path = format!("/api/v2/statements?requestId={}&async=true", fresh_request_id()); + let (status, v) = call(h, reqwest::Method::POST, &path, Some(&body)).await?; + let handle = v["statementHandle"].as_str().unwrap_or("").to_string(); + if handle.is_empty() { + return Err(v["message"].as_str().unwrap_or("Snowflake returned no statement handle").to_string()); + } + // 200: already done (and the first partition is here); 202: running. + Ok((Statement { handle }, (status == 200).then_some(v))) +} + +/// Wait for a statement and return its first partition with the metadata. +async fn wait(h: &SnowflakeConn, st: &Statement) -> Result { + let mut delay = 100u64; + loop { + let (status, v) = call(h, reqwest::Method::GET, &format!("/api/v2/statements/{}", st.handle), None).await?; + if status == 200 { + return Ok(v); + } + tokio::time::sleep(Duration::from_millis(delay)).await; + delay = (delay * 2).min(1500); + } +} + +async fn partition(h: &SnowflakeConn, st: &Statement, n: usize) -> Result { + let (_, v) = call(h, reqwest::Method::GET, &format!("/api/v2/statements/{}?partition={n}", st.handle), None).await?; + Ok(v) +} + +async fn cancel(h: &SnowflakeConn, st: &Statement) { + let _ = tokio::time::timeout(Duration::from_secs(10), call(h, reqwest::Method::POST, &format!("/api/v2/statements/{}/cancel", st.handle), None)).await; +} + +async fn run(h: &SnowflakeConn, sql: &str, binds: &Binds) -> Result<(Statement, Value), String> { + let (st, done) = submit(h, sql, binds).await?; + let first = match done { + Some(v) => v, + None => wait(h, &st).await?, + }; + Ok((st, first)) +} + +pub async fn connect(cfg: &SnowflakeConfig) -> Result { + if cfg.account.trim().is_empty() || cfg.user.trim().is_empty() { + return Err("Enter the account identifier and the user".into()); + } + if cfg.database.trim().is_empty() { + return Err("Enter the database".into()); + } + let h = Arc::new(SnowflakeConn { cfg: cfg.clone(), jwt: Mutex::new(None) }); + ping(&h).await?; + Ok(h) +} + +pub async fn ping(h: &SnowflakeConn) -> Result<(), String> { + run(h, "SELECT 1", &Binds::default()).await.map(|_| ()) +} + +// ── Values ──────────────────────────────────────────────────────────────────── + +fn row_types(v: &Value) -> Vec { + v["resultSetMetaData"]["rowType"].as_array().cloned().unwrap_or_default() +} + +fn type_label(t: &Value) -> String { + let ty = t["type"].as_str().unwrap_or("text").to_ascii_lowercase(); + match ty.as_str() { + "fixed" => match (t["precision"].as_u64(), t["scale"].as_u64()) { + (Some(p), Some(0)) => format!("NUMBER({p},0)"), + (Some(p), Some(s)) => format!("NUMBER({p},{s})"), + _ => "NUMBER".into(), + }, + "real" => "FLOAT".into(), + "text" => match t["length"].as_u64() { + Some(l) if l > 0 && l < 16_777_216 => format!("VARCHAR({l})"), + _ => "VARCHAR".into(), + }, + other => other.to_ascii_uppercase(), + } +} + +fn days_to_date(days: i64) -> Option { + chrono::NaiveDate::from_num_days_from_ce_opt(719_163 + days as i32).map(|d| d.format("%Y-%m-%d").to_string()) +} + +/// "seconds.fraction" → (seconds, nanoseconds). +fn split_secs(s: &str) -> Option<(i64, u32)> { + let (whole, frac) = s.split_once('.').unwrap_or((s, "")); + let secs: i64 = whole.trim().parse().ok()?; + let mut f = frac.trim().to_string(); + f.truncate(9); + while f.len() < 9 { + f.push('0'); + } + let nanos: u32 = f.parse().unwrap_or(0); + // A negative time before the epoch counts the fraction backwards. + if secs < 0 && nanos > 0 { Some((secs - 1, 1_000_000_000 - nanos)) } else { Some((secs, nanos)) } +} + +fn trim_frac(s: String) -> String { + match s.split_once('.') { + Some((a, b)) => { + let b = b.trim_end_matches('0'); + if b.is_empty() { a.to_string() } else { format!("{a}.{b}") } + } + None => s, + } +} + +fn timestamp(s: &str, ty: &str) -> Option { + let (secs_part, offset) = match s.split_once(' ') { + Some((a, b)) => (a, b.trim().parse::().ok().map(|m| m - 1440)), + None => (s, None), + }; + let (secs, nanos) = split_secs(secs_part)?; + let utc = chrono::DateTime::from_timestamp(secs, nanos)?; + Some(match (ty, offset) { + ("timestamp_tz", Some(mins)) => { + let off = chrono::FixedOffset::east_opt(mins * 60)?; + trim_frac(utc.with_timezone(&off).format("%Y-%m-%d %H:%M:%S%.9f").to_string()) + &utc.with_timezone(&off).format(" %:z").to_string() + } + ("timestamp_ltz", _) | ("timestamp_tz", None) => trim_frac(utc.format("%Y-%m-%d %H:%M:%S%.9f").to_string()) + " UTC", + _ => trim_frac(utc.naive_utc().format("%Y-%m-%d %H:%M:%S%.9f").to_string()), + }) +} + +fn time_of_day(s: &str) -> Option { + let (secs, nanos) = split_secs(s)?; + let t = chrono::NaiveTime::from_num_seconds_from_midnight_opt(secs.rem_euclid(86_400) as u32, nanos)?; + Some(trim_frac(t.format("%H:%M:%S%.9f").to_string())) +} + +/// A jsonv2 cell (always a string or null) as the grid shows it. +fn cell(t: &Value, v: Value) -> Value { + let Value::String(s) = v else { return v }; + let ty = t["type"].as_str().unwrap_or("text").to_ascii_lowercase(); + match ty.as_str() { + "fixed" if t["scale"].as_u64().unwrap_or(0) == 0 => match s.parse::() { + Ok(n) if n.unsigned_abs() <= (1u64 << 53) => json!(n), + _ => Value::String(s), + }, + "real" => match s.parse::() { + Ok(x) if x.is_finite() => json!(x), + _ => Value::String(s), + }, + "boolean" => match s.as_str() { + "true" | "1" => json!(true), + "false" | "0" => json!(false), + _ => Value::String(s), + }, + "date" => s.parse::().ok().and_then(days_to_date).map(Value::String).unwrap_or(Value::String(s)), + "time" => time_of_day(&s).map(Value::String).unwrap_or(Value::String(s)), + "timestamp_ntz" | "timestamp_ltz" | "timestamp_tz" => timestamp(&s, &ty).map(Value::String).unwrap_or(Value::String(s)), + "variant" | "object" | "array" => serde_json::from_str(&s).unwrap_or(Value::String(s)), + _ => super::sql_util::cap_json_value("text", Value::String(s)), + } +} + +fn columns_of(types: &[Value]) -> Vec { + types.iter().map(|t| ColumnInfo::new(t["name"].as_str().unwrap_or("").to_string(), type_label(t))).collect() +} + +fn rows_of(types: &[Value], v: &Value) -> Vec> { + v["data"] + .as_array() + .map(|rows| { + rows.iter() + .map(|r| r.as_array().map(|cells| cells.iter().zip(types).map(|(c, t)| cell(t, c.clone())).collect()).unwrap_or_default()) + .collect() + }) + .unwrap_or_default() +} + +fn partitions(v: &Value) -> usize { + v["resultSetMetaData"]["partitionInfo"].as_array().map(|p| p.len()).unwrap_or(1).max(1) +} + +/// A statement's rows, up to `cap`, across its partitions. +async fn collect(h: &SnowflakeConn, sql: &str, binds: &Binds, cap: usize) -> Result<(Vec, Vec>, Value), String> { + let (st, first) = run(h, sql, binds).await?; + let types = row_types(&first); + let mut rows = rows_of(&types, &first); + for n in 1..partitions(&first) { + if rows.len() >= cap { + break; + } + rows.extend(rows_of(&types, &partition(h, &st, n).await?)); + } + rows.truncate(cap); + Ok((types, rows, first)) +} + +fn result_of(types: &[Value], rows: Vec>, first: &Value, sql: &str, t0: Instant) -> SqlResult { + let total = first["resultSetMetaData"]["numRows"].as_i64().unwrap_or(rows.len() as i64); + let message = (total > rows.len() as i64).then(|| format!("Showing the first {} of {total} rows", rows.len())); + SqlResult { columns: columns_of(types), row_count: Some(rows.len() as i64), rows, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() } +} + +pub fn reads(stmt: &str) -> bool { + matches!(super::sql_util::statement_head(stmt).as_str(), "select" | "with" | "show" | "describe" | "desc" | "explain" | "list" | "ls") +} + +pub async fn query(h: &SnowflakeConn, stmt: &str) -> Result { + let t0 = Instant::now(); + let sql = stmt.trim().trim_end_matches(';').trim(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let (types, rows, first) = collect(h, sql, &Binds::default(), MAX_ROWS).await?; + Ok(result_of(&types, rows, &first, sql, t0)) +} + +/// One console statement that Stop cancels on Snowflake. +pub async fn query_cancellable(h: &SnowflakeConn, stmt: &str, stop: &super::stop::Stop) -> Result { + let t0 = Instant::now(); + let sql = stmt.trim().trim_end_matches(';').trim(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let (st, done) = submit(h, sql, &Binds::default()).await?; + let work = async { + let first = match done { + Some(v) => v, + None => wait(h, &st).await?, + }; + let types = row_types(&first); + let mut rows = rows_of(&types, &first); + for n in 1..partitions(&first) { + if rows.len() >= MAX_ROWS { + break; + } + rows.extend(rows_of(&types, &partition(h, &st, n).await?)); + } + rows.truncate(MAX_ROWS); + Ok::<_, String>(result_of(&types, rows, &first, sql, t0)) + }; + tokio::pin!(work); + tokio::select! { + r = &mut work => r, + _ = stop.wait() => { + cancel(h, &st).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +/// Stream a statement's partitions into the console's sink; Stop cancels it. +pub async fn stream_into(h: &SnowflakeConn, stmt: &str, sink: &mut super::query::RowSink, stop: &super::stop::Stop) -> Result { + let t0 = Instant::now(); + let sql = stmt.trim().trim_end_matches(';').trim(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + let (st, done) = submit(h, sql, &Binds::default()).await?; + let work = async { + let first = match done { + Some(v) => v, + None => wait(h, &st).await?, + }; + let types = row_types(&first); + let columns = columns_of(&types); + sink.start(columns.clone())?; + let mut n_rows = 0usize; + for r in rows_of(&types, &first) { + sink.push(r)?; + n_rows += 1; + } + for n in 1..partitions(&first) { + for r in rows_of(&types, &partition(h, &st, n).await?) { + sink.push(r)?; + n_rows += 1; + } + } + sink.finish()?; + Ok::<_, String>(SqlResult { columns, rows: vec![], row_count: Some(n_rows as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) + }; + tokio::pin!(work); + tokio::select! { + r = &mut work => r, + _ = stop.wait() => { + cancel(h, &st).await; + Err(super::query::QUERY_CANCELLED.into()) + } + } +} + +// ── Plans ───────────────────────────────────────────────────────────────────── + +/// EXPLAIN USING TABULAR, as the plan view's tree: each operation under its +/// parent, with the tables it reads and the partitions it touches. +pub async fn explain_plan(h: &SnowflakeConn, sql: &str) -> Result { + let sql = sql.trim().trim_end_matches(';').trim(); + let sql = sql.strip_prefix("EXPLAIN ").or_else(|| sql.strip_prefix("explain ")).unwrap_or(sql); + let (types, rows, _) = collect(h, &format!("EXPLAIN USING TABULAR {sql}"), &Binds::default(), 10_000).await?; + Ok(plan_tree(&types, &rows)) +} + +pub fn plan_tree(types: &[Value], rows: &[Vec]) -> Value { + let col = |name: &str| types.iter().position(|t| t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))); + let get = |r: &[Value], name: &str| -> Value { col(name).and_then(|i| r.get(i).cloned()).unwrap_or(Value::Null) }; + let text = |v: Value| match v { + Value::String(s) => s, + Value::Null => String::new(), + other => other.to_string(), + }; + let mut nodes: Vec<(String, String, Map)> = Vec::new(); + let mut root_extra = Map::new(); + for r in rows { + let op = text(get(r, "operation")); + if op.eq_ignore_ascii_case("GlobalStats") { + for k in ["partitionsTotal", "partitionsAssigned", "bytesAssigned"] { + let v = text(get(r, k)); + if !v.is_empty() { + root_extra.insert(k.into(), json!(v)); + } + } + continue; + } + let mut n = Map::new(); + n.insert("Node Type".into(), json!(op)); + let objects = text(get(r, "objects")); + if !objects.is_empty() { + n.insert("Relation Name".into(), json!(objects)); + } + let expr = text(get(r, "expressions")); + if !expr.is_empty() { + n.insert("Filter".into(), json!(expr)); + } + for k in ["partitionsAssigned", "partitionsTotal"] { + let v = text(get(r, k)); + if !v.is_empty() { + n.insert(k.into(), json!(v)); + } + } + nodes.push((text(get(r, "id")), text(get(r, "parent")), n)); + } + fn build(id: &str, nodes: &[(String, String, Map)]) -> Value { + let (_, _, me) = nodes.iter().find(|n| n.0 == id).expect("node exists"); + let mut me = me.clone(); + let kids: Vec = nodes.iter().filter(|n| n.1 == id).map(|n| build(&n.0, nodes)).collect(); + if !kids.is_empty() { + me.insert("Plans".into(), Value::Array(kids)); + } + Value::Object(me) + } + let ids: Vec<&String> = nodes.iter().map(|n| &n.0).collect(); + let roots: Vec = nodes.iter().filter(|n| n.1.is_empty() || !ids.contains(&&n.1)).map(|n| build(&n.0, &nodes)).collect(); + let mut root = match roots.len() { + 0 => Map::from_iter([("Node Type".to_string(), json!("Plan"))]), + 1 => roots[0].as_object().cloned().unwrap_or_default(), + _ => Map::from_iter([("Node Type".to_string(), json!("Plan")), ("Plans".to_string(), Value::Array(roots))]), + }; + root.extend(root_extra); + Value::Object(root) +} + +// ── Catalog ─────────────────────────────────────────────────────────────────── + +pub fn quote(ident: &str) -> String { + super::sql_util::quote_double(ident) +} + +fn database(h: &SnowflakeConn) -> String { + quote(h.cfg.database.trim()) +} + +fn table_ref(h: &SnowflakeConn, schema: &str, table: &str) -> String { + format!("{}.{}.{}", database(h), quote(schema), quote(table)) +} + +/// A column of a SHOW / DESCRIBE result, by name. +fn field(types: &[Value], row: &[Value], name: &str) -> String { + types + .iter() + .position(|t| t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))) + .and_then(|i| row.get(i)) + .map(|v| match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + }) + .unwrap_or_default() +} + +async fn show(h: &SnowflakeConn, sql: &str) -> Result<(Vec, Vec>), String> { + let (types, rows, _) = collect(h, sql, &Binds::default(), 100_000).await?; + Ok((types, rows)) +} + +pub async fn list_schemas(h: &SnowflakeConn) -> Result, String> { + let (t, rows) = show(h, &format!("SHOW SCHEMAS IN DATABASE {}", database(h))).await?; + let mut out: Vec = rows.iter().map(|r| field(&t, r, "name")).filter(|n| !n.is_empty() && n != "INFORMATION_SCHEMA").collect(); + out.sort(); + // The connection's schema first. + let first = opt(&h.cfg.schema).unwrap_or("PUBLIC").to_string(); + if let Some(i) = out.iter().position(|s| s.eq_ignore_ascii_case(&first)) { + let s = out.remove(i); + out.insert(0, s); + } + Ok(out) +} + +pub async fn list_tables(h: &SnowflakeConn, schema: &str) -> Result, String> { + let scope = format!("{}.{}", database(h), quote(schema)); + let (t, rows) = show(h, &format!("SHOW TABLES IN SCHEMA {scope}")).await?; + let mut out: Vec = rows + .iter() + .map(|r| TableInfo { + name: field(&t, r, "name"), + row_count: field(&t, r, "rows").parse().unwrap_or(-1), + kind: "table".into(), + rls_enabled: None, + created_at: None, + create_order: None, + system: None, + }) + .collect(); + if let Ok((vt, views)) = show(h, &format!("SHOW VIEWS IN SCHEMA {scope}")).await { + out.extend(views.iter().map(|r| TableInfo { + name: field(&vt, r, "name"), + row_count: -1, + kind: "view".into(), + rls_enabled: None, + created_at: None, + create_order: None, + system: None, + })); + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(out) +} + +/// (column, referenced table, referenced column, constraint) for each +/// foreign key column of `table`; `exported` gives the keys pointing at it, +/// as (referencing table, referencing column, column here, constraint). +async fn keys(h: &SnowflakeConn, schema: &str, table: &str, exported: bool) -> Vec<[String; 4]> { + let kind = if exported { "EXPORTED" } else { "IMPORTED" }; + let Ok((t, rows)) = show(h, &format!("SHOW {kind} KEYS IN TABLE {}", table_ref(h, schema, table))).await else { return vec![] }; + rows.iter() + .map(|r| { + if exported { + [field(&t, r, "fk_table_name"), field(&t, r, "fk_column_name"), field(&t, r, "pk_column_name"), field(&t, r, "fk_name")] + } else { + [field(&t, r, "fk_column_name"), field(&t, r, "pk_table_name"), field(&t, r, "pk_column_name"), field(&t, r, "fk_name")] + } + }) + .collect() +} + +pub async fn get_column_structure(h: &SnowflakeConn, schema: &str, table: &str) -> Result, String> { + let (t, rows) = show(h, &format!("DESCRIBE TABLE {}", table_ref(h, schema, table))).await?; + let fks = keys(h, schema, table, false).await; + Ok(rows + .iter() + .enumerate() + .map(|(i, r)| { + let name = field(&t, r, "name"); + let fk = fks.iter().find(|k| k[0] == name); + ColumnStructureRow { + ordinal_position: (i + 1) as i32, + data_type: field(&t, r, "type"), + is_nullable: field(&t, r, "null?") != "N", + column_default: Some(field(&t, r, "default")).filter(|d| !d.is_empty()), + foreign_key: fk.map(|k| format!("{}.{}", k[1], k[2])), + fk_constraint_name: fk.map(|k| k[3].clone()).filter(|n| !n.is_empty()), + comment: Some(field(&t, r, "comment")).filter(|d| !d.is_empty()), + is_primary_key: field(&t, r, "primary key") == "Y", + name, + } + }) + .collect()) +} + +pub async fn schema_column_structure(h: &SnowflakeConn, schema: &str) -> Result, String> { + use futures::stream::StreamExt; + let tables = list_tables(h, schema).await?; + let out: Vec = futures::stream::iter(tables.into_iter().take(300).map(|t| async move { + get_column_structure(h, schema, &t.name).await.ok().map(|columns| super::schema::TableColumnStructure { table: t.name, columns }) + })) + .buffered(6) + .filter_map(|x| async move { x }) + .collect() + .await; + Ok(out) +} + +pub async fn incoming_foreign_keys(h: &SnowflakeConn, schema: &str, table: &str) -> Result, String> { + let mut out: Vec = Vec::new(); + for [from_table, col, ref_col, name] in keys(h, schema, table, true).await { + match out.iter_mut().find(|f| f.from_table == from_table && f.constraint_name == name) { + Some(f) => { + f.from_columns.push(col); + f.to_columns.push(ref_col); + } + None => out.push(super::schema::IncomingForeignKey { + from_schema: schema.to_string(), + from_table, + from_columns: vec![col], + to_columns: vec![ref_col], + constraint_name: name, + }), + } + } + Ok(out) +} + +pub async fn get_ddl(h: &SnowflakeConn, schema: &str, table: &str) -> Result { + let mut b = Binds::default(); + let name = format!("{}.{}.{}", h.cfg.database.trim(), quote(schema), quote(table)); + b.text(&name); + let (_, rows, _) = collect(h, "SELECT GET_DDL('TABLE', ?, TRUE)", &b, 1).await?; + match rows.first().and_then(|r| r.first()) { + Some(Value::String(s)) => Ok(s.clone()), + _ => Err("Snowflake returned no DDL for this table".into()), + } +} + +// ── The grid ────────────────────────────────────────────────────────────────── + +fn base_type(ty: &str) -> String { + ty.trim().to_ascii_uppercase().split(['(', ' ']).next().unwrap_or("").to_string() +} + +fn as_text(col: &str, ty: &str) -> String { + match base_type(ty).as_str() { + "VARCHAR" | "TEXT" | "STRING" | "CHAR" | "CHARACTER" => col.to_string(), + "VARIANT" | "OBJECT" | "ARRAY" => format!("TO_JSON({col})"), + _ => format!("TO_VARCHAR({col})"), + } +} + +/// A grid value as a binding for a column, or NULL. +fn bind_value(ty: &str, v: &Value, b: &mut Binds) -> Result { + let base = base_type(ty); + Ok(match v { + Value::Null => "NULL".into(), + Value::Bool(x) => b.bind("BOOLEAN", x.to_string()).into(), + Value::Number(n) if n.is_i64() || n.is_u64() => b.bind("FIXED", n.to_string()).into(), + Value::Number(n) => b.bind("REAL", n.to_string()).into(), + Value::String(s) if matches!(base.as_str(), "VARIANT" | "OBJECT" | "ARRAY") => { + // Bound as text, parsed on Snowflake's side. + format!("PARSE_JSON({})", b.text(s)) + } + Value::String(s) => b.text(s).into(), + other if matches!(base.as_str(), "VARIANT" | "OBJECT" | "ARRAY") => format!("PARSE_JSON({})", b.text(&other.to_string())), + other => b.text(&other.to_string()).into(), + }) +} + +fn build_where(cols: &[ColumnStructureRow], search: Option<&str>, filters: Option<&[RowFilter]>, b: &mut Binds) -> String { + let by_name: HashMap<&str, &ColumnStructureRow> = cols.iter().map(|c| (c.name.as_str(), c)).collect(); + let mut clauses: Vec = Vec::new(); + if let Some(q) = search.map(str::trim).filter(|s| !s.is_empty()) { + let needle = format!("%{q}%"); + let ors: Vec = cols.iter().map(|c| format!("{} ILIKE {}", as_text("e(&c.name), &c.data_type), b.text(&needle))).collect(); + if !ors.is_empty() { + clauses.push(format!("({})", ors.join(" OR "))); + } + } + for f in filters.unwrap_or(&[]) { + let Some(c) = by_name.get(f.column.as_str()) else { continue }; + let col = quote(&c.name); + let v = f.value.as_deref().unwrap_or(""); + let text = as_text(&col, &c.data_type); + let clause = match f.op.as_str() { + "=" | "eq" | "!=" | "ne" | "neq" | ">" | "gt" | ">=" | "gte" | "<" | "lt" | "<=" | "lte" => { + let op = match f.op.as_str() { + "=" | "eq" => "=", + "!=" | "ne" | "neq" => "<>", + ">" | "gt" => ">", + ">=" | "gte" => ">=", + "<" | "lt" => "<", + _ => "<=", + }; + // Text is bound and Snowflake casts it to the column's type. + format!("{col} {op} {}", b.text(v)) + } + "contains" => format!("{text} ILIKE {}", b.text(&format!("%{v}%"))), + "not_contains" => format!("({col} IS NULL OR {text} NOT ILIKE {})", b.text(&format!("%{v}%"))), + "starts_with" => format!("{text} ILIKE {}", b.text(&format!("{v}%"))), + "ends_with" => format!("{text} ILIKE {}", b.text(&format!("%{v}"))), + "between" => { + let mut parts = v.splitn(2, ','); + let (a, z) = (parts.next().unwrap_or("").trim().to_string(), parts.next().unwrap_or("").trim().to_string()); + format!("{col} BETWEEN {} AND {}", b.text(&a), b.text(&z)) + } + "is_null" => format!("{col} IS NULL"), + "is_not_null" => format!("{col} IS NOT NULL"), + _ => continue, + }; + let joiner = if clauses.is_empty() { "" } else if f.conjunct.as_deref() == Some("or") { " OR " } else { " AND " }; + if joiner.is_empty() { + clauses.push(clause); + } else { + let last = clauses.pop().unwrap_or_default(); + clauses.push(format!("({last}{joiner}{clause})")); + } + } + if clauses.is_empty() { String::new() } else { format!(" WHERE {}", clauses.join(" AND ")) } +} + +#[allow(clippy::too_many_arguments)] +pub async fn get_table_rows( + h: &SnowflakeConn, + schema: &str, + table: &str, + limit: i64, + offset: i64, + search: Option, + sort_column: Option, + sort_direction: Option, + filters: Option>, +) -> Result { + let t0 = Instant::now(); + let cols = get_column_structure(h, schema, table).await?; + if cols.is_empty() { + return Err(format!("No table named {table}")); + } + let tref = table_ref(h, schema, table); + let mut b = Binds::default(); + let where_clause = build_where(&cols, search.as_deref(), filters.as_deref(), &mut b); + let order = match sort_column.as_deref().filter(|c| cols.iter().any(|x| x.name == *c)) { + Some(c) => { + let d = if sort_direction.as_deref().is_some_and(|d| d.eq_ignore_ascii_case("desc")) { "DESC" } else { "ASC" }; + format!(" ORDER BY {} {d}", quote(c)) + } + None => { + let pk: Vec = cols.iter().filter(|c| c.is_primary_key).map(|c| quote(&c.name)).collect(); + if pk.is_empty() { String::new() } else { format!(" ORDER BY {}", pk.join(", ")) } + } + }; + let (limit, offset) = (limit.max(0), offset.max(0)); + let data_sql = format!("SELECT * FROM {tref}{where_clause}{order} LIMIT {limit} OFFSET {offset}"); + let count_sql = format!("SELECT COUNT(*) FROM {tref}{where_clause}"); + let (data, count) = tokio::join!(collect(h, &data_sql, &b, limit as usize), collect(h, &count_sql, &b, 1)); + let (types, rows, _) = data?; + let total = count.ok().and_then(|(_, r, _)| r.first().and_then(|r| r.first()).and_then(|v| v.as_i64())).unwrap_or(rows.len() as i64); + let fks = cols + .iter() + .filter_map(|c| { + let (t, col) = c.foreign_key.as_ref()?.split_once('.')?; + Some(ForeignKeyInfo { columns: vec![c.name.clone()], referenced_schema: schema.to_string(), referenced_table: t.to_string(), referenced_columns: vec![col.to_string()] }) + }) + .collect(); + Ok(TableRows { + preview_columns: Vec::new(), + columns: columns_of(&types), + rows, + total, + query_ms: t0.elapsed().as_millis() as u64, + primary_key: cols.iter().filter(|c| c.is_primary_key).map(|c| c.name.clone()).collect(), + foreign_keys: fks, + sql: format!("{data_sql}\n{count_sql}"), + }) +} + +fn pk_where(cols: &[ColumnStructureRow], pk: &HashMap, b: &mut Binds) -> Result { + let keys: Vec<&ColumnStructureRow> = cols.iter().filter(|c| c.is_primary_key).collect(); + if keys.is_empty() { + return Err("This table declares no primary key, so the grid can't tell its rows apart. Use UPDATE or DELETE in the SQL console, or add a PRIMARY KEY constraint (Snowflake keeps it as metadata).".into()); + } + let mut parts = Vec::new(); + for c in keys { + let v = pk.get(&c.name).ok_or_else(|| format!("The row's {} is missing", c.name))?; + let col = quote(&c.name); + parts.push(if v.is_null() { format!("{col} IS NULL") } else { format!("{col} = {}", bind_value(&c.data_type, v, b)?) }); + } + Ok(parts.join(" AND ")) +} + +/// Rows a DML statement changed, from its one-row result. +async fn dml(h: &SnowflakeConn, sql: &str, b: &Binds) -> Result, String> { + let (_, rows, _) = collect(h, sql, b, 1).await?; + Ok(rows.first().and_then(|r| r.first()).and_then(|v| v.as_i64())) +} + +pub async fn update_table_cell( + h: &SnowflakeConn, + schema: &str, + table: &str, + primary_key: HashMap, + column: &str, + value: &Value, +) -> Result<(), String> { + let cols = get_column_structure(h, schema, table).await?; + let c = cols.iter().find(|c| c.name == column).ok_or_else(|| format!("No column named {column}"))?; + let mut b = Binds::default(); + let set = format!("{} = {}", quote(column), bind_value(&c.data_type, value, &mut b)?); + let w = pk_where(&cols, &primary_key, &mut b)?; + let sql = format!("UPDATE {} SET {set} WHERE {w}", table_ref(h, schema, table)); + match dml(h, &sql, &b).await? { + Some(1) | None => Ok(()), + Some(n) => Err(super::query::row_count_error(&primary_key.keys().cloned().collect::>(), &primary_key, n.max(0) as u64)), + } +} + +pub async fn insert_table_row(h: &SnowflakeConn, schema: &str, table: &str, values: HashMap) -> Result, String> { + let cols = get_column_structure(h, schema, table).await?; + let mut b = Binds::default(); + let mut names = Vec::new(); + let mut holes = Vec::new(); + for c in &cols { + let Some(v) = values.get(&c.name) else { continue }; + names.push(quote(&c.name)); + holes.push(bind_value(&c.data_type, v, &mut b)?); + } + if names.is_empty() { + return Err("Fill in at least one column".into()); + } + // VALUES can't hold PARSE_JSON; SELECT can, for VARIANT columns. + let sql = format!("INSERT INTO {} ({}) SELECT {}", table_ref(h, schema, table), names.join(", "), holes.join(", ")); + dml(h, &sql, &b).await?; + Ok(cols.iter().map(|c| values.get(&c.name).cloned().unwrap_or(Value::Null)).collect()) +} + +pub async fn delete_table_rows(h: &SnowflakeConn, schema: &str, table: &str, primary_keys: Vec>) -> Result { + if primary_keys.is_empty() { + return Ok(0); + } + let cols = get_column_structure(h, schema, table).await?; + let mut b = Binds::default(); + let mut ors = Vec::new(); + for pk in &primary_keys { + ors.push(format!("({})", pk_where(&cols, pk, &mut b)?)); + } + let sql = format!("DELETE FROM {} WHERE {}", table_ref(h, schema, table), ors.join(" OR ")); + Ok(dml(h, &sql, &b).await?.map(|n| n.max(0) as u64).unwrap_or(primary_keys.len() as u64)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_read_as_the_grid_shows_them() { + let t = |ty: &str| json!({ "type": ty, "scale": 0, "precision": 38 }); + assert_eq!(cell(&t("fixed"), json!("42")), json!(42)); + assert_eq!(cell(&json!({ "type": "fixed", "scale": 2 }), json!("12.50")), json!("12.50")); + assert_eq!(cell(&t("real"), json!("9.5")), json!(9.5)); + assert_eq!(cell(&t("boolean"), json!("true")), json!(true)); + assert_eq!(cell(&t("date"), json!("20413")), json!("2025-11-21")); + assert_eq!(cell(&t("time"), json!("45296.500000000")), json!("12:34:56.5")); + assert_eq!(cell(&t("timestamp_ntz"), json!("1795237200.000000000")), json!("2026-11-21 05:00:00")); + assert_eq!(cell(&t("timestamp_ltz"), json!("1795237200.250000000")), json!("2026-11-21 05:00:00.25 UTC")); + assert_eq!(cell(&t("timestamp_tz"), json!("1795237200.000000000 1500")), json!("2026-11-21 06:00:00 +01:00")); + assert_eq!(cell(&t("variant"), json!("{\"a\":1}")), json!({ "a": 1 })); + assert_eq!(cell(&t("text"), Value::Null), Value::Null); + } + + #[test] + fn types_label_like_snowflake() { + assert_eq!(type_label(&json!({ "type": "fixed", "precision": 38, "scale": 0 })), "NUMBER(38,0)"); + assert_eq!(type_label(&json!({ "type": "text", "length": 16777216 })), "VARCHAR"); + assert_eq!(type_label(&json!({ "type": "timestamp_tz" })), "TIMESTAMP_TZ"); + } + + #[test] + fn jwt_names_the_account_snowflake_s_way() { + assert_eq!(jwt_account("myorg-myaccount"), "MYORG-MYACCOUNT"); + assert_eq!(jwt_account("xy12345.us-east-2.aws"), "XY12345"); + assert_eq!(jwt_account("xy12345.snowflakecomputing.com"), "XY12345"); + } + + /// A 2048-bit test key, generated for this test only. + fn test_key() -> String { + let out = std::process::Command::new("openssl").args(["genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048"]).output(); + match out { + Ok(o) if o.status.success() => String::from_utf8(o.stdout).unwrap(), + _ => String::new(), + } + } + + #[test] + fn key_pair_jwt_carries_the_public_key_fingerprint() { + let pem = test_key(); + if pem.is_empty() { + return; // no openssl here + } + let jwt = sign_jwt("myorg-acct", "me", &pem, 1_700_000_000).unwrap(); + let claims: Value = serde_json::from_slice(&B64URL.decode(jwt.split('.').nth(1).unwrap()).unwrap()).unwrap(); + assert_eq!(claims["sub"], "MYORG-ACCT.ME"); + // The same fingerprint openssl computes over the public key's DER. + let dir = std::env::temp_dir().join(format!("stroke-sf-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let kp = dir.join("k.pem"); + std::fs::write(&kp, &pem).unwrap(); + let der = std::process::Command::new("openssl").args(["pkey", "-in", kp.to_str().unwrap(), "-pubout", "-outform", "DER"]).output().unwrap().stdout; + let fp = B64.encode(ring::digest::digest(&ring::digest::SHA256, &der).as_ref()); + assert_eq!(claims["iss"], format!("MYORG-ACCT.ME.SHA256:{fp}")); + assert_eq!(claims["exp"].as_u64().unwrap() - claims["iat"].as_u64().unwrap(), 3540); + let _ = std::fs::remove_dir_all(dir); + assert!(sign_jwt("a", "b", "-----BEGIN ENCRYPTED PRIVATE KEY-----\nAAAA\n-----END ENCRYPTED PRIVATE KEY-----", 0).unwrap_err().contains("encrypted")); + } + + #[test] + fn plans_nest_by_parent() { + let types: Vec = ["step", "id", "parent", "operation", "objects", "expressions", "partitionsTotal", "partitionsAssigned"] + .iter() + .map(|n| json!({ "name": n, "type": "text" })) + .collect(); + let row = |id: &str, parent: &str, op: &str, obj: &str| -> Vec { + vec![json!("1"), json!(id), if parent.is_empty() { Value::Null } else { json!(parent) }, json!(op), json!(obj), Value::Null, json!("4"), json!("2")] + }; + let rows = vec![ + vec![Value::Null, Value::Null, Value::Null, json!("GlobalStats"), Value::Null, Value::Null, json!("4"), json!("2")], + row("0", "", "Result", ""), + row("1", "0", "Filter", ""), + row("2", "1", "TableScan", "DB.PUBLIC.T"), + ]; + let p = plan_tree(&types, &rows); + assert_eq!(p["Node Type"], "Result"); + assert_eq!(p["partitionsTotal"], "4"); + assert_eq!(p["Plans"][0]["Plans"][0]["Relation Name"], "DB.PUBLIC.T"); + } + + #[test] + fn filters_bind_their_values() { + let col = |n: &str, t: &str| ColumnStructureRow { + ordinal_position: 1, name: n.into(), data_type: t.into(), is_nullable: true, column_default: None, + foreign_key: None, fk_constraint_name: None, comment: None, is_primary_key: false, + }; + let cols = vec![col("ID", "NUMBER(38,0)"), col("NAME", "VARCHAR(40)"), col("META", "VARIANT")]; + let mut b = Binds::default(); + let f = RowFilter { column: "ID".into(), op: ">=".into(), value: Some("2'; drop".into()), conjunct: None, data_type: None }; + let w = build_where(&cols, Some("an"), Some(&[f]), &mut b); + assert_eq!(w, " WHERE ((TO_VARCHAR(\"ID\") ILIKE ? OR \"NAME\" ILIKE ? OR TO_JSON(\"META\") ILIKE ?) AND \"ID\" >= ?)"); + assert_eq!(b.0["4"]["value"], "2'; drop"); + let mut b = Binds::default(); + assert_eq!(bind_value("VARIANT", &json!({ "k": 1 }), &mut b).unwrap(), "PARSE_JSON(?)"); + assert_eq!(bind_value("NUMBER(38,0)", &json!(7), &mut b).unwrap(), "?"); + assert_eq!(b.0["2"]["type"], "FIXED"); + } + + /// A stand-in for Snowflake's SQL API: answers a few statements the way + /// the API documents, with an asynchronous first reply, two partitions, + /// an error and a cancel. + #[tokio::test] + async fn against_a_stand_in_sql_api() { + use axum::{extract::{Path, Query, State}, http::StatusCode, routing::{get, post}, Json, Router}; + #[derive(Default)] + struct Mock { + polls: std::sync::atomic::AtomicUsize, + cancelled: std::sync::atomic::AtomicBool, + seen: Mutex>, + } + let mock = Arc::new(Mock::default()); + let rt = |name: &str, ty: &str| json!({ "name": name, "type": ty, "scale": 0, "precision": 38, "nullable": true }); + async fn submit_h(State(m): State>, Json(body): Json) -> (StatusCode, Json) { + m.seen.lock().unwrap().push(body.clone()); + let sql = body["statement"].as_str().unwrap_or(""); + if sql.contains("nope") { + return (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({ "code": "002003", "message": "SQL compilation error: Object 'NOPE' does not exist", "statementHandle": "h-err" }))); + } + let handle = if sql.starts_with("SELECT * FROM") { "h-big" } else if sql.contains("SYSTEM$WAIT") { "h-slow" } else { "h-small" }; + (StatusCode::ACCEPTED, Json(json!({ "statementHandle": handle, "message": "Asynchronous execution in progress." }))) + } + async fn status_h(State(m): State>, Path(handle): Path, Query(q): Query>) -> (StatusCode, Json) { + let rt = |name: &str, ty: &str| json!({ "name": name, "type": ty, "scale": 0, "precision": 38, "nullable": true }); + if handle == "h-slow" { + return (StatusCode::ACCEPTED, Json(json!({ "statementHandle": handle }))); + } + // The first poll says it's still running. + if m.polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { + return (StatusCode::ACCEPTED, Json(json!({ "statementHandle": handle }))); + } + match (handle.as_str(), q.get("partition").map(String::as_str)) { + ("h-big", Some("1")) => (StatusCode::OK, Json(json!({ "data": [["3", "ink", "20413"]] }))), + ("h-big", _) => (StatusCode::OK, Json(json!({ + "statementHandle": handle, + "resultSetMetaData": { "numRows": 3, "format": "jsonv2", "rowType": [rt("ID", "fixed"), rt("NAME", "text"), rt("D", "date")], + "partitionInfo": [{ "rowCount": 2 }, { "rowCount": 1 }] }, + "data": [["1", "pen", "20413"], ["2", null, null]], + }))), + _ => (StatusCode::OK, Json(json!({ + "statementHandle": handle, + "resultSetMetaData": { "numRows": 1, "rowType": [rt("1", "fixed")], "partitionInfo": [{ "rowCount": 1 }] }, + "data": [["1"]], + }))), + } + } + async fn cancel_h(State(m): State>, Path(_h): Path) -> Json { + m.cancelled.store(true, std::sync::atomic::Ordering::SeqCst); + Json(json!({ "message": "successfully canceled" })) + } + let _ = rt; + let app = Router::new() + .route("/api/v2/statements", post(submit_h)) + .route("/api/v2/statements/:handle", get(status_h)) + .route("/api/v2/statements/:handle/cancel", post(cancel_h)) + .with_state(mock.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let cfg = SnowflakeConfig { + name: "t".into(), + account: "myorg-acct".into(), + user: "me".into(), + auth: "token".into(), + private_key_file: None, + password: Some("pat-secret".into()), + warehouse: Some("WH".into()), + database: "DB".into(), + schema: Some("PUBLIC".into()), + role: None, + host: Some(format!("http://{addr}")), + }; + let h = connect(&cfg).await.unwrap(); + let seen = mock.seen.lock().unwrap()[0].clone(); + assert_eq!(seen["warehouse"], "WH"); + assert_eq!(seen["database"], "DB"); + assert_eq!(seen["schema"], "PUBLIC"); + + // Async reply, a poll that says running, then two partitions. + let r = query(&h, "SELECT * FROM T").await.unwrap(); + assert_eq!(r.rows.len(), 3); + assert_eq!(r.rows[0], vec![json!(1), json!("pen"), json!("2025-11-21")]); + assert_eq!(r.rows[2][1], json!("ink")); + assert_eq!(r.columns[0].data_type, "NUMBER(38,0)"); + + let e = query(&h, "SELECT nope").await.unwrap_err(); + assert!(e.contains("does not exist"), "{e}"); + + // Stop cancels the statement on the server. + let (tx, rx) = tokio::sync::oneshot::channel(); + let stop = super::super::stop::Stop::from_rx(rx); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + let _ = tx.send(()); + }); + let e = query_cancellable(&h, "CALL SYSTEM$WAIT(60)", &stop).await.unwrap_err(); + assert!(e.starts_with(super::super::query::QUERY_CANCELLED)); + assert!(mock.cancelled.load(std::sync::atomic::Ordering::SeqCst)); + } +} diff --git a/src-tauri/src/db/spanner.rs b/src-tauri/src/db/spanner.rs new file mode 100644 index 00000000..54a8609a --- /dev/null +++ b/src-tauri/src/db/spanner.rs @@ -0,0 +1,1355 @@ +//! Google Cloud Spanner over its REST API (v1). Beta. +//! +//! Sign-in comes from `google_auth`: a service account key, the gcloud login, +//! or the local emulator (no auth, `SPANNER_EMULATOR_HOST`-style host). +//! +//! - Reads run as single-use read-only queries (strong reads). +//! - INSERT, UPDATE and DELETE run in a read-write transaction that commits +//! when the statement succeeds. +//! - CREATE, ALTER and DROP go through the database's schema update, a +//! long-running operation this waits for. +//! +//! Both dialects work: GoogleSQL quotes identifiers with backticks and keeps +//! its tables in the unnamed schema (shown as `default`); PostgreSQL-dialect +//! databases quote with double quotes and use `public`. `information_schema` +//! answers the same lowercase column names in both. +//! +//! Values in the grid are bound as typed query parameters, never spliced into +//! the SQL text. + +use super::query::{ColumnInfo, ForeignKeyInfo, RowFilter, SqlResult, TableRows}; +use super::schema::{ColumnStructureRow, IndexInfo, TableInfo}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::collections::HashMap; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SpannerConfig { + pub name: String, + pub project_id: String, + pub instance_id: String, + pub database_id: String, + /// "serviceAccount", "gcloud" or "emulator". + #[serde(default = "default_auth")] + pub auth: String, + #[serde(default)] + pub key_file: Option, + /// The emulator's REST address, `localhost:9020` when blank. + #[serde(default)] + pub emulator_host: Option, +} + +fn default_auth() -> String { + "gcloud".into() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dialect { + GoogleSql, + Postgres, +} + +pub struct SpannerConn { + pub cfg: SpannerConfig, + pub dialect: Dialect, + /// One session for the connection, made on first use and made again when + /// Spanner forgets it (idle sessions expire after an hour). + session: tokio::sync::Mutex>, +} + +pub type SpannerHandle = Arc; + +/// What the schema switcher calls GoogleSQL's unnamed schema. +pub const DEFAULT_SCHEMA: &str = "default"; + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .timeout(Duration::from_secs(300)) + .connect_timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default() + }) +} + +fn base_url(cfg: &SpannerConfig) -> String { + if cfg.auth == "emulator" { + let h = cfg.emulator_host.as_deref().map(str::trim).filter(|h| !h.is_empty()).unwrap_or("localhost:9020"); + let h = h.trim_end_matches('/'); + if h.contains("://") { format!("{h}/v1") } else { format!("http://{h}/v1") } + } else { + "https://spanner.googleapis.com/v1".into() + } +} + +pub fn database_path(cfg: &SpannerConfig) -> String { + format!( + "projects/{}/instances/{}/databases/{}", + cfg.project_id.trim(), + cfg.instance_id.trim(), + cfg.database_id.trim() + ) +} + +/// One REST call. `path` is relative to `/v1`. +async fn call(cfg: &SpannerConfig, method: reqwest::Method, path: &str, body: Option<&Value>) -> Result { + let url = format!("{}/{}", base_url(cfg), path.trim_start_matches('/')); + let token = super::google_auth::token(&cfg.auth, cfg.key_file.as_deref(), super::google_auth::SCOPE_CLOUD_PLATFORM).await?; + let build = || { + let mut req = client().request(method.clone(), &url).bearer_auth(&token); + if let Some(b) = body { + req = req.json(b); + } + req + }; + // One retry when the request never got an answer (a dropped keep-alive + // connection). Safe to resend: DML carries its seqno and a commit its + // transaction id, so Spanner applies neither twice. + let sent = match build().send().await { + Err(e) if e.is_request() || e.is_connect() => { + tokio::time::sleep(Duration::from_millis(150)).await; + build().send().await + } + other => other, + }; + let resp = sent.map_err(|e| { + if e.is_connect() && cfg.auth == "emulator" { + format!("Could not reach the Spanner emulator at {}: is it running?", base_url(cfg)) + } else { + format!("Spanner request failed: {e}") + } + })?; + let status = resp.status(); + let text = resp.text().await.map_err(|e| e.to_string())?; + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if !status.is_success() || v.get("error").is_some() { + return Err(error_text(status.as_u16(), &v, &text)); + } + Ok(v) +} + +/// Google's error body (`{"error": {"message", "status"}}`), or the emulator's +/// flatter one (`{"code", "message"}`). +fn error_text(status: u16, v: &Value, raw: &str) -> String { + let e = v.get("error").unwrap_or(v); + let msg = e.get("message").and_then(|m| m.as_str()).unwrap_or(""); + let kind = e.get("status").and_then(|s| s.as_str()).unwrap_or(""); + match status { + 401 => "Google refused the credentials. Sign in again with gcloud, or check the key file.".into(), + 403 => format!("Not allowed on this database: {msg}"), + _ if !msg.is_empty() => { + if kind.is_empty() { format!("Spanner: {msg}") } else { format!("Spanner ({kind}): {msg}") } + } + _ => format!("Spanner error (HTTP {status}): {}", raw.chars().take(300).collect::()), + } +} + +fn is_session_gone(err: &str) -> bool { + err.contains("Session not found") || err.contains("NOT_FOUND") && err.contains("ession") +} + +pub async fn connect(cfg: &SpannerConfig) -> Result { + for (what, v) in [("project", &cfg.project_id), ("instance", &cfg.instance_id), ("database", &cfg.database_id)] { + if v.trim().is_empty() { + return Err(format!("Enter the Spanner {what}")); + } + } + let db = call(cfg, reqwest::Method::GET, &database_path(cfg), None).await?; + let dialect = match db.get("databaseDialect").and_then(|d| d.as_str()) { + Some("POSTGRESQL") => Dialect::Postgres, + _ => Dialect::GoogleSql, + }; + let h = Arc::new(SpannerConn { cfg: cfg.clone(), dialect, session: tokio::sync::Mutex::new(None) }); + session(&h).await?; + Ok(h) +} + +async fn session(h: &SpannerConn) -> Result { + let mut s = h.session.lock().await; + if let Some(name) = s.as_ref() { + return Ok(name.clone()); + } + let v = call(&h.cfg, reqwest::Method::POST, &format!("{}/sessions", database_path(&h.cfg)), Some(&json!({}))).await?; + let name = v.get("name").and_then(|n| n.as_str()).ok_or("Spanner did not return a session")?.to_string(); + *s = Some(name.clone()); + Ok(name) +} + +async fn forget_session(h: &SpannerConn) { + *h.session.lock().await = None; +} + +/// `session:executeSql`, made once more on a fresh session if Spanner forgot ours. +async fn execute(h: &SpannerConn, body: &Value) -> Result { + for attempt in 0..2 { + let s = session(h).await?; + match call(&h.cfg, reqwest::Method::POST, &format!("{s}:executeSql"), Some(body)).await { + Err(e) if attempt == 0 && is_session_gone(&e) => forget_session(h).await, + other => return other, + } + } + unreachable_err() +} + +fn unreachable_err() -> Result { + Err("Spanner kept losing the session".into()) +} + +pub async fn ping(h: &SpannerConn) -> Result<(), String> { + execute(h, &json!({ "sql": "SELECT 1" })).await.map(|_| ()) +} + +// ── Values ──────────────────────────────────────────────────────────────────── + +/// `ARRAY`, `STRUCT`, `INT64`: a column's type for the grid header. +fn type_label(t: &Value) -> String { + let code = t.get("code").and_then(|c| c.as_str()).unwrap_or("UNKNOWN"); + match code { + "ARRAY" => format!("ARRAY<{}>", t.get("arrayElementType").map(type_label).unwrap_or_default()), + other => other.to_string(), + } +} + +/// A Spanner value as the grid shows it. INT64 arrives as a string; it becomes +/// a number when it fits a double exactly. JSON arrives as text; it becomes +/// the object. Everything else stays as Spanner sent it. +fn cell(t: &Value, v: Value) -> Value { + if v.is_null() { + return v; + } + match t.get("code").and_then(|c| c.as_str()).unwrap_or("") { + "INT64" => match v.as_str().and_then(|s| s.parse::().ok()) { + Some(n) if n.unsigned_abs() <= (1u64 << 53) => json!(n), + _ => v, + }, + "JSON" => v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(v), + "ARRAY" => match (t.get("arrayElementType"), v) { + (Some(et), Value::Array(items)) => Value::Array(items.into_iter().map(|x| cell(et, x)).collect()), + (_, other) => other, + }, + _ => v, + } +} + +fn to_result(v: &Value, sql: &str, t0: Instant) -> SqlResult { + let fields = v["metadata"]["rowType"]["fields"].as_array().cloned().unwrap_or_default(); + let columns: Vec = fields + .iter() + .enumerate() + .map(|(i, f)| { + let name = f.get("name").and_then(|n| n.as_str()).filter(|n| !n.is_empty()).map(String::from).unwrap_or_else(|| format!("_{i}")); + ColumnInfo::new(name, type_label(&f["type"])) + }) + .collect(); + let rows: Vec> = v["rows"] + .as_array() + .map(|rows| { + rows.iter() + .map(|r| { + r.as_array() + .map(|cells| { + cells + .iter() + .zip(fields.iter()) + .map(|(c, f)| super::sql_util::cap_json_value("text", cell(&f["type"], c.clone()))) + .collect() + }) + .unwrap_or_default() + }) + .collect() + }) + .unwrap_or_default(); + let changed = v["stats"]["rowCountExact"].as_str().and_then(|s| s.parse::().ok()); + let (row_count, message) = if columns.is_empty() { + let n = changed.unwrap_or(0); + (Some(n), Some(format!("{n} row{} affected", if n == 1 { "" } else { "s" }))) + } else { + (Some(rows.len() as i64), None) + }; + SqlResult { columns, rows, row_count, message, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() } +} + +/// The parameter type Spanner wants for a column type (`STRING(MAX)` → +/// `STRING`). Arrays and structs can't be edited from a cell. +fn base_type(spanner_type: &str) -> String { + let t = spanner_type.trim().to_ascii_uppercase(); + let t = t.split('(').next().unwrap_or(&t).trim().to_string(); + // PostgreSQL-dialect spellings. + match t.as_str() { + "BIGINT" | "INT8" => "INT64".into(), + "DOUBLE PRECISION" | "FLOAT8" => "FLOAT64".into(), + "REAL" | "FLOAT4" => "FLOAT32".into(), + "BOOLEAN" => "BOOL".into(), + "CHARACTER VARYING" | "VARCHAR" | "TEXT" => "STRING".into(), + "BYTEA" => "BYTES".into(), + "TIMESTAMP WITH TIME ZONE" | "TIMESTAMPTZ" => "TIMESTAMP".into(), + "JSONB" => "JSON".into(), + _ => t, + } +} + +/// A cell's value as a Spanner query parameter: the JSON encoding Spanner +/// expects for its type (INT64, NUMERIC, dates and bytes as strings). +fn param(ty: &str, v: &Value) -> Result<(Value, Value), String> { + let code = base_type(ty); + if code.starts_with("ARRAY") || code.starts_with("STRUCT") { + return Err(format!("{ty} values can't be edited from the grid yet; use an UPDATE in the SQL console")); + } + let t = json!({ "code": code }); + if v.is_null() { + return Ok((Value::Null, t)); + } + let text = match v { + Value::String(s) => s.clone(), + other => other.to_string(), + }; + let encoded = match code.as_str() { + "BOOL" => match text.trim().to_ascii_lowercase().as_str() { + "true" | "t" | "1" | "yes" => json!(true), + "false" | "f" | "0" | "no" => json!(false), + _ => return Err(format!("\"{text}\" is not a BOOL")), + }, + "FLOAT64" | "FLOAT32" => match text.trim().parse::() { + Ok(f) if f.is_finite() => json!(f), + _ => json!(text.trim()), + }, + "INT64" => { + text.trim().parse::().map_err(|_| format!("\"{text}\" is not an INT64"))?; + json!(text.trim()) + } + "JSON" => match v { + Value::String(s) => json!(s), + other => json!(other.to_string()), + }, + _ => json!(text), + }; + Ok((encoded, t)) +} + +// ── Statements ──────────────────────────────────────────────────────────────── + +fn kind(stmt: &str) -> &'static str { + match super::sql_util::statement_head(stmt).as_str() { + "select" | "with" | "show" | "graph" | "@" => "read", + "insert" | "update" | "delete" => "dml", + "create" | "alter" | "drop" | "grant" | "revoke" | "rename" | "analyze" => "ddl", + _ => "read", + } +} + +/// Whether a console statement returns rows. +pub fn reads(stmt: &str) -> bool { + kind(stmt) == "read" +} + +async fn read(h: &SpannerConn, sql: &str, params: Option<(Map, Map)>) -> Result { + let mut body = json!({ "sql": sql }); + if let Some((p, t)) = params { + body["params"] = Value::Object(p); + body["paramTypes"] = Value::Object(t); + } + execute(h, &body).await +} + +/// A DML statement in its own read-write transaction, committed on success. +async fn dml(h: &SpannerConn, sql: &str, params: Option<(Map, Map)>) -> Result { + for attempt in 0..2 { + let s = session(h).await?; + let begun = call(&h.cfg, reqwest::Method::POST, &format!("{s}:beginTransaction"), Some(&json!({ "options": { "readWrite": {} } }))).await; + let tx = match begun { + Err(e) if attempt == 0 && is_session_gone(&e) => { + forget_session(h).await; + continue; + } + other => other?, + }; + let id = tx.get("id").and_then(|i| i.as_str()).ok_or("Spanner did not start a transaction")?.to_string(); + let mut body = json!({ "sql": sql, "transaction": { "id": id }, "seqno": "1" }); + if let Some((p, t)) = params.clone() { + body["params"] = Value::Object(p); + body["paramTypes"] = Value::Object(t); + } + let out = call(&h.cfg, reqwest::Method::POST, &format!("{s}:executeSql"), Some(&body)).await; + match out { + Ok(v) => { + call(&h.cfg, reqwest::Method::POST, &format!("{s}:commit"), Some(&json!({ "transactionId": id }))).await?; + return Ok(v); + } + Err(e) => { + let _ = call(&h.cfg, reqwest::Method::POST, &format!("{s}:rollback"), Some(&json!({ "transactionId": id }))).await; + return Err(e); + } + } + } + unreachable_err() +} + +/// Schema statements through the database's DDL update; waits for the +/// long-running operation (seconds on Spanner, at once on the emulator). +async fn ddl(h: &SpannerConn, statements: Vec) -> Result<(), String> { + let mut op = call( + &h.cfg, + reqwest::Method::PATCH, + &format!("{}/ddl", database_path(&h.cfg)), + Some(&json!({ "statements": statements })), + ) + .await?; + let deadline = Instant::now() + Duration::from_secs(600); + while op.get("done").and_then(|d| d.as_bool()) != Some(true) { + if Instant::now() > deadline { + return Err("The schema change is still running on Spanner; check the database in a minute".into()); + } + tokio::time::sleep(Duration::from_millis(800)).await; + let name = op.get("name").and_then(|n| n.as_str()).ok_or("Spanner did not name the schema operation")?.to_string(); + op = call(&h.cfg, reqwest::Method::GET, &name, None).await?; + } + if let Some(e) = op.get("error") { + return Err(format!("Spanner rejected the schema change: {}", e.get("message").and_then(|m| m.as_str()).unwrap_or("unknown error"))); + } + Ok(()) +} + +/// Run one statement, the console's way: reads come back as rows, DML says +/// how many rows changed, DDL says it was applied. +/// Backtick-quoted names → double-quoted ones, for a PostgreSQL-dialect +/// database. The app quotes Spanner names GoogleSQL's way (it can't know the +/// dialect before connecting), and a backtick is never valid PostgreSQL, so +/// outside strings, comments and quoted names this only ever fixes a name. +fn pg_quotes(sql: &str) -> String { + let mut out = String::with_capacity(sql.len()); + let mut it = sql.chars().peekable(); + while let Some(c) = it.next() { + match c { + '\'' | '"' => { + out.push(c); + while let Some(d) = it.next() { + out.push(d); + if d == c { + if it.peek() == Some(&c) { + out.push(it.next().unwrap()); + } else { + break; + } + } + } + } + '-' if it.peek() == Some(&'-') => { + out.push(c); + for d in it.by_ref() { + out.push(d); + if d == '\n' { + break; + } + } + } + '/' if it.peek() == Some(&'*') => { + out.push(c); + out.push(it.next().unwrap()); + let mut prev = ' '; + for d in it.by_ref() { + out.push(d); + if prev == '*' && d == '/' { + break; + } + prev = d; + } + } + '`' => { + out.push('"'); + while let Some(d) = it.next() { + match d { + '`' if it.peek() == Some(&'`') => { + it.next(); + out.push('`'); + } + '`' => break, + '"' => out.push_str("\"\""), + _ => out.push(d), + } + } + out.push('"'); + } + _ => out.push(c), + } + } + out +} + +/// The statement as this database's dialect reads it. +fn dialect_sql(h: &SpannerConn, sql: &str) -> String { + if h.dialect == Dialect::Postgres && sql.contains('`') { + pg_quotes(sql) + } else { + sql.to_string() + } +} + +pub async fn query(h: &SpannerConn, stmt: &str) -> Result { + let t0 = Instant::now(); + let fixed = dialect_sql(h, stmt); + let sql = fixed.trim().trim_end_matches(';').trim(); + if sql.is_empty() { + return Err("Query is empty".into()); + } + match kind(sql) { + "dml" => Ok(to_result(&dml(h, sql, None).await?, sql, t0)), + "ddl" => { + ddl(h, vec![sql.to_string()]).await?; + Ok(SqlResult { columns: vec![], rows: vec![], row_count: Some(0), message: Some("Schema updated".into()), query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) + } + _ => Ok(to_result(&read(h, sql, None).await?, sql, t0)), + } +} + +// ── Plans ───────────────────────────────────────────────────────────────────── + +/// A query's plan in PLAN mode (nothing runs), as the plan view's tree. +pub async fn explain_plan(h: &SpannerConn, sql: &str) -> Result { + let fixed = dialect_sql(h, sql); + let sql = fixed.trim().trim_end_matches(';').trim(); + let sql = sql.strip_prefix("EXPLAIN ").or_else(|| sql.strip_prefix("explain ")).unwrap_or(sql); + let v = execute(h, &json!({ "sql": sql, "queryMode": "PLAN" })).await?; + let nodes = v["stats"]["queryPlan"]["planNodes"].as_array().cloned().unwrap_or_default(); + if nodes.is_empty() { + return Err("Spanner returned no plan for this statement".into()); + } + Ok(plan_tree(&nodes, 0, 0)) +} + +/// Spanner's flat plan nodes (indexed, with child links) → nested nodes. +/// Scalar nodes (expressions) fold into their parent's details. +pub fn plan_tree(nodes: &[Value], index: usize, depth: usize) -> Value { + let n = &nodes[index.min(nodes.len().saturating_sub(1))]; + let name = n.get("displayName").and_then(|d| d.as_str()).unwrap_or("Step"); + let meta = n.get("metadata").cloned().unwrap_or(Value::Null); + let mut out = Map::new(); + let label = match meta.get("scan_type").and_then(|s| s.as_str()) { + Some(scan) => format!("{name} ({scan})"), + None => match meta.get("call_type").and_then(|s| s.as_str()) { + Some(call) => format!("{name} ({call})"), + None => name.to_string(), + }, + }; + out.insert("Node Type".into(), json!(label)); + if let Some(t) = meta.get("scan_target").and_then(|s| s.as_str()) { + out.insert("Relation Name".into(), json!(t)); + } + let mut conditions: Vec = Vec::new(); + let mut kids: Vec = Vec::new(); + if depth < 64 { + for link in n.get("childLinks").and_then(|c| c.as_array()).into_iter().flatten() { + let Some(ci) = link.get("childIndex").and_then(|c| c.as_u64()).map(|c| c as usize) else { continue }; + let Some(child) = nodes.get(ci) else { continue }; + if child.get("kind").and_then(|k| k.as_str()) == Some("SCALAR") { + if let Some(desc) = child.get("shortRepresentation").and_then(|s| s.get("description")).and_then(|d| d.as_str()) { + let role = link.get("type").and_then(|t| t.as_str()).unwrap_or(""); + conditions.push(if role.is_empty() { desc.to_string() } else { format!("{role}: {desc}") }); + } + continue; + } + kids.push(plan_tree(nodes, ci, depth + 1)); + } + } + if !conditions.is_empty() { + out.insert("Filter".into(), json!(conditions.join(", "))); + } + if !kids.is_empty() { + out.insert("Plans".into(), Value::Array(kids)); + } + Value::Object(out) +} + +// ── Identifiers and schemas ─────────────────────────────────────────────────── + +pub fn quote_ident(h: &SpannerConn, ident: &str) -> String { + match h.dialect { + Dialect::GoogleSql => super::sql_util::quote_backtick(ident), + Dialect::Postgres => super::sql_util::quote_double(ident), + } +} + +/// The schema as `information_schema` names it: GoogleSQL's unnamed one is ''. +fn schema_key(h: &SpannerConn, schema: &str) -> String { + let s = schema.trim(); + match h.dialect { + Dialect::GoogleSql if s.is_empty() || s == DEFAULT_SCHEMA => String::new(), + Dialect::Postgres if s.is_empty() => "public".into(), + _ => s.to_string(), + } +} + +pub(crate) fn table_ref(h: &SpannerConn, schema: &str, table: &str) -> String { + let key = schema_key(h, schema); + if key.is_empty() || (h.dialect == Dialect::Postgres && key == "public") { + quote_ident(h, table) + } else { + format!("{}.{}", quote_ident(h, &key), quote_ident(h, table)) + } +} + +/// Parameters as `@p` (GoogleSQL) or `$1` (PostgreSQL dialect), with types. +struct Params { + dialect: Dialect, + values: Map, + types: Map, +} + +impl Params { + fn new(dialect: Dialect) -> Self { + Self { dialect, values: Map::new(), types: Map::new() } + } + /// Bind `v`, returning the placeholder to put in the SQL. + fn bind(&mut self, value: Value, ty: Value) -> String { + let n = self.values.len() + 1; + let (key, placeholder) = match self.dialect { + Dialect::GoogleSql => (format!("p{n}"), format!("@p{n}")), + Dialect::Postgres => (format!("p{n}"), format!("${n}")), + }; + self.values.insert(key.clone(), value); + self.types.insert(key, ty); + placeholder + } + fn string(&mut self, s: &str) -> String { + self.bind(json!(s), json!({ "code": "STRING" })) + } + fn take(self) -> Option<(Map, Map)> { + if self.values.is_empty() { None } else { Some((self.values, self.types)) } + } +} + +fn text_of(r: &SqlResult, row: &[Value], name: &str) -> String { + r.columns + .iter() + .position(|c| c.name.eq_ignore_ascii_case(name)) + .and_then(|i| row.get(i)) + .map(|v| match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + }) + .unwrap_or_default() +} + +async fn catalog(h: &SpannerConn, sql: &str, p: Params) -> Result { + let t0 = Instant::now(); + Ok(to_result(&read(h, sql, p.take()).await?, sql, t0)) +} + +pub async fn list_schemas(h: &SpannerConn) -> Result, String> { + let r = catalog( + h, + "SELECT schema_name FROM information_schema.schemata ORDER BY schema_name", + Params::new(h.dialect), + ) + .await?; + let hidden = ["information_schema", "spanner_sys", "pg_catalog"]; + let mut out: Vec = r + .rows + .iter() + .map(|row| text_of(&r, row, "schema_name")) + .filter(|s| !hidden.contains(&s.to_ascii_lowercase().as_str())) + .map(|s| if s.is_empty() { DEFAULT_SCHEMA.to_string() } else { s }) + .collect(); + if out.is_empty() { + out.push(if h.dialect == Dialect::Postgres { "public".into() } else { DEFAULT_SCHEMA.into() }); + } + Ok(out) +} + +pub async fn list_tables(h: &SpannerConn, schema: &str) -> Result, String> { + let mut p = Params::new(h.dialect); + let s = p.string(&schema_key(h, schema)); + let sql = format!("SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = {s} ORDER BY table_name"); + let r = catalog(h, &sql, p).await?; + Ok(r.rows + .iter() + .map(|row| { + let ty = text_of(&r, row, "table_type").to_ascii_uppercase(); + TableInfo { + name: text_of(&r, row, "table_name"), + row_count: -1, + kind: if ty.contains("VIEW") { "view".into() } else { "table".into() }, + rls_enabled: None, + created_at: None, + create_order: None, + system: None, + } + }) + .collect()) +} + +/// Columns of one table, or of every table in the schema, with primary and +/// foreign keys filled in. Returns (table, column) pairs in table order. +async fn columns_in(h: &SpannerConn, schema: &str, table: Option<&str>) -> Result, String> { + let key = schema_key(h, schema); + let mut p = Params::new(h.dialect); + let s = p.string(&key); + let mut cols_sql = format!( + "SELECT table_name, column_name, ordinal_position, spanner_type, is_nullable, column_default \ + FROM information_schema.columns WHERE table_schema = {s}" + ); + if let Some(t) = table { + let tp = p.string(t); + cols_sql.push_str(&format!(" AND table_name = {tp}")); + } + cols_sql.push_str(" ORDER BY table_name, ordinal_position"); + let cols = catalog(h, &cols_sql, p).await?; + + let mut p = Params::new(h.dialect); + let s = p.string(&key); + let pk_sql = format!( + "SELECT table_name, column_name FROM information_schema.index_columns \ + WHERE table_schema = {s} AND index_type = 'PRIMARY_KEY'" + ); + let pks = catalog(h, &pk_sql, p).await.unwrap_or_else(|_| SqlResult { columns: vec![], rows: vec![], row_count: None, message: None, query_ms: 0, sql: String::new() }); + let pk_set: std::collections::HashSet<(String, String)> = + pks.rows.iter().map(|r| (text_of(&pks, r, "table_name"), text_of(&pks, r, "column_name"))).collect(); + + let fks = foreign_keys_in(h, schema).await.unwrap_or_default(); + + Ok(cols + .rows + .iter() + .enumerate() + .map(|(i, row)| { + let t = text_of(&cols, row, "table_name"); + let name = text_of(&cols, row, "column_name"); + let ty = text_of(&cols, row, "spanner_type"); + let default = Some(text_of(&cols, row, "column_default")).filter(|d| !d.is_empty()); + let ordinal = text_of(&cols, row, "ordinal_position").parse::().unwrap_or((i + 1) as i32); + let fk = fks.iter().find(|f| f.0 == t && f.1 == name); + ( + t.clone(), + ColumnStructureRow { + ordinal_position: ordinal, + name: name.clone(), + data_type: ty, + is_nullable: text_of(&cols, row, "is_nullable").eq_ignore_ascii_case("YES"), + column_default: default, + foreign_key: fk.map(|f| format!("{}.{}", f.2, f.3)), + fk_constraint_name: fk.map(|f| f.4.clone()), + is_primary_key: pk_set.contains(&(t, name)), + comment: None, + }, + ) + }) + .collect()) +} + +/// (table, column, referenced table, referenced column, constraint) per FK column. +async fn foreign_keys_in(h: &SpannerConn, schema: &str) -> Result, String> { + let mut p = Params::new(h.dialect); + let s = p.string(&schema_key(h, schema)); + let sql = format!( + "SELECT kcu.table_name, kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column, tc.constraint_name \ + FROM information_schema.table_constraints AS tc \ + JOIN information_schema.key_column_usage AS kcu \ + ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema \ + JOIN information_schema.constraint_column_usage AS ccu \ + ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema \ + WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = {s}" + ); + let r = catalog(h, &sql, p).await?; + let mut out: Vec<(String, String, String, String, String)> = r + .rows + .iter() + .map(|row| { + ( + text_of(&r, row, "table_name"), + text_of(&r, row, "column_name"), + text_of(&r, row, "ref_table"), + text_of(&r, row, "ref_column"), + text_of(&r, row, "constraint_name"), + ) + }) + .collect(); + out.extend(interleave_links(h, schema).await.unwrap_or_default()); + Ok(out) +} + +/// Interleaved tables as relations. Spanner keeps a child's rows inside its +/// parent's (`INTERLEAVE IN PARENT`) instead of declaring a foreign key, so a +/// schema built that way, the usual Spanner design, showed no relations at +/// all. A child's primary key starts with its parent's key columns under the +/// same names, which makes each of them a link to the parent. +async fn interleave_links(h: &SpannerConn, schema: &str) -> Result, String> { + let mut p = Params::new(h.dialect); + let s = p.string(&schema_key(h, schema)); + let parents = catalog( + h, + &format!("SELECT table_name, parent_table_name FROM information_schema.tables WHERE table_schema = {s} AND parent_table_name IS NOT NULL"), + p, + ) + .await?; + if parents.rows.is_empty() { + return Ok(vec![]); + } + let mut p = Params::new(h.dialect); + let s = p.string(&schema_key(h, schema)); + let keys = catalog( + h, + &format!("SELECT table_name, column_name, ordinal_position FROM information_schema.index_columns WHERE table_schema = {s} AND index_type = 'PRIMARY_KEY' ORDER BY table_name, ordinal_position"), + p, + ) + .await?; + let key_of = |t: &str| -> Vec { + keys.rows.iter().filter(|r| text_of(&keys, r, "table_name") == t).map(|r| text_of(&keys, r, "column_name")).collect() + }; + let mut out = Vec::new(); + for row in &parents.rows { + let child = text_of(&parents, row, "table_name"); + let parent = text_of(&parents, row, "parent_table_name"); + if child.is_empty() || parent.is_empty() { + continue; + } + let child_key = key_of(&child); + for col in key_of(&parent) { + if child_key.contains(&col) { + out.push((child.clone(), col.clone(), parent.clone(), col, format!("INTERLEAVE_{child}"))); + } + } + } + Ok(out) +} + +/// Foreign keys in this schema that point at `table`, for the grid's +/// "referenced by" jumps. +pub async fn incoming_foreign_keys(h: &SpannerConn, schema: &str, table: &str) -> Result, String> { + let mut by_fk: Vec = Vec::new(); + for (from_table, col, ref_table, ref_col, name) in foreign_keys_in(h, schema).await? { + if ref_table != table { + continue; + } + let i = match by_fk.iter().position(|f| f.from_table == from_table && f.constraint_name == name) { + Some(i) => i, + None => { + by_fk.push(super::schema::IncomingForeignKey { + from_schema: schema.to_string(), + from_table, + from_columns: vec![], + to_columns: vec![], + constraint_name: name, + }); + by_fk.len() - 1 + } + }; + let fk = &mut by_fk[i]; + if !fk.from_columns.contains(&col) { + fk.from_columns.push(col); + fk.to_columns.push(ref_col); + } + } + Ok(by_fk) +} + +pub async fn get_column_structure(h: &SpannerConn, schema: &str, table: &str) -> Result, String> { + Ok(columns_in(h, schema, Some(table)).await?.into_iter().map(|(_, c)| c).collect()) +} + +pub async fn schema_column_structure(h: &SpannerConn, schema: &str) -> Result, String> { + let mut out: Vec = Vec::new(); + for (table, col) in columns_in(h, schema, None).await? { + match out.last_mut() { + Some(last) if last.table == table => last.columns.push(col), + _ => out.push(super::schema::TableColumnStructure { table, columns: vec![col] }), + } + } + Ok(out) +} + +pub async fn list_indexes(h: &SpannerConn, schema: &str) -> Result, String> { + let key = schema_key(h, schema); + let mut p = Params::new(h.dialect); + let s = p.string(&key); + let sql = format!( + "SELECT table_name, index_name, index_type, is_unique FROM information_schema.indexes \ + WHERE table_schema = {s} ORDER BY table_name, index_name" + ); + let idx = catalog(h, &sql, p).await?; + let mut p = Params::new(h.dialect); + let s = p.string(&key); + let sql = format!( + "SELECT table_name, index_name, column_name, ordinal_position FROM information_schema.index_columns \ + WHERE table_schema = {s} AND ordinal_position IS NOT NULL ORDER BY table_name, index_name, ordinal_position" + ); + let cols = catalog(h, &sql, p).await?; + let mut by_index: HashMap<(String, String), Vec> = HashMap::new(); + for row in &cols.rows { + by_index + .entry((text_of(&cols, row, "table_name"), text_of(&cols, row, "index_name"))) + .or_default() + .push(text_of(&cols, row, "column_name")); + } + Ok(idx + .rows + .iter() + .map(|row| { + let table = text_of(&idx, row, "table_name"); + let name = text_of(&idx, row, "index_name"); + let kind = text_of(&idx, row, "index_type"); + let unique = matches!(text_of(&idx, row, "is_unique").to_ascii_lowercase().as_str(), "true" | "yes"); + let columns = by_index.get(&(table.clone(), name.clone())).cloned().unwrap_or_default().join(", "); + IndexInfo { + is_primary: kind == "PRIMARY_KEY", + name: if kind == "PRIMARY_KEY" { "PRIMARY_KEY".into() } else { name }, + table_name: table, + columns, + index_type: kind.to_ascii_lowercase(), + is_unique: unique || kind == "PRIMARY_KEY", + condition: None, + comment: None, + } + }) + .collect()) +} + +/// The table's DDL as Spanner keeps it: its CREATE TABLE and its indexes. +pub async fn get_ddl(h: &SpannerConn, _schema: &str, table: &str) -> Result { + let v = call(&h.cfg, reqwest::Method::GET, &format!("{}/ddl", database_path(&h.cfg)), None).await?; + let lower = table.to_ascii_lowercase(); + let names = [format!(" {lower} "), format!(" {lower}("), format!("`{lower}`"), format!("\"{lower}\""), format!(" {lower}\n")]; + let mine: Vec = v["statements"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str()) + .filter(|s| { + let l = format!("{} ", s.to_ascii_lowercase()); + let head = l.split('(').next().unwrap_or(&l).to_string(); + names.iter().any(|n| head.contains(n.as_str()) || l.contains(&format!(" on {lower}")) || l.contains(&format!(" on `{lower}`"))) + }) + .map(|s| format!("{};", s.trim_end_matches(';'))) + .collect(); + Ok(mine.join("\n\n")) +} + +// ── The grid ────────────────────────────────────────────────────────────────── + +/// A column as text for search and contains-filters. +fn as_text(h: &SpannerConn, col: &str, ty: &str) -> String { + let base = base_type(ty); + match h.dialect { + Dialect::Postgres => format!("CAST({col} AS text)"), + Dialect::GoogleSql if base == "STRING" => col.to_string(), + Dialect::GoogleSql if base.starts_with("ARRAY") || base.starts_with("STRUCT") || base == "JSON" || base == "BYTES" => { + format!("TO_JSON_STRING({col})") + } + Dialect::GoogleSql => format!("CAST({col} AS STRING)"), + } +} + +fn build_where(h: &SpannerConn, cols: &[ColumnStructureRow], search: Option<&str>, filters: Option<&[RowFilter]>, p: &mut Params) -> String { + let by_name: HashMap<&str, &ColumnStructureRow> = cols.iter().map(|c| (c.name.as_str(), c)).collect(); + let mut clauses: Vec = Vec::new(); + if let Some(q) = search.map(str::trim).filter(|s| !s.is_empty()) { + let needle = p.string(&format!("%{}%", q.to_lowercase())); + let ors: Vec = + cols.iter().map(|c| format!("LOWER({}) LIKE {needle}", as_text(h, "e_ident(h, &c.name), &c.data_type))).collect(); + if !ors.is_empty() { + clauses.push(format!("({})", ors.join(" OR "))); + } + } + for f in filters.unwrap_or(&[]) { + let Some(c) = by_name.get(f.column.as_str()) else { continue }; + let col = quote_ident(h, &c.name); + let v = f.value.as_deref().unwrap_or(""); + let typed = |p: &mut Params, raw: &str| -> Option { param(&c.data_type, &json!(raw)).ok().map(|(val, t)| p.bind(val, t)) }; + let text = as_text(h, &col, &c.data_type); + let clause = match f.op.as_str() { + "=" | "eq" | "!=" | "ne" | "neq" | ">" | "gt" | ">=" | "gte" | "<" | "lt" | "<=" | "lte" => { + let op = match f.op.as_str() { + "=" | "eq" => "=", + "!=" | "ne" | "neq" => "!=", + ">" | "gt" => ">", + ">=" | "gte" => ">=", + "<" | "lt" => "<", + _ => "<=", + }; + match typed(p, v) { + Some(ph) => format!("{col} {op} {ph}"), + None => continue, + } + } + "contains" => format!("LOWER({text}) LIKE {}", p.string(&format!("%{}%", v.to_lowercase()))), + "not_contains" => format!("({col} IS NULL OR NOT LOWER({text}) LIKE {})", p.string(&format!("%{}%", v.to_lowercase()))), + "starts_with" => format!("LOWER({text}) LIKE {}", p.string(&format!("{}%", v.to_lowercase()))), + "ends_with" => format!("LOWER({text}) LIKE {}", p.string(&format!("%{}", v.to_lowercase()))), + "between" => { + let mut parts = v.splitn(2, ','); + let (a, b) = (parts.next().unwrap_or("").trim().to_string(), parts.next().unwrap_or("").trim().to_string()); + match (typed(p, &a), typed(p, &b)) { + (Some(x), Some(y)) => format!("{col} BETWEEN {x} AND {y}"), + _ => continue, + } + } + "is_null" => format!("{col} IS NULL"), + "is_not_null" => format!("{col} IS NOT NULL"), + _ => continue, + }; + let joiner = if clauses.is_empty() { "" } else if f.conjunct.as_deref() == Some("or") { " OR " } else { " AND " }; + if joiner.is_empty() { + clauses.push(clause); + } else { + let last = clauses.pop().unwrap_or_default(); + clauses.push(format!("({last}{joiner}{clause})")); + } + } + if clauses.is_empty() { String::new() } else { format!(" WHERE {}", clauses.join(" AND ")) } +} + +#[allow(clippy::too_many_arguments)] +pub async fn get_table_rows( + h: &SpannerConn, + schema: &str, + table: &str, + limit: i64, + offset: i64, + search: Option, + sort_column: Option, + sort_direction: Option, + filters: Option>, +) -> Result { + let t0 = Instant::now(); + let cols = get_column_structure(h, schema, table).await?; + if cols.is_empty() { + return Err(format!("No table named {table}")); + } + let tref = table_ref(h, schema, table); + let mut p = Params::new(h.dialect); + let where_clause = build_where(h, &cols, search.as_deref(), filters.as_deref(), &mut p); + let order = match sort_column.as_deref().filter(|c| cols.iter().any(|x| x.name == *c)) { + Some(c) => { + let d = if sort_direction.as_deref().is_some_and(|d| d.eq_ignore_ascii_case("desc")) { "DESC" } else { "ASC" }; + format!(" ORDER BY {} {d}", quote_ident(h, c)) + } + None => { + // A stable page order: the primary key. + let pk: Vec = cols.iter().filter(|c| c.is_primary_key).map(|c| quote_ident(h, &c.name)).collect(); + if pk.is_empty() { String::new() } else { format!(" ORDER BY {}", pk.join(", ")) } + } + }; + let (limit, offset) = (limit.max(0), offset.max(0)); + let data_sql = format!("SELECT * FROM {tref}{where_clause}{order} LIMIT {limit} OFFSET {offset}"); + let count_sql = format!("SELECT COUNT(*) AS n FROM {tref}{where_clause}"); + let params = p.take(); + let (data, count) = tokio::join!(read(h, &data_sql, params.clone()), read(h, &count_sql, params)); + let result = to_result(&data?, &data_sql, t0); + let total = count?["rows"][0][0].as_str().and_then(|s| s.parse::().ok()).unwrap_or(result.rows.len() as i64); + let fks: Vec = cols + .iter() + .filter_map(|c| { + let target = c.foreign_key.as_ref()?; + let (t, col) = target.split_once('.')?; + Some(ForeignKeyInfo { + columns: vec![c.name.clone()], + referenced_schema: schema.to_string(), + referenced_table: t.to_string(), + referenced_columns: vec![col.to_string()], + }) + }) + .collect(); + Ok(TableRows { + preview_columns: Vec::new(), + columns: result.columns, + rows: result.rows, + total, + query_ms: t0.elapsed().as_millis() as u64, + primary_key: cols.iter().filter(|c| c.is_primary_key).map(|c| c.name.clone()).collect(), + foreign_keys: fks, + sql: format!("{data_sql}\n{count_sql}"), + }) +} + +pub async fn count_rows(h: &SpannerConn, schema: &str, table: &str) -> Result { + let sql = format!("SELECT COUNT(*) FROM {}", table_ref(h, schema, table)); + let v = read(h, &sql, None).await?; + Ok(v["rows"][0][0].as_str().and_then(|s| s.parse::().ok()).unwrap_or(0)) +} + +fn column_types(cols: &[ColumnStructureRow]) -> HashMap { + cols.iter().map(|c| (c.name.clone(), c.data_type.clone())).collect() +} + +fn pk_where(h: &SpannerConn, types: &HashMap, pk: &HashMap, p: &mut Params) -> Result { + if pk.is_empty() { + return Err("Spanner needs the row's primary key to change it".into()); + } + let mut parts = Vec::new(); + for (k, v) in pk { + let ty = types.get(k).ok_or_else(|| format!("No column named {k}"))?; + let (val, t) = param(ty, v)?; + parts.push(format!("{} = {}", quote_ident(h, k), p.bind(val, t))); + } + Ok(parts.join(" AND ")) +} + +pub async fn update_table_cell( + h: &SpannerConn, + schema: &str, + table: &str, + primary_key: HashMap, + column: &str, + value: &Value, +) -> Result<(), String> { + let cols = get_column_structure(h, schema, table).await?; + let types = column_types(&cols); + let ty = types.get(column).ok_or_else(|| format!("No column named {column}"))?; + let mut p = Params::new(h.dialect); + let (val, t) = param(ty, value)?; + let set = format!("{} = {}", quote_ident(h, column), p.bind(val, t)); + let w = pk_where(h, &types, &primary_key, &mut p)?; + let sql = format!("UPDATE {} SET {set} WHERE {w}", table_ref(h, schema, table)); + let v = dml(h, &sql, p.take()).await?; + match v["stats"]["rowCountExact"].as_str() { + Some("1") => Ok(()), + Some(n) => Err(super::query::row_count_error(&primary_key.keys().cloned().collect::>(), &primary_key, n.parse().unwrap_or(0))), + None => Ok(()), + } +} + +pub async fn insert_table_row(h: &SpannerConn, schema: &str, table: &str, values: HashMap) -> Result, String> { + let cols = get_column_structure(h, schema, table).await?; + let types = column_types(&cols); + let mut p = Params::new(h.dialect); + let mut names = Vec::new(); + let mut holes = Vec::new(); + for c in &cols { + let Some(v) = values.get(&c.name) else { continue }; + let (val, t) = param(&c.data_type, v)?; + names.push(quote_ident(h, &c.name)); + holes.push(p.bind(val, t)); + } + if names.is_empty() { + return Err("Fill in at least the primary key".into()); + } + let sql = format!("INSERT INTO {} ({}) VALUES ({})", table_ref(h, schema, table), names.join(", "), holes.join(", ")); + dml(h, &sql, p.take()).await?; + // Read the row back by its key, so defaults and commit timestamps show. + let pk: HashMap = + cols.iter().filter(|c| c.is_primary_key).filter_map(|c| Some((c.name.clone(), values.get(&c.name)?.clone()))).collect(); + if pk.len() != cols.iter().filter(|c| c.is_primary_key).count() || pk.is_empty() { + return Ok(cols.iter().map(|c| values.get(&c.name).cloned().unwrap_or(Value::Null)).collect()); + } + let mut p = Params::new(h.dialect); + let w = pk_where(h, &types, &pk, &mut p)?; + let sql = format!("SELECT * FROM {} WHERE {w}", table_ref(h, schema, table)); + let r = to_result(&read(h, &sql, p.take()).await?, &sql, Instant::now()); + Ok(r.rows.into_iter().next().unwrap_or_default()) +} + +pub async fn delete_table_rows(h: &SpannerConn, schema: &str, table: &str, primary_keys: Vec>) -> Result { + if primary_keys.is_empty() { + return Ok(0); + } + let cols = get_column_structure(h, schema, table).await?; + let types = column_types(&cols); + let mut p = Params::new(h.dialect); + let mut ors = Vec::new(); + for pk in &primary_keys { + ors.push(format!("({})", pk_where(h, &types, pk, &mut p)?)); + } + let sql = format!("DELETE FROM {} WHERE {}", table_ref(h, schema, table), ors.join(" OR ")); + let v = dml(h, &sql, p.take()).await?; + Ok(v["stats"]["rowCountExact"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0)) +} + +#[cfg(test)] +mod tests { + #[test] + fn backticks_become_pg_quotes() { + assert_eq!(pg_quotes("SELECT * FROM `public`.`items` WHERE a = 'x`y'"), "SELECT * FROM \"public\".\"items\" WHERE a = 'x`y'"); + assert_eq!(pg_quotes("SELECT `a``b`, `c\"d` -- `keep`\nFROM t /* `no` */"), "SELECT \"a`b\", \"c\"\"d\" -- `keep`\nFROM t /* `no` */"); + assert_eq!(pg_quotes("SELECT \"x`\" FROM t"), "SELECT \"x`\" FROM t"); + } + + use super::*; + + #[test] + fn values_come_back_as_the_grid_shows_them() { + assert_eq!(cell(&json!({"code": "INT64"}), json!("42")), json!(42)); + assert_eq!(cell(&json!({"code": "INT64"}), json!("9223372036854775807")), json!("9223372036854775807")); + assert_eq!(cell(&json!({"code": "JSON"}), json!("{\"a\":1}")), json!({"a": 1})); + assert_eq!( + cell(&json!({"code": "ARRAY", "arrayElementType": {"code": "INT64"}}), json!(["1", "2"])), + json!([1, 2]) + ); + assert_eq!(type_label(&json!({"code": "ARRAY", "arrayElementType": {"code": "STRING"}})), "ARRAY"); + } + + #[test] + fn cells_bind_as_typed_parameters() { + assert_eq!(param("INT64", &json!("7")).unwrap(), (json!("7"), json!({"code": "INT64"}))); + assert!(param("INT64", &json!("seven")).is_err()); + assert_eq!(param("BOOL", &json!("true")).unwrap().0, json!(true)); + assert_eq!(param("STRING(MAX)", &json!("x")).unwrap(), (json!("x"), json!({"code": "STRING"}))); + assert_eq!(param("FLOAT64", &json!("1.5")).unwrap().0, json!(1.5)); + assert_eq!(param("TIMESTAMP", &Value::Null).unwrap().0, Value::Null); + assert!(param("ARRAY", &json!("[]")).is_err()); + assert_eq!(base_type("character varying(20)"), "STRING"); + } + + #[test] + fn statements_are_classified() { + assert!(reads("SELECT 1")); + assert!(reads("WITH a AS (SELECT 1) SELECT * FROM a")); + assert_eq!(kind("INSERT INTO t (a) VALUES (1)"), "dml"); + assert_eq!(kind("CREATE INDEX i ON t(a)"), "ddl"); + } + + #[test] + fn plans_nest_and_fold_scalars() { + let nodes = json!([ + {"index": 0, "kind": "RELATIONAL", "displayName": "Distributed Union", "childLinks": [{"childIndex": 1}]}, + {"index": 1, "kind": "RELATIONAL", "displayName": "Scan", "metadata": {"scan_type": "TableScan", "scan_target": "users"}, + "childLinks": [{"childIndex": 2, "type": "Condition"}]}, + {"index": 2, "kind": "SCALAR", "displayName": "Function", "shortRepresentation": {"description": "($id > 1)"}} + ]); + let t = plan_tree(nodes.as_array().unwrap(), 0, 0); + assert_eq!(t["Node Type"], "Distributed Union"); + assert_eq!(t["Plans"][0]["Node Type"], "Scan (TableScan)"); + assert_eq!(t["Plans"][0]["Relation Name"], "users"); + assert_eq!(t["Plans"][0]["Filter"], "Condition: ($id > 1)"); + } + + /// Interleaved tables show as relations (STROKE_TEST_SPANNER). + /// The emulator takes one schema change at a time: the live tests, run in + /// parallel, rejected each other's DDL ("concurrent schema change") and left + /// tables behind for the next run to trip on. + static EMULATOR: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + + #[tokio::test] + async fn live_interleaved_relations() { + let Ok(spec) = std::env::var("STROKE_TEST_SPANNER") else { return }; + let _one_at_a_time = EMULATOR.lock().await; + let mut parts = spec.splitn(4, '/'); + let (host, project, instance, database) = + (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = SpannerConfig { + name: "t".into(), + project_id: project.into(), + instance_id: instance.into(), + database_id: database.into(), + auth: "emulator".into(), + key_file: None, + emulator_host: Some(host.into()), + }; + let h = connect(&cfg).await.unwrap(); + let _ = query(&h, "DROP TABLE StrokeOrders").await; + let _ = query(&h, "DROP TABLE StrokeCustomers").await; + query(&h, "CREATE TABLE StrokeCustomers (CustomerId STRING(36) NOT NULL, Name STRING(100)) PRIMARY KEY (CustomerId)").await.unwrap(); + query(&h, "CREATE TABLE StrokeOrders (CustomerId STRING(36) NOT NULL, OrderId STRING(36) NOT NULL, Status STRING(20)) PRIMARY KEY (CustomerId, OrderId), INTERLEAVE IN PARENT StrokeCustomers ON DELETE CASCADE").await.unwrap(); + let cols = get_column_structure(&h, DEFAULT_SCHEMA, "StrokeOrders").await.unwrap(); + assert_eq!(cols.iter().find(|c| c.name == "CustomerId").unwrap().foreign_key.as_deref(), Some("StrokeCustomers.CustomerId")); + assert!(cols.iter().find(|c| c.name == "OrderId").unwrap().foreign_key.is_none()); + let inc = incoming_foreign_keys(&h, DEFAULT_SCHEMA, "StrokeCustomers").await.unwrap(); + assert!(inc.iter().any(|f| f.from_table == "StrokeOrders" && f.from_columns == vec!["CustomerId".to_string()]), "{inc:?}"); + query(&h, "DROP TABLE StrokeOrders").await.unwrap(); + query(&h, "DROP TABLE StrokeCustomers").await.unwrap(); + } + + /// Against the Spanner emulator: + /// docker run -p 9010:9010 -p 9020:9020 gcr.io/cloud-spanner-emulator/emulator + /// STROKE_TEST_SPANNER=localhost:9020/test/inst/shop cargo test --lib spanner::tests::live + #[tokio::test] + async fn live_emulator_round_trip() { + let Ok(spec) = std::env::var("STROKE_TEST_SPANNER") else { return }; + let _one_at_a_time = EMULATOR.lock().await; + let mut parts = spec.splitn(4, '/'); + let (host, project, instance, database) = + (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = SpannerConfig { + name: "t".into(), + project_id: project.into(), + instance_id: instance.into(), + database_id: database.into(), + auth: "emulator".into(), + key_file: None, + emulator_host: Some(host.into()), + }; + let h = connect(&cfg).await.unwrap(); + let _ = query(&h, "DROP TABLE stroke_t").await; + query(&h, "CREATE TABLE stroke_t (id INT64 NOT NULL, name STRING(50), score FLOAT64, ok BOOL, born DATE) PRIMARY KEY (id)").await.unwrap(); + let r = query(&h, "INSERT INTO stroke_t (id, name, score, ok) VALUES (1, 'a', 1.5, true), (2, 'b', NULL, false)").await.unwrap(); + assert_eq!(r.row_count, Some(2)); + + assert!(list_schemas(&h).await.unwrap().contains(&DEFAULT_SCHEMA.to_string())); + let tables = list_tables(&h, DEFAULT_SCHEMA).await.unwrap(); + assert!(tables.iter().any(|t| t.name == "stroke_t")); + let cols = get_column_structure(&h, DEFAULT_SCHEMA, "stroke_t").await.unwrap(); + assert!(cols.iter().find(|c| c.name == "id").unwrap().is_primary_key); + + let page = get_table_rows(&h, DEFAULT_SCHEMA, "stroke_t", 50, 0, None, None, None, None).await.unwrap(); + assert_eq!(page.total, 2); + assert_eq!(page.primary_key, vec!["id".to_string()]); + let filtered = get_table_rows( + &h, DEFAULT_SCHEMA, "stroke_t", 50, 0, None, None, None, + Some(vec![RowFilter { column: "id".into(), op: ">".into(), value: Some("1".into()), conjunct: None, data_type: None }]), + ).await.unwrap(); + assert_eq!(filtered.total, 1); + let searched = get_table_rows(&h, DEFAULT_SCHEMA, "stroke_t", 50, 0, Some("B".into()), None, None, None).await.unwrap(); + assert_eq!(searched.total, 1); + + let pk = |id: i64| HashMap::from([("id".to_string(), json!(id))]); + update_table_cell(&h, DEFAULT_SCHEMA, "stroke_t", pk(2), "name", &json!("bee")).await.unwrap(); + update_table_cell(&h, DEFAULT_SCHEMA, "stroke_t", pk(2), "born", &json!("2020-02-02")).await.unwrap(); + let row = insert_table_row(&h, DEFAULT_SCHEMA, "stroke_t", HashMap::from([("id".to_string(), json!("3")), ("name".to_string(), json!("c"))])).await.unwrap(); + assert_eq!(row[0], json!(3)); + assert_eq!(delete_table_rows(&h, DEFAULT_SCHEMA, "stroke_t", vec![pk(1), pk(3)]).await.unwrap(), 2); + let r = query(&h, "SELECT name, born FROM stroke_t").await.unwrap(); + assert_eq!(r.rows, vec![vec![json!("bee"), json!("2020-02-02")]]); + + let plan = explain_plan(&h, "SELECT * FROM stroke_t WHERE id > 1").await.unwrap(); + assert!(plan["Node Type"].is_string(), "{plan}"); + assert!(get_ddl(&h, DEFAULT_SCHEMA, "stroke_t").await.unwrap().contains("CREATE TABLE")); + assert!(query(&h, "SELECT * FROM no_such_table").await.is_err()); + query(&h, "DROP TABLE stroke_t").await.unwrap(); + + // The seeded tables: a foreign key and a secondary index. + if list_tables(&h, DEFAULT_SCHEMA).await.unwrap().iter().any(|t| t.name == "orders") { + let cols = get_column_structure(&h, DEFAULT_SCHEMA, "orders").await.unwrap(); + assert_eq!(cols.iter().find(|c| c.name == "user_id").unwrap().foreign_key.as_deref(), Some("users.id")); + let idx = list_indexes(&h, DEFAULT_SCHEMA).await.unwrap(); + assert!(idx.iter().any(|i| i.name == "orders_by_user" && i.columns == "user_id"), "{idx:?}"); + let inc = incoming_foreign_keys(&h, DEFAULT_SCHEMA, "users").await.unwrap(); + assert!(inc.iter().any(|f| f.from_table == "orders" && f.from_columns == ["user_id"] && f.to_columns == ["id"]), "{inc:?}"); + assert!(count_rows(&h, DEFAULT_SCHEMA, "users").await.unwrap() >= 0); + } + } + + /// A PostgreSQL-dialect database on the emulator: + /// STROKE_TEST_SPANNER_PG=localhost:9020/test/inst/pgshop (with an `items` table) + #[tokio::test] + async fn live_emulator_postgres_dialect() { + let Ok(spec) = std::env::var("STROKE_TEST_SPANNER_PG") else { return }; + let _one_at_a_time = EMULATOR.lock().await; + let mut parts = spec.splitn(4, '/'); + let (host, project, instance, database) = + (parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap(), parts.next().unwrap()); + let cfg = SpannerConfig { + name: "t".into(), project_id: project.into(), instance_id: instance.into(), database_id: database.into(), + auth: "emulator".into(), key_file: None, emulator_host: Some(host.into()), + }; + let h = connect(&cfg).await.unwrap(); + assert_eq!(h.dialect, Dialect::Postgres); + assert!(list_schemas(&h).await.unwrap().contains(&"public".to_string())); + assert!(list_tables(&h, "public").await.unwrap().iter().any(|t| t.name == "items")); + query(&h, "DELETE FROM items WHERE true").await.unwrap(); + query(&h, "INSERT INTO items (id, label, price) VALUES (1, 'pen', 2.5), (2, 'cup', 4)").await.unwrap(); + let page = get_table_rows( + &h, "public", "items", 50, 0, None, Some("price".into()), Some("desc".into()), + Some(vec![RowFilter { column: "id".into(), op: ">=".into(), value: Some("1".into()), conjunct: None, data_type: None }]), + ).await.unwrap(); + assert_eq!(page.total, 2); + assert_eq!(page.rows[0][1], json!("cup")); + update_table_cell(&h, "public", "items", HashMap::from([("id".to_string(), json!(1))]), "label", &json!("pencil")).await.unwrap(); + let r = query(&h, "SELECT label FROM items WHERE id = 1").await.unwrap(); + assert_eq!(r.rows[0][0], json!("pencil")); + // The app's GoogleSQL-style quoting still reads here. + let r = query(&h, "SELECT `label` FROM `public`.`items` WHERE `id` = 1").await.unwrap(); + assert_eq!(r.rows[0][0], json!("pencil")); + } +} diff --git a/src-tauri/src/db/sqlite.rs b/src-tauri/src/db/sqlite.rs index d2fee48e..61d89013 100644 --- a/src-tauri/src/db/sqlite.rs +++ b/src-tauri/src/db/sqlite.rs @@ -107,19 +107,122 @@ pub async fn fetch_foreign_keys(pool: &SqlitePool, table: &str) -> Result Result { + let mut conn = pool.acquire().await.map_err(|e| format!("{e}"))?; + run_sql(&mut conn, sql).await +} + +extern "C" { + /// SQLite's own cancel: the statement running on `db` stops at its next + /// step with SQLITE_INTERRUPT. Safe to call from another thread. Linked + /// from the SQLite that sqlx already builds in. + fn sqlite3_interrupt(db: *mut std::ffi::c_void); +} + +/// A connection's `sqlite3*`, sent to the Stop watcher's thread. +struct RawDb(*mut std::ffi::c_void); +// SAFETY: only ever passed to sqlite3_interrupt, which SQLite documents as +// safe to call from any thread while the connection is open; `Arm` keeps the +// call inside the window where this run holds the connection. +unsafe impl Send for RawDb {} + +/// `execute_sql`, stoppable. Stop interrupts the statement inside SQLite, so +/// it really ends: before, the future was dropped while the worker thread kept +/// running it, holding the write lock for whatever came next. +pub async fn execute_sql_cancellable( + pool: &SqlitePool, + sql: &str, + cancel: tokio::sync::oneshot::Receiver<()>, +) -> Result { + let mut conn = pool.acquire().await.map_err(|e| format!("{e}"))?; + let raw = RawDb( + conn.lock_handle().await.map_err(|e| format!("{e}"))?.as_raw_handle().as_ptr() as *mut std::ffi::c_void, + ); + let arm = super::stop::Arm::new(cancel, move || { + let raw = raw; + // SAFETY: see RawDb. The connection is checked out by this run until + // `disarm` below, and Arm never calls this after disarm. + unsafe { sqlite3_interrupt(raw.0) } + }); + let result = run_sql(&mut conn, sql).await; + let stopped = arm.disarm(); + match result { + Err(_) if stopped => Err(super::query::QUERY_CANCELLED.into()), + other => other, + } +} + +/// One row-returning statement streamed into the console's sink (and so into +/// the result store) as it arrives, stoppable like `execute_sql_cancellable`. +pub async fn stream_into( + pool: &SqlitePool, + sql: &str, + sink: &mut super::query::RowSink, + cancel: tokio::sync::oneshot::Receiver<()>, +) -> Result { + let t0 = Instant::now(); + let mut conn = pool.acquire().await.map_err(|e| format!("{e}"))?; + let raw = RawDb( + conn.lock_handle().await.map_err(|e| format!("{e}"))?.as_raw_handle().as_ptr() as *mut std::ffi::c_void, + ); + let arm = super::stop::Arm::new(cancel, move || { + let raw = raw; + // SAFETY: see RawDb and execute_sql_cancellable. + unsafe { sqlite3_interrupt(raw.0) } + }); + let mut columns: Vec = Vec::new(); + let mut total = 0usize; + let streamed: Result<(), String> = async { + let mut stream = sqlx::query(sql).fetch(&mut *conn); + while let Some(row) = stream.try_next().await.map_err(|e| format!("{e}"))? { + if total == 0 { + columns = row.columns().iter().map(|c| ColumnInfo::new(c.name(), c.type_info().name().to_lowercase())).collect(); + sink.start(columns.clone())?; + } + sink.push((0..columns.len()).map(|i| cell_to_json(&row, i)).collect())?; + total += 1; + } + Ok(()) + } + .await; + let stopped = arm.disarm(); + match streamed { + Err(_) if stopped => return Err(super::query::QUERY_CANCELLED.into()), + Err(e) => return Err(e), + Ok(()) => {} + } + if total > 0 { + sink.finish()?; + } else { + // No row to read the columns off: an empty SELECT showed no headers. + columns = describe_columns(&mut conn, sql).await; + } + Ok(SqlResult { columns, rows: vec![], row_count: Some(total as i64), message: None, query_ms: t0.elapsed().as_millis() as u64, sql: sql.to_string() }) +} + +/// A statement's result columns without running it again: what an empty +/// result reports, since they are otherwise read off its first row. +async fn describe_columns(conn: &mut sqlx::SqliteConnection, sql: &str) -> Vec { + match sqlx::Executor::describe(conn, sql).await { + Ok(d) => d.columns().iter().map(|c| ColumnInfo::new(c.name(), c.type_info().name().to_lowercase())).collect(), + Err(_) => Vec::new(), + } +} + +async fn run_sql(conn: &mut sqlx::SqliteConnection, sql: &str) -> Result { let t0 = Instant::now(); let sql = sql.trim(); let head = super::sql_util::statement_head(sql); if matches!(head.as_str(), "select" | "with" | "pragma" | "explain" | "values") { - let mut stream = sqlx::query(sql).fetch(pool); + let mut stream = sqlx::query(sql).fetch(&mut *conn); // Convert each row to JSON as it streams in and drop the driver row // immediately - retaining the full Vec alongside the JSON // rows would double peak memory on a large result. let mut columns: Vec = Vec::new(); let mut data: Vec> = Vec::new(); let mut capped = false; + let mut budget = super::query::CollectBudget::default(); loop { match stream.try_next().await { @@ -131,8 +234,10 @@ pub async fn execute_sql(pool: &SqlitePool, sql: &str) -> Result= EXECUTE_SQL_MAX_ROWS { + let cells: Vec = (0..columns.len()).map(|i| cell_to_json(&row, i)).collect(); + let fits = budget.take(&cells); + data.push(cells); + if !fits || data.len() >= EXECUTE_SQL_MAX_ROWS { capped = true; break; } @@ -145,25 +250,22 @@ pub async fn execute_sql(pool: &SqlitePool, sql: &str) -> Result Result( other => q.bind(other.to_string()), } } + +#[cfg(test)] +mod empty_result_tests { + use sqlx::Connection; + + /// A SELECT that matches nothing still names its columns. + #[tokio::test] + async fn empty_select_keeps_its_columns() { + let mut conn = sqlx::SqliteConnection::connect("sqlite::memory:").await.unwrap(); + sqlx::query("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)").execute(&mut conn).await.unwrap(); + let r = super::run_sql(&mut conn, "SELECT id, name FROM t WHERE id < 0").await.unwrap(); + assert!(r.rows.is_empty()); + assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::>(), ["id", "name"]); + } +} diff --git a/src-tauri/src/db/ssh_tunnel.rs b/src-tauri/src/db/ssh_tunnel.rs index 426a20d4..ba2e2af5 100644 --- a/src-tauri/src/db/ssh_tunnel.rs +++ b/src-tauri/src/db/ssh_tunnel.rs @@ -1,15 +1,44 @@ use serde::{Deserialize, Serialize}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; +use tauri::Emitter; +use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::{Child, Command}; /// SSH tunnel configuration - serialized alongside saved connections. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SshConfig { + /// How the tunnel is made: "" or "ssh" (a bastion), "kubernetes" + /// (`kubectl port-forward`) or "ssm" (`aws ssm start-session`). Every kind + /// forwards a local port to the database, so the engines need nothing else. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub kind: String, + /// The tunnel's end: the SSH host, the Kubernetes resource (`svc/postgres`, + /// `pod/db-0`, `deployment/api`), or the SSM target (`i-0abc…`). pub host: String, #[serde(default = "default_ssh_port")] pub port: u16, + #[serde(default)] pub username: String, + /// Kubernetes: the kubeconfig context; empty is the current one. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub context: String, + /// Kubernetes: the namespace; empty is the context's default. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub namespace: String, + /// SSM: the AWS region; empty is the CLI's default. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub region: String, + /// SSM: the AWS CLI profile; empty is the default credentials. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub profile: String, + /// Set by `establish` when the SSH connection goes through a proxy: the + /// local forwarder's port, which ssh dials instead of `host:port`. + #[serde(skip)] + pub hop_port: Option, /// Path to an identity file (e.g. `~/.ssh/id_rsa`). /// Leave empty to rely on the system SSH agent. #[serde(default)] @@ -30,18 +59,100 @@ fn default_ssh_port() -> u16 { 22 } +// ── Loss tracking ───────────────────────────────────────────────────────────── +// +// A query that fails because its tunnel went away has two very different +// meanings. If the tunnel was already down when it started, nothing reached the +// server. If the tunnel dropped while it ran, nobody knows: a write may have +// committed before the reply was lost. The query paths read these counters +// around a run (`RunWatch`) and say which one happened. + +/// Bumped every time a tunnel's ssh process exits on its own. +static LOSSES: AtomicU64 = AtomicU64::new(0); +/// Tunnels currently down and reconnecting. +static DOWN: AtomicUsize = AtomicUsize::new(0); +/// For the `tunnel-status` events the window listens to. +static APP: OnceLock = OnceLock::new(); + +pub fn init(app: tauri::AppHandle) { + let _ = APP.set(app); +} + +/// Taken before a query runs; asked about its error afterwards. +#[derive(Clone, Copy)] +pub struct RunWatch { + losses: u64, + down: bool, +} + +impl RunWatch { + pub fn start() -> Self { + Self { losses: LOSSES.load(Ordering::SeqCst), down: DOWN.load(Ordering::SeqCst) > 0 } + } + + /// Reword a failed run's error when a tunnel explains it. `writes` is + /// whether the SQL could have changed anything. + pub fn explain(self, err: String, writes: bool) -> String { + if err == super::query::QUERY_CANCELLED { + return err; + } + if self.down { + return format!("The SSH tunnel is down and reconnecting, so this did not reach the server. Run it again once the tunnel is back. ({err})"); + } + if LOSSES.load(Ordering::SeqCst) != self.losses { + return if writes { + format!("Result unknown: the SSH tunnel dropped while this ran, so it may or may not have been applied. Check the data before running it again. ({err})") + } else { + format!("The SSH tunnel dropped while this ran. Nothing was changed; run it again once the tunnel is back. ({err})") + }; + } + err + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct TunnelEvent { + /// `user@host:port` of the SSH server. + via: String, + /// "down" (lost, reconnecting), "retrying" (a reconnect failed), "up", + /// or "closed" (the connection was left while it was down). + state: &'static str, + message: Option, +} + +fn announce(via: &str, state: &'static str, message: Option) { + if let Some(app) = APP.get() { + let _ = app.emit("tunnel-status", TunnelEvent { via: via.to_string(), state, message }); + } +} + // ── SshTunnel ───────────────────────────────────────────────────────────────── -/// A live SSH local-port-forward tunnel backed by a system `ssh -N -L` process. -/// Dropping the struct kills the SSH process automatically. +/// A live SSH local-port-forward tunnel backed by a system `ssh -N -L` process, +/// watched by a supervisor that rebuilds it on the same local port when the +/// process exits. Dropping the struct stops the supervisor, which kills ssh. pub struct SshTunnel { pub local_port: u16, - child: Child, + /// The proxy forwarder this tunnel dials through, kept alive with it. + _hop: Option, + supervisor: tauri::async_runtime::JoinHandle<()>, + /// This tunnel is down and its supervisor is reconnecting. + down: Arc, + via: String, } impl Drop for SshTunnel { fn drop(&mut self) { - let _ = self.child.start_kill(); + // The child is spawned with kill_on_drop, and the supervisor owns it. + self.supervisor.abort(); + // Closed while down (the connection was left mid-reconnect): it no + // longer counts as down, and the window's "reconnecting" toast goes. + // Left counted, every later failed query read as a tunnel failure. + if self.down.swap(false, Ordering::SeqCst) { + DOWN.fetch_sub(1, Ordering::SeqCst); + announce(&self.via, "closed", None); + } } } @@ -56,104 +167,776 @@ fn find_free_port() -> Result { Ok(port) } +/// The last lines ssh wrote to stderr: the only place it says *why*. +type StderrTail = Arc>>; + +fn args_for(ssh: &SshConfig, forward: &str) -> Vec { + let mut args: Vec = vec![ + "-N".into(), + // Kill immediately if port-forward binding fails + "-o".into(), "ExitOnForwardFailure=yes".into(), + // Never prompt: there is no terminal to answer, so a passphrase or + // password prompt would hang until the deadline and then say nothing. + "-o".into(), "BatchMode=yes".into(), + // Accept new hosts but reject changed fingerprints + "-o".into(), "StrictHostKeyChecking=accept-new".into(), + "-o".into(), "ServerAliveCountMax=3".into(), + "-o".into(), "ConnectTimeout=10".into(), + "-p".into(), ssh.hop_port.unwrap_or(ssh.port).to_string(), + "-L".into(), forward.to_string(), + ]; + // Through a proxy: dial its local forwarder, and check the host key under + // the bastion's own name rather than 127.0.0.1's. + if ssh.hop_port.is_some() { + args.push("-o".into()); + args.push(format!("HostKeyAlias={}", ssh.host)); + } + // Keep-alive so long-idle tunnels don't stall the pool. Configurable + // because the useful value is a property of the network in between, not + // of the database: 30s is right behind a NAT, pointless on a LAN, and + // too slow for a load balancer that reaps at 20. + if ssh.keepalive > 0 { + args.push("-o".into()); + args.push(format!("ServerAliveInterval={}", ssh.keepalive)); + } + if !ssh.private_key_path.trim().is_empty() { + args.push("-i".into()); + args.push(ssh.private_key_path.clone()); + } + // Tests run against a throwaway sshd and must not write to ~/.ssh. + #[cfg(test)] + if let Ok(file) = std::env::var("STROKE_TEST_KNOWN_HOSTS") { + args.push("-o".into()); + args.push(format!("UserKnownHostsFile={file}")); + } + let dial_host = if ssh.hop_port.is_some() { "127.0.0.1" } else { ssh.host.as_str() }; + args.push(format!("{}@{}", ssh.username, dial_host)); + args +} + +impl SshConfig { + fn is_kubernetes(&self) -> bool { + self.kind == "kubernetes" + } + fn is_ssm(&self) -> bool { + self.kind == "ssm" + } + /// A database connection through a proxy (Settings > Network): `host` is + /// the proxy URL, and the "tunnel" is an in-process forwarder. + fn is_proxy(&self) -> bool { + self.kind == "proxy" + } + /// How the tunnel is named in its status events and errors. + fn label(&self) -> String { + if self.is_kubernetes() { + let ns = if self.namespace.is_empty() { String::new() } else { format!("{}/", self.namespace) }; + format!("kubectl {ns}{}", self.host) + } else if self.is_ssm() { + format!("SSM {}", self.host) + } else { + format!("{}@{}:{}", self.username, self.host, self.port) + } + } +} + +/// `kubectl port-forward` to the resource, on 127.0.0.1 only. +fn kubectl_args(cfg: &SshConfig, local_port: u16, db_port: u16) -> Vec { + let mut args: Vec = Vec::new(); + if !cfg.context.trim().is_empty() { + args.push("--context".into()); + args.push(cfg.context.trim().into()); + } + if !cfg.namespace.trim().is_empty() { + args.push("--namespace".into()); + args.push(cfg.namespace.trim().into()); + } + args.extend(["port-forward".into(), "--address".into(), "127.0.0.1".into(), cfg.host.trim().into(), format!("{local_port}:{db_port}")]); + args +} + +/// `aws ssm start-session` forwarding through the target to the database +/// host, so an RDS instance in a private subnet is reached through any +/// instance that can see it (or the target itself, as localhost). +fn ssm_args(cfg: &SshConfig, local_port: u16, db_host: &str, db_port: u16) -> Vec { + let mut args: Vec = vec!["ssm".into(), "start-session".into(), "--target".into(), cfg.host.trim().into()]; + if !cfg.region.trim().is_empty() { + args.push("--region".into()); + args.push(cfg.region.trim().into()); + } + if !cfg.profile.trim().is_empty() { + args.push("--profile".into()); + args.push(cfg.profile.trim().into()); + } + let params = serde_json::json!({ + "host": [db_host], + "portNumber": [db_port.to_string()], + "localPortNumber": [local_port.to_string()], + }); + args.extend(["--document-name".into(), "AWS-StartPortForwardingSessionToRemoteHost".into(), "--parameters".into(), params.to_string()]); + args +} + +/// What kubectl or the AWS CLI said, as a sentence someone can act on. +fn explain_cli_failure(cfg: &SshConfig, tail: &[String], fallback: &str) -> String { + let all = tail.join("\n"); + let has = |needle: &str| all.contains(needle); + if cfg.is_kubernetes() { + if has("NotFound") || has("not found") { + return format!("Kubernetes has no {} in {}. Check the resource name (svc/…, pod/…, deployment/…) and the namespace.", cfg.host, if cfg.namespace.is_empty() { "the default namespace" } else { &cfg.namespace }); + } + if has("context") && (has("does not exist") || has("not found")) { + return format!("No kubeconfig context named {}. kubectl config get-contexts lists them.", cfg.context); + } + if has("Unauthorized") || has("forbidden") || has("Forbidden") { + return format!("Kubernetes refused the port-forward to {}: the credentials in this context may not allow it.", cfg.host); + } + if has("unable to connect") || has("Unable to connect") || has("connection refused") { + return "kubectl could not reach the cluster. Check the context and that the cluster is up.".into(); + } + } else if cfg.is_ssm() { + if has("SessionManagerPlugin is not found") || has("session-manager-plugin") { + return "SSM port forwarding needs the AWS Session Manager plugin next to the AWS CLI. Install session-manager-plugin, then try again.".into(); + } + if has("TargetNotConnected") { + return format!("{} is not connected to Systems Manager. Check the SSM agent is running on it and its role allows SSM.", cfg.host); + } + if has("AccessDenied") || has("not authorized") { + return "AWS refused the session: the credentials in use may not allow ssm:StartSession on this target.".into(); + } + if has("Unable to locate credentials") || has("could not be found") && has("profile") { + return "The AWS CLI has no credentials for this. Check the profile, or run aws configure / aws sso login.".into(); + } + } + match tail.iter().rev().find(|l| !l.trim().is_empty()) { + Some(line) => format!("{} failed: {}", cfg.label(), line.trim()), + None => fallback.to_string(), + } +} + +/// Turn what ssh printed into a sentence someone can act on. +fn explain_ssh_failure(ssh: &SshConfig, tail: &[String], fallback: &str) -> String { + if ssh.is_kubernetes() || ssh.is_ssm() { + return explain_cli_failure(ssh, tail, fallback); + } + let all = tail.join("\n"); + let has = |needle: &str| all.contains(needle); + let who = format!("{}@{}:{}", ssh.username, ssh.host, ssh.port); + let reason = if has("REMOTE HOST IDENTIFICATION HAS CHANGED") || has("Host key verification failed") { + format!("The host key for {} has changed since it was last seen. If the server was rebuilt, remove its old entry from ~/.ssh/known_hosts; otherwise do not connect.", ssh.host) + } else if has("Permission denied") { + if ssh.private_key_path.trim().is_empty() { + format!("{who} rejected the login. No key file is set, so ssh used your agent: check the key is loaded (ssh-add -l) and allowed on the server.") + } else { + format!("{who} rejected the key {}. Check it is the right key and that it has no passphrase, or load it into your SSH agent.", ssh.private_key_path) + } + } else if has("Could not resolve hostname") { + format!("Could not find the SSH host {}. Check the name.", ssh.host) + } else if has("Connection refused") { + format!("{} refused the SSH connection on port {}. Check the port and that sshd is running.", ssh.host, ssh.port) + } else if has("timed out") { + format!("No answer from {} on port {} within 10 seconds. Check the host is reachable and the port is not blocked.", ssh.host, ssh.port) + } else if has("Address already in use") || has("cannot listen to port") { + "The local end of the tunnel could not bind its port. Another program may have taken it.".to_string() + } else if has("Identity file") && has("not accessible") { + format!("The key file {} could not be read. Check the path.", ssh.private_key_path) + } else { + return match tail.iter().rev().find(|l| !l.trim().is_empty()) { + Some(line) => format!("SSH tunnel to {who} failed: {}", line.trim()), + None => fallback.to_string(), + }; + }; + reason +} + +/// Spawn ssh forwarding `local_port` and wait until the port answers, ssh +/// exits (fail with its own reason), or the deadline passes. +async fn spawn_ready(ssh: &SshConfig, local_port: u16, db_host: &str, db_port: u16) -> Result<(Child, StderrTail), String> { + let forward = format!("{local_port}:{db_host}:{db_port}"); + let (program, args, missing) = if ssh.is_kubernetes() { + ("kubectl", kubectl_args(ssh, local_port, db_port), "Failed to launch kubectl. Install it and make sure it is on your PATH.") + } else if ssh.is_ssm() { + ("aws", ssm_args(ssh, local_port, db_host, db_port), "Failed to launch the AWS CLI. Install aws (v2) and the Session Manager plugin, and make sure they are on your PATH.") + } else { + ("ssh", args_for(ssh, &forward), "Failed to launch SSH. Ensure the 'ssh' binary is on your PATH.") + }; + let mut cmd = Command::new(program); + if ssh.is_kubernetes() || ssh.is_ssm() { + cmd.envs(crate::proxy::child_env()); + } + cmd.args(args) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true); + // quiet: the tunnel is a background process the user never interacts with, + // so on Windows it must not get a console window of its own. + let mut child = crate::proc::quiet(&mut cmd) + .spawn() + .map_err(|e| format!("{missing} ({e})"))?; + + let tail: StderrTail = Arc::new(Mutex::new(VecDeque::new())); + if let Some(stderr) = child.stderr.take() { + let tail = tail.clone(); + tauri::async_runtime::spawn(async move { + let mut lines = BufReader::new(stderr).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let mut t = tail.lock().unwrap_or_else(|e| e.into_inner()); + if t.len() == 20 { + t.pop_front(); + } + t.push_back(line); + } + }); + } + + // Poll until the forwarded port accepts connections: 10 s for ssh, 30 s + // for kubectl and SSM, which first ask an API (and SSM opens a session). + let wait = if ssh.is_kubernetes() || ssh.is_ssm() { 30 } else { 10 }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(wait); + loop { + if let Ok(Some(_)) = child.try_wait() { + // Give the reader a moment to collect the last lines. + tokio::time::sleep(Duration::from_millis(100)).await; + let lines: Vec = tail.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(); + return Err(explain_ssh_failure(ssh, &lines, &format!("{} exited before the tunnel was up.", ssh.label()))); + } + if tokio::net::TcpStream::connect(format!("127.0.0.1:{local_port}")).await.is_ok() { + return Ok((child, tail)); + } + if tokio::time::Instant::now() >= deadline { + let lines: Vec = tail.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(); + return Err(explain_ssh_failure( + ssh, + &lines, + &if ssh.is_kubernetes() || ssh.is_ssm() { + format!("{} did not open the local port within {wait} seconds.", ssh.label()) + } else { + format!( + "SSH tunnel to {}@{} timed out - check credentials, host reachability, and that port {} is not blocked", + ssh.username, ssh.host, ssh.port + ) + }, + )); + } + tokio::time::sleep(Duration::from_millis(250)).await; + } +} + +/// Backoff between reconnect attempts: 1, 2, 4, 8, 16, then every 30 s. +fn backoff(attempt: u32) -> Duration { + Duration::from_secs((1u64 << attempt.min(5)).min(30)) +} + impl SshTunnel { - /// Spawn `ssh -N -L {local_port}:{db_host}:{db_port} …` and block until - /// the forwarded port is reachable (or the 10 s deadline is hit). + /// Spawn `ssh -N -L {local_port}:{db_host}:{db_port} …`, block until the + /// forwarded port is reachable, then supervise it for as long as the + /// tunnel lives. pub async fn establish(ssh: &SshConfig, db_host: &str, db_port: u16) -> Result { + let down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + if ssh.is_proxy() { + let fwd = crate::proxy::ProxyForward::start(&ssh.host, db_host, db_port).await?; + // Nothing to supervise: every connection dials the proxy afresh. + let supervisor = tauri::async_runtime::spawn(std::future::pending::<()>()); + return Ok(SshTunnel { local_port: fwd.local_port, _hop: Some(fwd), supervisor, down, via: "proxy".into() }); + } + let mut cfg = ssh.clone(); + let mut hop = None; + if !ssh.is_kubernetes() && !ssh.is_ssm() { + if let Some(url) = crate::proxy::custom_url(crate::proxy::Kind::Ssh) { + let fwd = crate::proxy::ProxyForward::start(&url, &ssh.host, ssh.port).await?; + cfg.hop_port = Some(fwd.local_port); + hop = Some(fwd); + } + } let local_port = find_free_port()?; - let forward = format!("{local_port}:{db_host}:{db_port}"); - let dest = format!("{}@{}", ssh.username, ssh.host); - - let mut args: Vec = vec![ - "-N".into(), - // Kill immediately if port-forward binding fails - "-o".into(), "ExitOnForwardFailure=yes".into(), - // Accept new hosts but reject changed fingerprints - "-o".into(), "StrictHostKeyChecking=accept-new".into(), - "-o".into(), "ServerAliveCountMax=3".into(), - "-o".into(), "ConnectTimeout=10".into(), - "-p".into(), ssh.port.to_string(), - "-L".into(), forward, - ]; - - // Keep-alive so long-idle tunnels don't stall the pool. Configurable - // because the useful value is a property of the network in between, not - // of the database: 30s is right behind a NAT, pointless on a LAN, and - // too slow for a load balancer that reaps at 20. - if ssh.keepalive > 0 { - args.push("-o".into()); - args.push(format!("ServerAliveInterval={}", ssh.keepalive)); - } - - if !ssh.private_key_path.trim().is_empty() { - args.push("-i".into()); - args.push(ssh.private_key_path.clone()); - } - - args.push(dest); - - let mut cmd = Command::new("ssh"); - cmd.args(&args) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()); - // quiet: the tunnel is a background process the user never interacts with - // (all three streams are already closed), so on Windows it must not get a - // console window of its own. - let child = crate::proc::quiet(&mut cmd) - .spawn() - .map_err(|e| { - format!( - "Failed to launch SSH: {e}. \ - Ensure the 'ssh' binary is on your PATH." - ) - })?; - - // Poll until the forwarded port accepts connections (up to 10 s). - let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + let (child, tail) = spawn_ready(&cfg, local_port, db_host, db_port).await?; + let supervisor = tauri::async_runtime::spawn(supervise(cfg.clone(), local_port, db_host.to_string(), db_port, child, tail, down.clone())); + Ok(SshTunnel { local_port, _hop: hop, supervisor, down, via: ssh.label() }) + } +} + +/// The tunnel a connection takes: its own SSH/Kubernetes/SSM tunnel when it +/// has one, otherwise the database proxy from Settings > Network, if set. +pub fn effective(ssh: &Option) -> Option { + if let Some(s) = ssh { + return Some(s.clone()); + } + crate::proxy::custom_url(crate::proxy::Kind::Database).map(|url| SshConfig { kind: "proxy".into(), host: url, ..Default::default() }) +} + +impl SshTunnel { +} + +/// Wait on ssh; when it exits on its own, say so and bring it back on the same +/// local port, so the pool's address stays valid and its keepalive replaces the +/// dead connections without anyone reconnecting by hand. +async fn supervise( + ssh: SshConfig, + local_port: u16, + db_host: String, + db_port: u16, + mut child: Child, + mut tail: StderrTail, + down: Arc, +) { + let via = ssh.label(); + loop { + let _ = child.wait().await; + LOSSES.fetch_add(1, Ordering::SeqCst); + if !down.swap(true, Ordering::SeqCst) { + DOWN.fetch_add(1, Ordering::SeqCst); + } + let lines: Vec = tail.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(); + let why = explain_ssh_failure(&ssh, &lines, "The SSH connection closed."); + log::info!("ssh tunnel {via} lost: {why}"); + announce(&via, "down", Some(why)); + + let mut attempt = 0; loop { - if tokio::net::TcpStream::connect(format!("127.0.0.1:{local_port}")) - .await - .is_ok() - { - break; + tokio::time::sleep(backoff(attempt)).await; + match spawn_ready(&ssh, local_port, &db_host, db_port).await { + Ok((c, t)) => { + child = c; + tail = t; + break; + } + Err(e) => { + attempt += 1; + announce(&via, "retrying", Some(e)); + } } - if tokio::time::Instant::now() >= deadline { - return Err(format!( - "SSH tunnel to {}@{} timed out - \ - check credentials, host reachability, and that port {} is not blocked", - ssh.username, ssh.host, ssh.port - )); - } - tokio::time::sleep(Duration::from_millis(250)).await; } + if down.swap(false, Ordering::SeqCst) { + DOWN.fetch_sub(1, Ordering::SeqCst); + } + log::info!("ssh tunnel {via} back on 127.0.0.1:{local_port}"); + announce(&via, "up", None); + } +} + +// ── HTTP engines through a tunnel ───────────────────────────────────────────── - Ok(SshTunnel { local_port, child }) +/// A base URL pointed through `via`: the port becomes the tunnel's, and the +/// host stays the server's name (TLS checks it; `http_client` resolves it to +/// the tunnel). An IP address has no name to keep, so it becomes 127.0.0.1. +pub fn url_via(mut url: reqwest::Url, via: Option) -> reqwest::Url { + let Some(via) = via else { return url }; + let is_ip = url.host_str().map(|h| h.trim_matches(['[', ']'])).and_then(|h| h.parse::().ok()).is_some(); + if is_ip { + let _ = url.set_host(Some("127.0.0.1")); + } + let _ = url.set_port(Some(via.port())); + url +} + +/// The HTTP client for a server reached through `via`: its name resolves to +/// the tunnel. One per (name, tunnel), kept. None without a tunnel, so the +/// caller keeps its shared client. +pub fn http_client(host: &str, via: Option, insecure: bool) -> Option { + static CLIENTS: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + let via = via?; + let key = (host.to_string(), via, insecure); + let mut map = CLIENTS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(c) = map.get(&key) { + return Some(c.clone()); + } + // Always direct: `via` is a local tunnel end, already past any proxy. + let c = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(60)) + .connect_timeout(Duration::from_secs(10)) + .danger_accept_invalid_certs(insecure) + .resolve(host, via) + .build() + .ok()?; + map.insert(key, c.clone()); + Some(c) +} + +/// Host and port of an HTTP(S) URL, the port defaulting by scheme. +pub fn url_target(url: &str) -> Result<(String, u16), String> { + let raw = url.trim().trim_end_matches('/'); + let raw = if raw.contains("://") { raw.to_string() } else { format!("http://{raw}") }; + let u = reqwest::Url::parse(&raw).map_err(|e| format!("Invalid URL \"{raw}\": {e}"))?; + let host = u.host_str().ok_or_else(|| format!("No host in \"{raw}\""))?.trim_matches(['[', ']']).to_string(); + let port = u.port_or_known_default().unwrap_or(80); + Ok((host, port)) +} + +/// A `mongodb://` URI pointed at `local`: the first host replaced by the +/// tunnel and `directConnection=true`, since a replica set would otherwise +/// hand back member names this machine can't reach. Refuses what a tunnel +/// can't carry: `mongodb+srv://` (several hosts found by DNS) and TLS (the +/// driver can't dial one address while verifying another name). +pub fn mongo_uri_via(uri: &str, local: u16) -> Result { + let uri = uri.trim(); + if uri.starts_with("mongodb+srv://") { + return Err("An SSH tunnel needs a mongodb:// connection string with a host and port; mongodb+srv:// finds its hosts through DNS. Use the standard connection string from your provider.".into()); + } + let rest = uri.strip_prefix("mongodb://").ok_or("The connection string starts with mongodb://")?; + let (auth, after_auth) = match rest.rfind('@') { + Some(i) if rest[..i].find('/').is_none() => (&rest[..=i], &rest[i + 1..]), + _ => ("", rest), + }; + let end = after_auth.find(['/', '?']).unwrap_or(after_auth.len()); + let tail = &after_auth[end..]; + let query = tail.split_once('?').map(|(_, q)| q).unwrap_or(""); + let tls = query.split('&').any(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + (k.eq_ignore_ascii_case("tls") || k.eq_ignore_ascii_case("ssl")) && v.eq_ignore_ascii_case("true") + }); + if tls { + return Err("MongoDB with TLS can't go through an SSH tunnel here: the driver would check the certificate against 127.0.0.1. Turn TLS off for a server only reachable through the tunnel, or connect without SSH.".into()); + } + let path = if tail.is_empty() { "/".to_string() } else if tail.starts_with('?') { format!("/{tail}") } else { tail.to_string() }; + let sep = if path.contains('?') { "&" } else { "?" }; + let direct = if query.to_ascii_lowercase().contains("directconnection=") { String::new() } else { format!("{sep}directConnection=true") }; + Ok(format!("mongodb://{auth}127.0.0.1:{local}{path}{direct}")) +} + +/// The first host of a `mongodb://` URI, port defaulting to 27017. +pub fn mongo_first_host(uri: &str) -> Option<(String, u16)> { + let rest = uri.trim().strip_prefix("mongodb://")?; + let after_auth = match rest.rfind('@') { + Some(i) if rest[..i].find('/').is_none() => &rest[i + 1..], + _ => rest, + }; + let hosts = &after_auth[..after_auth.find(['/', '?']).unwrap_or(after_auth.len())]; + let first = hosts.split(',').next()?.trim(); + if let Some(v6) = first.strip_prefix('[') { + let (h, rest) = v6.split_once(']')?; + let port = rest.strip_prefix(':').and_then(|p| p.parse().ok()).unwrap_or(27017); + return Some((h.to_string(), port)); + } + match first.rsplit_once(':') { + Some((h, p)) => Some((h.to_string(), p.parse().ok()?)), + None => Some((first.to_string(), 27017)), } } // ── TunnelState ─────────────────────────────────────────────────────────────── -/// Tauri-managed state holding the currently active SSH tunnel (if any). -/// Set on connect, cleared on disconnect; Drop kills the ssh process. -pub struct TunnelState { - inner: std::sync::Mutex>, +/// The tunnel under the open connection, and the tunnels under connections +/// Labs has set aside (by the same key as the parked pool). A tunnel moves with +/// its connection: before, there was one slot, so connecting anything through +/// SSH killed the tunnel a parked connection still depended on, and switching +/// to an engine without SSH left the old tunnel's ssh running. +#[derive(Default)] +struct Tunnels { + active: Option, + parked: std::collections::HashMap, +} + +static TUNNELS: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); + +fn tunnels() -> std::sync::MutexGuard<'static, Tunnels> { + TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The open connection is being set aside under `key`: so is its tunnel. +pub fn park_active(key: &str) { + let mut t = tunnels(); + match t.active.take() { + Some(tunnel) => { + t.parked.insert(key.to_string(), tunnel); + } + None => { + t.parked.remove(key); + } + } +} + +/// The connection under `key` is open again: its tunnel is the active one. +pub fn resume_parked(key: &str) { + let mut t = tunnels(); + let tunnel = t.parked.remove(key); + t.active = tunnel; +} + +/// Parked connections were closed: close their tunnels. +pub fn drop_parked(keys: &[String]) { + let mut t = tunnels(); + for k in keys { + t.parked.remove(k); + } +} + +/// The open connection is closing: close its tunnel. +pub fn drop_active() { + tunnels().active = None; } +/// Tauri-managed handle on the active tunnel (kept so commands can take it as +/// state). Set on connect, cleared on disconnect; dropping a tunnel stops its +/// supervisor and ssh. +pub struct TunnelState; + impl TunnelState { pub fn new() -> Self { - Self { - inner: std::sync::Mutex::new(None), - } + Self } pub fn set(&self, tunnel: Option) { - if let Ok(mut g) = self.inner.lock() { - *g = tunnel; - } + tunnels().active = tunnel; } pub fn clear(&self) { self.set(None); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg(key: &str) -> SshConfig { + SshConfig { host: "bastion".into(), port: 22, username: "me".into(), private_key_path: key.into(), keepalive: 30, ..Default::default() } + } + + #[test] + fn names_the_real_reason() { + let key = explain_ssh_failure(&cfg("~/.ssh/id"), &["me@bastion: Permission denied (publickey).".into()], "x"); + assert!(key.contains("rejected the key ~/.ssh/id"), "{key}"); + let agent = explain_ssh_failure(&cfg(""), &["Permission denied (publickey).".into()], "x"); + assert!(agent.contains("ssh-add -l"), "{agent}"); + let changed = explain_ssh_failure(&cfg(""), &["@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @".into()], "x"); + assert!(changed.contains("known_hosts"), "{changed}"); + let other = explain_ssh_failure(&cfg(""), &["".to_string(), "kex_exchange_identification: read: Connection reset".into(), "".into()], "x"); + assert!(other.ends_with("kex_exchange_identification: read: Connection reset"), "{other}"); + assert_eq!(explain_ssh_failure(&cfg(""), &[], "fallback"), "fallback"); + } + + // Live: a tunnel whose ssh dies comes back on the same local port, and a + // bad key says so. Needs an sshd that forwards to a Postgres: + // STROKE_TEST_SSH=user@127.0.0.1:2222 STROKE_TEST_SSH_KEY=/path/key + // STROKE_TEST_SSH_WRONG_KEY=/path/other STROKE_TEST_KNOWN_HOSTS=/tmp/kh + // STROKE_TEST_PG_PORT=5433 cargo test --lib ssh_tunnel::tests::live_ -- --nocapture + #[tokio::test] + async fn live_tunnel_comes_back_after_ssh_dies() { + let (Ok(target), Ok(key), Ok(pg_port)) = ( + std::env::var("STROKE_TEST_SSH"), + std::env::var("STROKE_TEST_SSH_KEY"), + std::env::var("STROKE_TEST_PG_PORT"), + ) else { + return; + }; + let (user, hostport) = target.split_once('@').unwrap(); + let (host, port) = hostport.split_once(':').unwrap(); + let ssh = SshConfig { host: host.into(), port: port.parse().unwrap(), username: user.into(), private_key_path: key, keepalive: 5, ..Default::default() }; + let pg_port: u16 = pg_port.parse().unwrap(); + + let tunnel = SshTunnel::establish(&ssh, "127.0.0.1", pg_port).await.unwrap(); + let url = format!("postgres://postgres@127.0.0.1:{}/postgres", tunnel.local_port); + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(2).connect(&url).await.unwrap(); + let one: i32 = sqlx::query_scalar("SELECT 1").fetch_one(&pool).await.unwrap(); + assert_eq!(one, 1); + + // A dropped network: ssh exits on its own. + let watch = RunWatch::start(); + let killed = std::process::Command::new("pkill") + .args(["-f", &format!("{}:127.0.0.1:{pg_port} ", tunnel.local_port)]) + .status() + .unwrap(); + assert!(killed.success(), "found the tunnel's ssh to kill"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(watch.explain("x".into(), true).starts_with("Result unknown"), "the loss is counted"); + assert!(RunWatch::start().down, "the tunnel reports down while it reconnects"); + + // Back on the same port within the first backoff (1 s) plus a connect. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + if DOWN.load(Ordering::SeqCst) == 0 { + break; + } + assert!(tokio::time::Instant::now() < deadline, "tunnel did not come back"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + // The pool's address never changed: a fresh connection just works. + let pool2 = sqlx::postgres::PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap(); + let two: i32 = sqlx::query_scalar("SELECT 2").fetch_one(&pool2).await.unwrap(); + assert_eq!(two, 2); + drop(tunnel); + } + + // Live: Labs parks a tunnelled connection and opens another through SSH. + // The parked one's tunnel must survive, come back on resume, and the one + // in front at that point must close. + #[tokio::test] + async fn live_parked_tunnels_survive_and_come_back() { + let (Ok(target), Ok(key), Ok(pg_port)) = ( + std::env::var("STROKE_TEST_SSH"), + std::env::var("STROKE_TEST_SSH_KEY"), + std::env::var("STROKE_TEST_PG_PORT"), + ) else { + return; + }; + let (user, hostport) = target.split_once('@').unwrap(); + let (host, port) = hostport.split_once(':').unwrap(); + let ssh = SshConfig { host: host.into(), port: port.parse().unwrap(), username: user.into(), private_key_path: key, keepalive: 30, ..Default::default() }; + let pg_port: u16 = pg_port.parse().unwrap(); + let up = |p: u16| async move { tokio::net::TcpStream::connect(("127.0.0.1", p)).await.is_ok() }; + + let a = SshTunnel::establish(&ssh, "127.0.0.1", pg_port).await.unwrap(); + let a_port = a.local_port; + let state = TunnelState::new(); + state.set(Some(a)); + park_active("conn-a|db"); + + // Connecting B: what connect does (close_existing, then set). + drop_active(); + let b = SshTunnel::establish(&ssh, "127.0.0.1", pg_port).await.unwrap(); + let b_port = b.local_port; + state.set(Some(b)); + assert!(up(a_port).await, "the parked connection's tunnel must stay up"); + + // Back to A: B is set aside by the page first in real use, but a + // resume alone replaces whatever was in front. + resume_parked("conn-a|db"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(up(a_port).await, "A's tunnel is in front again"); + assert!(!up(b_port).await, "B's tunnel closed with it"); + + drop_active(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!up(a_port).await); + } + + // Live: leaving a connection while its tunnel is down must not leave the + // tunnel counted as down (later failures would all read as tunnel loss). + #[tokio::test] + async fn live_dropping_a_down_tunnel_settles_it() { + let (Ok(target), Ok(key), Ok(pg_port), Ok(pidfile)) = ( + std::env::var("STROKE_TEST_SSH"), + std::env::var("STROKE_TEST_SSH_KEY"), + std::env::var("STROKE_TEST_PG_PORT"), + std::env::var("STROKE_TEST_SSHD_PID"), + ) else { + return; + }; + let (user, hostport) = target.split_once('@').unwrap(); + let (host, port) = hostport.split_once(':').unwrap(); + let ssh = SshConfig { host: host.into(), port: port.parse().unwrap(), username: user.into(), private_key_path: key, keepalive: 30, ..Default::default() }; + let t = SshTunnel::establish(&ssh, "127.0.0.1", pg_port.parse().unwrap()).await.unwrap(); + // Take the server away and kill the tunnel: it stays down, retrying. + let sshd = std::fs::read_to_string(&pidfile).unwrap().trim().to_string(); + std::process::Command::new("kill").arg(&sshd).status().unwrap(); + std::process::Command::new("pkill").args(["-f", &format!("{}:127.0.0.1:{pg_port} ", t.local_port)]).status().unwrap(); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!(t.down.load(Ordering::SeqCst)); + let before = DOWN.load(Ordering::SeqCst); + drop(t); + assert_eq!(DOWN.load(Ordering::SeqCst), before - 1); + } + + #[tokio::test] + async fn live_wrong_key_says_rejected() { + let (Ok(target), Ok(key)) = (std::env::var("STROKE_TEST_SSH"), std::env::var("STROKE_TEST_SSH_WRONG_KEY")) else { + return; + }; + let (user, hostport) = target.split_once('@').unwrap(); + let (host, port) = hostport.split_once(':').unwrap(); + let ssh = SshConfig { host: host.into(), port: port.parse().unwrap(), username: user.into(), private_key_path: key.clone(), keepalive: 30, ..Default::default() }; + let err = SshTunnel::establish(&ssh, "127.0.0.1", 5433).await.err().expect("a wrong key must fail"); + assert!(err.contains(&format!("rejected the key {key}")), "{err}"); + } + + #[test] + fn points_a_mongo_uri_at_the_tunnel() { + assert_eq!( + mongo_uri_via("mongodb://u:p%40ss@db1:27018,db2:27019/shop?replicaSet=rs0", 40001).unwrap(), + "mongodb://u:p%40ss@127.0.0.1:40001/shop?replicaSet=rs0&directConnection=true" + ); + assert_eq!(mongo_uri_via("mongodb://db1", 40001).unwrap(), "mongodb://127.0.0.1:40001/?directConnection=true"); + assert_eq!(mongo_uri_via("mongodb://db1/?directConnection=false", 7).unwrap(), "mongodb://127.0.0.1:7/?directConnection=false"); + assert!(mongo_uri_via("mongodb+srv://c.example.net/shop", 7).unwrap_err().contains("mongodb+srv")); + assert!(mongo_uri_via("mongodb://db1/?tls=true", 7).unwrap_err().contains("TLS")); + assert_eq!(mongo_first_host("mongodb://u:p@db1:27018,db2/shop"), Some(("db1".into(), 27018))); + assert_eq!(mongo_first_host("mongodb://db1"), Some(("db1".into(), 27017))); + assert_eq!(mongo_first_host("mongodb://[::1]:27020/x"), Some(("::1".into(), 27020))); + } + + #[test] + fn points_an_http_url_at_the_tunnel() { + assert_eq!(url_target("https://es.example.com").unwrap(), ("es.example.com".into(), 443)); + assert_eq!(url_target("couch.local:5984").unwrap(), ("couch.local".into(), 5984)); + let via: std::net::SocketAddr = "127.0.0.1:41000".parse().unwrap(); + let named = url_via(reqwest::Url::parse("https://es.example.com:9200/").unwrap(), Some(via)); + assert_eq!(named.as_str(), "https://es.example.com:41000/", "the name stays for TLS"); + let ip = url_via(reqwest::Url::parse("http://10.0.0.5:5984/").unwrap(), Some(via)); + assert_eq!(ip.as_str(), "http://127.0.0.1:41000/"); + let direct = url_via(reqwest::Url::parse("http://10.0.0.5:5984/").unwrap(), None); + assert_eq!(direct.as_str(), "http://10.0.0.5:5984/"); + } + + // Live: a Kubernetes tunnel to a Postgres service answers a query, and a + // wrong resource says what is wrong. Needs kubectl on PATH and a cluster: + // STROKE_TEST_K8S="svc/postgres|data|pw" KUBECONFIG=... cargo test --lib ssh_tunnel::tests::live_kubernetes + #[tokio::test] + async fn live_kubernetes_port_forward() { + let Ok(spec) = std::env::var("STROKE_TEST_K8S") else { return }; + let p: Vec<&str> = spec.splitn(3, '|').collect(); + let cfg = SshConfig { kind: "kubernetes".into(), host: p[0].into(), namespace: p[1].into(), ..Default::default() }; + let tunnel = SshTunnel::establish(&cfg, "ignored", 5432).await.expect("kubectl tunnel"); + let url = format!("postgres://postgres:{}@127.0.0.1:{}/postgres", p[2], tunnel.local_port); + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(1).connect(&url).await.expect("connect through the tunnel"); + let one: i32 = sqlx::query_scalar("SELECT 1").fetch_one(&pool).await.unwrap(); + assert_eq!(one, 1); + let wrong = SshConfig { kind: "kubernetes".into(), host: "svc/nope".into(), namespace: p[1].into(), ..Default::default() }; + let err = SshTunnel::establish(&wrong, "ignored", 5432).await.err().expect("a missing service fails"); + assert!(err.contains("no svc/nope"), "{err}"); + } + + // Live: an SSM tunnel through a managed instance reaches a Postgres + // server, which answers the 8-byte SSL probe with one byte ('S' or 'N'). + // Needs the AWS CLI, the Session Manager plugin and credentials in the + // environment: + // STROKE_TEST_SSM="i-0abc|ap-south-1|db.host|5432" cargo test --lib ssh_tunnel::tests::live_ssm + #[tokio::test] + async fn live_ssm_port_forward() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let Ok(spec) = std::env::var("STROKE_TEST_SSM") else { return }; + let p: Vec<&str> = spec.splitn(4, '|').collect(); + let cfg = SshConfig { kind: "ssm".into(), host: p[0].into(), region: p[1].into(), ..Default::default() }; + let tunnel = SshTunnel::establish(&cfg, p[2], p[3].parse().unwrap()).await.expect("ssm tunnel"); + let mut sock = tokio::net::TcpStream::connect(("127.0.0.1", tunnel.local_port)).await.unwrap(); + sock.write_all(&[0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]).await.unwrap(); + let mut buf = [0u8; 1]; + let n = tokio::time::timeout(Duration::from_secs(20), sock.read(&mut buf)).await.expect("an answer in time").unwrap(); + assert!(n == 1 && (buf[0] == b'S' || buf[0] == b'N'), "{buf:?}"); + } + + #[test] + fn builds_kubectl_and_ssm_commands() { + let k = SshConfig { kind: "kubernetes".into(), host: "svc/postgres".into(), namespace: "data".into(), context: "prod".into(), ..Default::default() }; + assert_eq!(kubectl_args(&k, 41000, 5432), ["--context", "prod", "--namespace", "data", "port-forward", "--address", "127.0.0.1", "svc/postgres", "41000:5432"]); + assert_eq!(k.label(), "kubectl data/svc/postgres"); + let s = SshConfig { kind: "ssm".into(), host: "i-0abc".into(), region: "ap-south-1".into(), ..Default::default() }; + let a = ssm_args(&s, 41001, "db.internal", 5432); + assert_eq!(&a[..6], ["ssm", "start-session", "--target", "i-0abc", "--region", "ap-south-1"]); + assert!(a.contains(&"AWS-StartPortForwardingSessionToRemoteHost".to_string())); + assert!(a.last().unwrap().contains(r#""localPortNumber":["41001"]"#) && a.last().unwrap().contains(r#""host":["db.internal"]"#)); + let err = explain_ssh_failure(&s, &["An error occurred (TargetNotConnected) when calling the StartSession operation".into()], "x"); + assert!(err.contains("not connected to Systems Manager"), "{err}"); + let err = explain_ssh_failure(&k, &["Error from server (NotFound): services \"postgres\" not found".into()], "x"); + assert!(err.contains("no svc/postgres in data"), "{err}"); + } + + #[test] + fn backs_off_to_thirty_seconds() { + let s: Vec = (0..8).map(|a| backoff(a).as_secs()).collect(); + assert_eq!(s, vec![1, 2, 4, 8, 16, 30, 30, 30]); + } + + #[test] + fn says_whether_a_failed_run_reached_the_server() { + let before = RunWatch { losses: LOSSES.load(Ordering::SeqCst), down: false }; + assert_eq!(before.explain("boom".into(), true), "boom"); + LOSSES.fetch_add(1, Ordering::SeqCst); + assert!(before.explain("boom".into(), true).starts_with("Result unknown")); + assert!(before.explain("boom".into(), false).contains("Nothing was changed")); + let down = RunWatch { losses: 0, down: true }; + assert!(down.explain("refused".into(), true).contains("did not reach the server")); + assert_eq!(down.explain(crate::db::query::QUERY_CANCELLED.into(), true), crate::db::query::QUERY_CANCELLED); + } +} diff --git a/src-tauri/src/db/stop.rs b/src-tauri/src/db/stop.rs new file mode 100644 index 00000000..712ad03e --- /dev/null +++ b/src-tauri/src/db/stop.rs @@ -0,0 +1,211 @@ +//! Stop for the console, shared by every engine that is not Postgres. +//! +//! The window sends one Stop per run (a oneshot), but a script runs several +//! statements and each engine wants the signal in its own shape: a receiver, +//! a future to race, or a callback on another thread. `Stop` turns the one +//! signal into as many of those as a run needs. +//! +//! `Arm` is the callback shape, for drivers that interrupt a running call from +//! another thread (SQLite's `sqlite3_interrupt`, DuckDB's `InterruptHandle`). +//! The interrupt goes to whatever the connection is running *now*, so it must +//! never fire after the run is over and the connection has moved on to the next +//! caller: `disarm` and the watcher take the same lock, and the watcher checks +//! `done` under it. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::sync::{oneshot, Notify}; + +#[derive(Clone)] +pub struct Stop { + fired: Arc, + notify: Arc, +} + +impl Stop { + /// Listen on the run's Stop. If the run ends first, the sender is dropped + /// and the listener exits. + pub fn from_rx(rx: oneshot::Receiver<()>) -> Self { + let stop = Self { fired: Arc::new(AtomicBool::new(false)), notify: Arc::new(Notify::new()) }; + let s = stop.clone(); + tauri::async_runtime::spawn(async move { + if rx.await.is_ok() { + s.fired.store(true, Ordering::SeqCst); + s.notify.notify_waiters(); + } + }); + stop + } + + pub fn fired(&self) -> bool { + self.fired.load(Ordering::SeqCst) + } + + /// Resolves once Stop is pressed (at once if it already was). + pub async fn wait(&self) { + loop { + let notified = self.notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if self.fired() { + return; + } + notified.await; + } + } + + /// A receiver for one statement. Its forwarder exits when the statement + /// drops the receiver, so an unpressed Stop leaves nothing behind. + pub fn receiver(&self) -> oneshot::Receiver<()> { + let (mut tx, rx) = oneshot::channel(); + let s = self.clone(); + tauri::async_runtime::spawn(async move { + tokio::select! { + _ = s.wait() => { let _ = tx.send(()); } + _ = tx.closed() => {} + } + }); + rx + } +} + +#[derive(Default)] +struct Flags { + done: bool, + fired: bool, +} + +/// An interrupt armed for one run on one connection. +pub struct Arm { + flags: Arc>, +} + +impl Arm { + pub fn new(rx: oneshot::Receiver<()>, interrupt: F) -> Self + where + F: FnOnce() + Send + 'static, + { + let flags = Arc::new(Mutex::new(Flags::default())); + let f = flags.clone(); + tauri::async_runtime::spawn(async move { + if rx.await.is_err() { + return; + } + let mut g = f.lock().unwrap_or_else(|e| e.into_inner()); + if !g.done { + g.fired = true; + interrupt(); + } + }); + Self { flags } + } + + /// The run is over: no interrupt can reach the connection from here on. + /// True when Stop interrupted it. + pub fn disarm(self) -> bool { + let mut g = self.flags.lock().unwrap_or_else(|e| e.into_inner()); + g.done = true; + g.fired + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[tokio::test] + async fn one_stop_reaches_every_statement() { + let (tx, rx) = oneshot::channel(); + let stop = Stop::from_rx(rx); + let a = stop.receiver(); + let b = stop.receiver(); + tx.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(1), stop.wait()).await.unwrap(); + assert!(a.await.is_ok() && b.await.is_ok()); + // A receiver taken after Stop still fires. + assert!(stop.receiver().await.is_ok()); + } + + #[tokio::test] + async fn an_arm_never_fires_after_disarm() { + let (tx, rx) = oneshot::channel(); + let hit = Arc::new(AtomicBool::new(false)); + let h = hit.clone(); + let arm = Arm::new(rx, move || h.store(true, Ordering::SeqCst)); + assert!(!arm.disarm()); + let _ = tx.send(()); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!hit.load(Ordering::SeqCst), "a late Stop must not interrupt the connection's next user"); + } + + #[tokio::test] + async fn an_arm_fires_while_armed() { + let (tx, rx) = oneshot::channel(); + let hit = Arc::new(AtomicBool::new(false)); + let h = hit.clone(); + let arm = Arm::new(rx, move || h.store(true, Ordering::SeqCst)); + tx.send(()).unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(hit.load(Ordering::SeqCst)); + assert!(arm.disarm()); + } +} + +/// Stop has to end the statement, not just the wait for it. +#[cfg(test)] +mod engine_tests { + use std::time::{Duration, Instant}; + use tokio::sync::oneshot; + + /// Runs forever unless interrupted. + const SQLITE_FOREVER: &str = + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c WHERE x < 0"; + + #[tokio::test] + async fn sqlite_stop_interrupts_the_statement() { + let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + let _ = tx.send(()); + }); + let t = Instant::now(); + let r = crate::db::sqlite::execute_sql_cancellable(&pool, SQLITE_FOREVER, rx).await; + assert_eq!(r.unwrap_err(), crate::db::query::QUERY_CANCELLED); + assert!(t.elapsed() < Duration::from_secs(3), "took {:?}", t.elapsed()); + // The one connection is free and clean: the statement really ended. + let r = crate::db::sqlite::execute_sql(&pool, "SELECT 1").await.unwrap(); + assert_eq!(r.row_count, Some(1)); + } + + #[tokio::test] + async fn sqlite_finishes_when_nobody_stops_it() { + let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap(); + let (_tx, rx) = oneshot::channel::<()>(); + let r = crate::db::sqlite::execute_sql_cancellable(&pool, "SELECT 42", rx).await.unwrap(); + assert_eq!(r.rows[0][0], serde_json::json!(42)); + } + + #[tokio::test] + async fn duckdb_stop_interrupts_the_statement() { + let cfg = crate::db::connection::DuckdbConfig { name: "t".into(), file_path: ":memory:".into() }; + let h = crate::db::connection::open_duckdb(&cfg).await.unwrap(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + let _ = tx.send(()); + }); + let t = Instant::now(); + let r = crate::db::duckdb::execute_sql_cancellable( + &h, + "SELECT count(*) FROM range(100000000) a, range(100000000) b WHERE a.range + b.range < 0", + rx, + ) + .await; + assert_eq!(r.unwrap_err(), crate::db::query::QUERY_CANCELLED); + assert!(t.elapsed() < Duration::from_secs(5), "took {:?}", t.elapsed()); + let r = crate::db::duckdb::execute_sql(&h, "SELECT 1").await.unwrap(); + assert_eq!(r.row_count, Some(1)); + } +} diff --git a/src-tauri/src/db/terminal.rs b/src-tauri/src/db/terminal.rs index 105d4c27..82d73a04 100644 --- a/src-tauri/src/db/terminal.rs +++ b/src-tauri/src/db/terminal.rs @@ -480,6 +480,10 @@ async fn pg_launch(config: PgConfig) -> Result { ("PGDATABASE", c.database.clone()), ("PGAPPNAME", "Stroke".to_string()), ]; + // Through a tunnel: dial it, and keep PGHOST for TLS verification. + if let Some(via) = c.via { + env.push(("PGHOSTADDR", via.ip().to_string())); + } if !c.password.is_empty() { env.push(("PGPASSWORD", c.password.clone())); } @@ -522,7 +526,9 @@ async fn pg_launch(config: PgConfig) -> Result { async fn mysql_launch(config: MysqlConfig, mariadb: bool) -> Result { let (c, tunnel) = resolve_mysql_ssh(config).await?; let mut args = vec![ - format!("--host={}", c.host), + // The mysql client has no separate dial address: through a tunnel it + // connects to the tunnel by IP. + format!("--host={}", c.via.map(|v| v.ip().to_string()).unwrap_or_else(|| c.host.clone())), format!("--port={}", c.port), format!("--user={}", c.user), "--default-character-set=utf8mb4".to_string(), @@ -914,6 +920,22 @@ pub async fn terminal_close(state: State<'_, TerminalState>, id: String) -> Resu /// Make the Turso CLI config folder Stroke points its shell at: autoupdate off. /// Returns None when it can't be written, and the CLI keeps its own. +/// The address `turso db shell` gets. Its `.dump` is an HTTP GET to +/// `/dump`, so a `libsql://` (or `wss://`) address failed with +/// "unsupported protocol scheme"; the shell itself takes https just as well. +fn turso_shell_url(url: &str) -> String { + let u = url.trim(); + if u.starts_with("libsql://") { + return super::libsql::libsql_http_url(u); + } + for (from, to) in [("wss://", "https://"), ("ws://", "http://")] { + if let Some(rest) = u.strip_prefix(from) { + return format!("{to}{rest}"); + } + } + u.to_string() +} + fn quiet_turso_config(dir: &Path) -> Option { std::fs::create_dir_all(dir).ok()?; let file = dir.join("settings.json"); @@ -923,21 +945,14 @@ fn quiet_turso_config(dir: &Path) -> Option { Some(dir.to_path_buf()) } -async fn open_session( - state: &TerminalState, +/// The command line, environment and tunnel a client is started with: the +/// same for the terminal tab and the live client tests. +async fn launch_for( config: AnyConnectionConfig, - cols: u16, - rows: u16, + binary: &Path, turso_token: Option, turso_config: Option, -) -> Result { - reap_unattached(state); - let t0 = Instant::now(); - let client = client_for(&config)?; - let binary = find_binary(client.binaries) - .await - .ok_or_else(|| format!("{} is not installed. {}", client.name, install_hint(&client)))?; - let t_find = t0.elapsed(); +) -> Result { let launch = match config { AnyConnectionConfig::Postgres(c) => pg_launch(c).await?, AnyConnectionConfig::Mysql(c) => { @@ -971,7 +986,7 @@ async fn open_session( if via_wsl { args.extend(["-e".into(), "turso".into()]); } - args.extend(["db".into(), "shell".into(), c.url.trim().to_string()]); + args.extend(["db".into(), "shell".into(), turso_shell_url(&c.url)]); let mut env = Vec::new(); if let Some(token) = turso_token { env.push(("TURSO_API_TOKEN", token)); @@ -990,6 +1005,25 @@ async fn open_session( } _ => return Err("This connection has no terminal client.".into()), }; + Ok(launch) +} + +async fn open_session( + state: &TerminalState, + config: AnyConnectionConfig, + cols: u16, + rows: u16, + turso_token: Option, + turso_config: Option, +) -> Result { + reap_unattached(state); + let t0 = Instant::now(); + let client = client_for(&config)?; + let binary = find_binary(client.binaries) + .await + .ok_or_else(|| format!("{} is not installed. {}", client.name, install_hint(&client)))?; + let t_find = t0.elapsed(); + let launch = launch_for(config, &binary, turso_token, turso_config).await?; let shared = state.shared(); let port = *state.port.get_or_try_init(|| serve(shared)).await?; @@ -1355,6 +1389,7 @@ mod tests { #[test] fn pg_password_and_ssl_travel_in_env_not_argv() { let config = PgConfig { + via: None, name: "t".into(), host: "db.example.com".into(), port: 5433, @@ -1366,6 +1401,7 @@ mod tests { ssl_root_cert: Some("/ca.pem".into()), ssh: None, timezone: Some("SYSTEM".into()), + params: None, }; let launch = tauri::async_runtime::block_on(pg_launch(config)).unwrap(); assert!(launch.args.iter().all(|a| !a.contains("s3cret"))); @@ -1401,6 +1437,7 @@ mod tests { #[test] fn mariadb_gets_switches_instead_of_ssl_mode() { let config = |ssl_mode: &str| MysqlConfig { + via: None, name: "t".into(), host: "h".into(), port: 3306, @@ -1516,3 +1553,86 @@ mod tests { }); } } + +#[cfg(test)] +mod turso_url_tests { + use super::turso_shell_url; + + #[test] + fn turso_shell_gets_an_http_address() { + assert_eq!(turso_shell_url("libsql://movie-x.aws-us-east-1.turso.io"), "https://movie-x.aws-us-east-1.turso.io"); + assert_eq!(turso_shell_url(" wss://db.example.io "), "https://db.example.io"); + assert_eq!(turso_shell_url("ws://127.0.0.1:8080"), "http://127.0.0.1:8080"); + assert_eq!(turso_shell_url("http://127.0.0.1:8080"), "http://127.0.0.1:8080"); + } +} + +#[cfg(test)] +mod live_clients { + //! Every terminal client the machine has, started with the app's own + //! arguments and environment against a real database, given one command, + //! and checked for the answer. STROKE_TEST_CLIENTS=1 turns it on; each + //! client also needs its database's variable below. + use super::*; + use serde_json::json; + use std::process::Stdio; + use tokio::io::AsyncWriteExt; + + async fn run(config: serde_json::Value, input: &str, expect: &str) -> Result<(), String> { + let cfg: AnyConnectionConfig = serde_json::from_value(config.clone()).map_err(|e| e.to_string())?; + let client = client_for(&cfg)?; + let Some(binary) = find_binary(client.binaries).await else { + println!("skip {}: not installed", client.name); + return Ok(()); + }; + let turso_config = std::env::var("STROKE_TEST_TURSO_CONFIG").ok().map(PathBuf::from); + let launch = launch_for(cfg, &binary, None, turso_config).await?; + let mut cmd = tokio::process::Command::new(&binary); + cmd.args(&launch.args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + for k in launch.unset { + cmd.env_remove(k); + } + for (k, v) in &launch.env { + cmd.env(k, v); + } + let mut child = cmd.spawn().map_err(|e| format!("{}: {e}", client.name))?; + child.stdin.take().unwrap().write_all(input.as_bytes()).await.map_err(|e| e.to_string())?; + let out = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output()).await.map_err(|_| format!("{} timed out", client.name))?.map_err(|e| e.to_string())?; + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + println!("== {} ({})\n{}", client.name, binary.display(), text.trim()); + if text.contains(expect) { Ok(()) } else { Err(format!("{}: expected {expect:?} in output:\n{text}", client.name)) } + } + + #[tokio::test] + async fn clients_answer() { + if std::env::var("STROKE_TEST_CLIENTS").is_err() { + return; + } + let mut failures = Vec::new(); + // psql: postgres://user:pw@host:port/db + if let Ok(spec) = std::env::var("STROKE_TEST_PSQL") { + let p: Vec<&str> = spec.split('|').collect(); + let cfg = json!({ "type": "postgres", "name": "t", "host": p[0], "port": p[1].parse::().unwrap(), "user": p[2], "password": p[3], "database": p[4], "ssl": false }); + if let Err(e) = run(cfg, "select 40 + 2 as answer;\n\\q\n", "42").await { failures.push(e) } + } + if let Ok(spec) = std::env::var("STROKE_TEST_MYSQL_CLI") { + let p: Vec<&str> = spec.split('|').collect(); + let cfg = json!({ "type": "mysql", "name": "t", "host": p[0], "port": p[1].parse::().unwrap(), "user": p[2], "password": p[3], "database": p[4], "ssl": false }); + if let Err(e) = run(cfg, "select 40 + 2 as answer;\nexit\n", "42").await { failures.push(e) } + } + if let Ok(path) = std::env::var("STROKE_TEST_SQLITE_FILE") { + let cfg = json!({ "type": "sqlite", "name": "t", "filePath": path }); + if let Err(e) = run(cfg, ".tables\n.quit\n", "pets").await { failures.push(e) } + } + if let Ok(spec) = std::env::var("STROKE_TEST_REDIS_CLI") { + let p: Vec<&str> = spec.split('|').collect(); + let cfg = json!({ "type": "redis", "name": "t", "host": p[0], "port": p[1].parse::().unwrap(), "db": 0, "tls": false }); + if let Err(e) = run(cfg, "PING\n", "PONG").await { failures.push(e) } + } + if let Ok(url) = std::env::var("STROKE_TEST_TURSO_URL") { + let cfg = json!({ "type": "libsql", "name": "t", "url": url }); + if let Err(e) = run(cfg, ".dump\n", "CREATE TABLE").await { failures.push(e) } + } + assert!(failures.is_empty(), "{}", failures.join("\n\n")); + } +} diff --git a/src-tauri/src/db/tx.rs b/src-tauri/src/db/tx.rs index b03fab1d..63cd2dce 100644 --- a/src-tauri/src/db/tx.rs +++ b/src-tauri/src/db/tx.rs @@ -7,20 +7,29 @@ the user can run a few statements, look at what they did, and then decide whether to keep them. A transaction holds a real connection (and, on most engines, locks) for as long -as it stays open, so a session that is left behind is closed automatically after -`IDLE_TIMEOUT` - see `sweep_idle`. +as it stays open, so a session that is left behind is rolled back after +`IDLE_TIMEOUT` by a timer (`sweep_idle`), and every session is rolled back when +the active connection changes (`connection_changed`). + +A session ends through `release` and nowhere else. Its `BEGIN` was a plain +statement, so sqlx does not know the connection is in a transaction: dropping +the `PoolConnection` hands it back to the pool still inside it (sqlx only pings +on release), and the next grid edit or console run that picks it up joins the +abandoned transaction. Its writes are never committed and the locks stay held. +`release` rolls back first and closes the socket if the rollback fails. */ use crate::db::connection::Db; use std::collections::HashMap; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use futures::TryStreamExt; use serde::Serialize; use serde_json::Value; use sqlx::{Column, Row, TypeInfo}; -use tauri::State; +use tauri::Emitter; use super::connection::{require_conn, ActiveConnection}; use super::query::{ @@ -33,25 +42,76 @@ use super::query::{ /// idle this long is rolled back and released on the next transaction command. const IDLE_TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// How often the timer looks for sessions past `IDLE_TIMEOUT`. +pub const SWEEP_EVERY: Duration = Duration::from_secs(60); + +/// Postgres's own backstop, a little past ours: if this process dies or hangs +/// with a transaction open, the server ends the session itself. +const SERVER_IDLE_TIMEOUT: &str = "35min"; + +/// A ROLLBACK that takes longer than this is talking to a dead socket. +const RELEASE_TIMEOUT: Duration = Duration::from_secs(5); + /// The checked-out connection, per engine. enum TxConn { Postgres(sqlx::pool::PoolConnection), Mysql(sqlx::pool::PoolConnection), Sqlite(sqlx::pool::PoolConnection), + // These engines hold one shared connection rather than a pool, so a + // transaction opens a connection of its own beside it (see each module's + // open_tx_*): on the shared one, every grid page and sidebar query would + // have run inside the transaction. + Duckdb(super::connection::DuckdbHandle), + Mssql(super::connection::MssqlHandle), + Oracle(super::connection::OracleHandle), + Odbc(super::odbc::OdbcHandle), } impl TxConn { + /// Take the connection out of the pool for good. Dropping the raw + /// connection closes its socket, which makes the server roll back. + fn close_hard(self) { + match self { + TxConn::Postgres(c) => drop(c.detach()), + TxConn::Mysql(c) => drop(c.detach()), + TxConn::Sqlite(c) => drop(c.detach()), + // Their own connection: dropping it closes it, and the server + // rolls back what it held. + TxConn::Duckdb(h) => drop(h), + TxConn::Mssql(h) => { + super::mssql::forget(&h); + drop(h) + } + TxConn::Oracle(h) => drop(h), + TxConn::Odbc(h) => drop(h), + } + } + fn engine(&self) -> &'static str { match self { TxConn::Postgres(_) => "postgres", TxConn::Mysql(_) => "mysql", TxConn::Sqlite(_) => "sqlite", + TxConn::Duckdb(_) => "duckdb", + TxConn::Mssql(_) => "mssql", + TxConn::Oracle(_) => "oracle", + TxConn::Odbc(_) => "odbc", } } } +/// Where to ask who this transaction is holding up: a second pooled +/// connection and this session's server-side id. +enum Blocker { + Postgres(sqlx::PgPool, i32), + Mysql(sqlx::MySqlPool, u64), +} + struct TxSession { conn: TxConn, + /// The connection epoch at BEGIN (see `connection_changed`). + epoch: u64, + blocker: Option, /// Statements run since BEGIN, for the status line. statements: usize, /// Rows reported changed by those statements. @@ -60,9 +120,101 @@ struct TxSession { last_used: Instant, } +/// Open sessions by id. Module state rather than Tauri state so a connection +/// switch (`connection_changed`, called from `db::connection`) can reach them. +static SESSIONS: LazyLock>> = LazyLock::new(Default::default); + +/// Bumped every time the active connection is replaced, parked or closed. A +/// session from an older epoch belongs to a database the window has left. +static EPOCH: AtomicU64 = AtomicU64::new(0); + +/// For the `tx-ended` event the window listens to. +static APP: OnceLock = OnceLock::new(); + +pub fn init(app: tauri::AppHandle) { + let _ = APP.set(app); +} + +/// Kept so `lib.rs` can still `.manage()` it; the sessions live in `SESSIONS`. #[derive(Default)] -pub struct TxState { - sessions: Mutex>, +pub struct TxState; + +/// Why a session ended without the user pressing Commit or Rollback. +#[derive(Debug, Clone, Copy, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub enum EndReason { + Idle, + ConnectionChanged, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct TxEnded { + session_id: String, + reason: EndReason, + /// False when the rollback failed and the socket was closed instead (the + /// server rolls back on its own when it sees the socket go). + rolled_back: bool, +} + +/// Roll the session back and give its connection back to the pool, or close +/// it if the rollback does not come back clean. True when it rolled back. +async fn release(mut session: TxSession) -> bool { + let ok = matches!( + tokio::time::timeout(RELEASE_TIMEOUT, run_statement(&mut session.conn, "ROLLBACK")).await, + Ok(Ok(_)) + ); + if !ok { + log::info!("tx: rollback failed, closing the {} connection", session.conn.engine()); + session.conn.close_hard(); + } + ok +} + +/// End sessions taken out of the map, tell the window, and report how many. +async fn end_sessions(ended: Vec<(String, TxSession)>, reason: EndReason) -> usize { + let n = ended.len(); + for (id, session) in ended { + let rolled_back = release(session).await; + if let Some(app) = APP.get() { + let _ = app.emit("tx-ended", TxEnded { session_id: id, reason, rolled_back }); + } + } + n +} + +/// The active connection is about to be replaced, parked or closed. Every open +/// session belongs to the old one: roll them all back. Without this, a tab's +/// session kept a live connection to the database just left, and its next +/// statement ran there while the window showed the new one. +pub fn connection_changed() { + EPOCH.fetch_add(1, Ordering::SeqCst); + let ended: Vec<(String, TxSession)> = SESSIONS.lock().unwrap().drain().collect(); + if ended.is_empty() { + return; + } + tauri::async_runtime::spawn(end_sessions(ended, EndReason::ConnectionChanged)); +} + +/// Roll back sessions idle past `IDLE_TIMEOUT`. Runs on a timer (lib.rs) as well +/// as on every begin and status call. +pub async fn sweep_idle() -> usize { + let ended: Vec<(String, TxSession)> = { + let mut sessions = SESSIONS.lock().unwrap(); + let stale: Vec = sessions + .iter() + .filter(|(_, s)| s.last_used.elapsed() >= IDLE_TIMEOUT) + .map(|(id, _)| id.clone()) + .collect(); + stale.into_iter().filter_map(|id| sessions.remove(&id).map(|s| (id, s))).collect() + }; + end_sessions(ended, EndReason::Idle).await +} + +/// Ids of the open sessions, for the quit guard. +#[tauri::command] +pub fn tx_open_sessions() -> Vec { + SESSIONS.lock().unwrap().keys().cloned().collect() } #[derive(Debug, Clone, Serialize)] @@ -74,11 +226,14 @@ pub struct TxStatus { /// Milliseconds since BEGIN, so the UI can warn about a long-held lock. pub open_ms: u64, pub engine: Option, + /// Other sessions waiting on a lock this transaction holds. None when the + /// engine can't say (SQLite) or the server would not tell us. + pub blocking: Option, } impl TxStatus { fn closed() -> Self { - Self { open: false, statements: 0, rows_affected: 0, open_ms: 0, engine: None } + Self { open: false, statements: 0, rows_affected: 0, open_ms: 0, engine: None, blocking: None } } fn of(session: &TxSession) -> Self { @@ -88,6 +243,7 @@ impl TxStatus { rows_affected: session.rows_affected, open_ms: session.started.elapsed().as_millis() as u64, engine: Some(session.conn.engine().to_string()), + blocking: None, } } } @@ -99,40 +255,92 @@ impl TxStatus { // uncontended across awaits, and makes a second concurrent command for the same // session fail fast instead of interleaving statements on one connection. -/// Remove sessions idle past the timeout. Their connections are dropped, which -/// returns them to the pool; the server rolls back the abandoned transaction. -fn sweep_idle(state: &State<'_, TxState>) { - let mut sessions = state.sessions.lock().unwrap(); - sessions.retain(|_, s| s.last_used.elapsed() < IDLE_TIMEOUT); +fn take(id: &str) -> Option { + SESSIONS.lock().unwrap().remove(id) } -fn take(state: &State<'_, TxState>, id: &str) -> Option { - state.sessions.lock().unwrap().remove(id) +/// Put a session back after a command. If the connection changed while the +/// command ran, `connection_changed` has already drained the map, so the +/// session comes back to a world that has moved on: end it instead. +async fn put(id: &str, session: TxSession) -> Result<(), String> { + if session.epoch != EPOCH.load(Ordering::SeqCst) { + let id = id.to_string(); + end_sessions(vec![(id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } + SESSIONS.lock().unwrap().insert(id.to_string(), session); + Ok(()) } -fn put(state: &State<'_, TxState>, id: &str, session: TxSession) { - state.sessions.lock().unwrap().insert(id.to_string(), session); -} +const LEFT_CONNECTION: &str = + "This transaction was on a connection you have since left, so it was rolled back. Nothing it did was saved."; fn no_session(id: &str) -> String { format!("No open transaction for {id}. Start one before running statements in it.") } +/// This session's server-side id, so `tx_status` can ask who it is blocking. +async fn blocker_for(conn: &mut TxConn, db: &ActiveConnection) -> Option { + match (conn, db) { + (TxConn::Postgres(c), ActiveConnection::Postgres(pool)) => { + let pid = sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()").fetch_one(&mut **c).await.ok()?; + Some(Blocker::Postgres(pool.clone(), pid)) + } + (TxConn::Mysql(c), ActiveConnection::Mysql(pool)) => { + let id = sqlx::query_scalar::<_, u64>("SELECT CONNECTION_ID()").fetch_one(&mut **c).await.ok()?; + Some(Blocker::Mysql(pool.clone(), id)) + } + _ => None, + } +} + +/// Sessions waiting on a lock this one holds, asked on a second connection. +/// None when the server won't say (MySQL needs performance_schema access). +async fn blocking_count(blocker: &Blocker) -> Option { + let ask = async { + match blocker { + // Everyone held up by it, not only those waiting on it directly: + // a second UPDATE of the same row waits on the first waiter, which + // waits on this transaction (measured: pg_blocking_pids names only + // the next link of the chain). + Blocker::Postgres(pool, pid) => sqlx::query_scalar::<_, i64>( + "WITH RECURSIVE held(pid) AS ( \ + SELECT pid FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)) \ + UNION \ + SELECT a.pid FROM pg_stat_activity a JOIN held h ON h.pid = ANY(pg_blocking_pids(a.pid)) \ + ) SELECT count(*)::bigint FROM held", + ) + .bind(pid) + .fetch_one(pool) + .await + .ok(), + Blocker::Mysql(pool, id) => sqlx::query_scalar::<_, i64>( + "SELECT COUNT(*) FROM performance_schema.data_lock_waits w \ + JOIN performance_schema.threads t ON t.THREAD_ID = w.BLOCKING_THREAD_ID \ + WHERE t.PROCESSLIST_ID = ?", + ) + .bind(id) + .fetch_one(pool) + .await + .ok(), + } + }; + tokio::time::timeout(Duration::from_secs(2), ask).await.ok().flatten() +} + // ── Commands ────────────────────────────────────────────────────────────────── /// Open a transaction and hold its connection until commit or rollback. #[tauri::command] -pub async fn tx_begin( - db: Db<'_>, - tx: State<'_, TxState>, - session_id: String, -) -> Result { - sweep_idle(&tx); - if tx.sessions.lock().unwrap().contains_key(&session_id) { +pub async fn tx_begin(db: Db<'_>, session_id: String) -> Result { + sweep_idle().await; + if SESSIONS.lock().unwrap().contains_key(&session_id) { return Err("A transaction is already open here. Commit or roll it back first.".into()); } + let epoch = EPOCH.load(Ordering::SeqCst); + let active = require_conn(&db)?; - let mut conn = match require_conn(&db)? { + let mut conn = match &active { ActiveConnection::Postgres(pool) => TxConn::Postgres( pool.acquire().await.map_err(|e| format!("Could not open a transaction: {e}"))?, ), @@ -142,9 +350,9 @@ pub async fn tx_begin( ActiveConnection::Sqlite(pool) => TxConn::Sqlite( pool.acquire().await.map_err(|e| format!("Could not open a transaction: {e}"))?, ), - ActiveConnection::Duckdb(_) | ActiveConnection::Mssql(_) | ActiveConnection::Oracle(_) => { - return Err("Explicit transactions are not supported for this engine yet".into()) - } + ActiveConnection::Duckdb(h) => TxConn::Duckdb(super::duckdb::open_tx_conn(h).await.map_err(|e| format!("Could not open a transaction: {e}"))?), + ActiveConnection::Mssql(h) => TxConn::Mssql(super::mssql::open_tx_client(h).await.map_err(|e| format!("Could not open a transaction: {e}"))?), + ActiveConnection::Oracle(h) => TxConn::Oracle(super::oracle::open_tx_session(h).await.map_err(|e| format!("Could not open a transaction: {e}"))?), ActiveConnection::D1(_) | ActiveConnection::LibSql(_) => { return Err("Explicit transactions need a persistent connection, which HTTP-based engines do not have".into()) } @@ -152,42 +360,48 @@ pub async fn tx_begin( return Err("ClickHouse does not support transactions".into()) } ActiveConnection::Posthog(_) => return Err("PostHog does not support transactions".into()), + ActiveConnection::Spanner(_) => return Err("Explicit transactions are not supported for Spanner yet; each statement commits on its own".into()), + ActiveConnection::Bigquery(_) => return Err("Explicit transactions are not supported for BigQuery yet; each statement commits on its own".into()), + ActiveConnection::Snowflake(_) => return Err("Explicit transactions are not supported for Snowflake yet; each statement commits on its own".into()), + ActiveConnection::Odbc(h) => TxConn::Odbc(super::odbc::open_tx(h).await.map_err(|e| format!("Could not open a transaction: {e}"))?), ActiveConnection::Redis(_) => return Err("Redis does not support SQL transactions".into()), ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => return Err("DynamoDB does not support SQL transactions here".into()), }; run_statement(&mut conn, "BEGIN").await.map_err(|e| format!("Could not begin: {e}"))?; - // A statement that hangs inside a transaction holds its locks for as long as - // it runs, so cap it the same way the autocommit path does. if let TxConn::Postgres(_) = conn { + // A statement that hangs inside a transaction holds its locks for as + // long as it runs, so cap it the same way the autocommit path does. + let _ = run_statement(&mut conn, &format!("SET LOCAL statement_timeout = {EXECUTE_SQL_TIMEOUT_MS}")).await; + // The server's own backstop for a session this process never comes + // back to. Postgres 9.6+; older servers refuse it, which is harmless. let _ = run_statement( &mut conn, - &format!("SET LOCAL statement_timeout = {EXECUTE_SQL_TIMEOUT_MS}"), + &format!("SET LOCAL idle_in_transaction_session_timeout = '{SERVER_IDLE_TIMEOUT}'"), ) .await; } + let blocker = blocker_for(&mut conn, &active).await; let now = Instant::now(); let session = TxSession { conn, + epoch, + blocker, statements: 0, rows_affected: 0, started: now, last_used: now, }; let status = TxStatus::of(&session); - put(&tx, &session_id, session); + put(&session_id, session).await?; Ok(status) } /// Run SQL inside the open transaction. Nothing is visible to anyone else until /// the transaction commits. #[tauri::command] -pub async fn tx_execute( - tx: State<'_, TxState>, - session_id: String, - sql: String, -) -> Result { +pub async fn tx_execute(session_id: String, sql: String) -> Result { let trimmed = sql.trim().to_string(); if trimmed.is_empty() { return Err("Query is empty".into()); @@ -204,7 +418,11 @@ pub async fn tx_execute( } } - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; + let mut session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + if session.epoch != EPOCH.load(Ordering::SeqCst) { + end_sessions(vec![(session_id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } let started = Instant::now(); let result = execute_in(&mut session.conn, &trimmed).await; @@ -221,7 +439,7 @@ pub async fn tx_execute( session.statements += 1; } } - put(&tx, &session_id, session); + put(&session_id, session).await?; result.map(|mut r| { r.query_ms = started.elapsed().as_millis() as u64; @@ -232,40 +450,60 @@ pub async fn tx_execute( /// Commit the open transaction and give the connection back. #[tauri::command] -pub async fn tx_commit(tx: State<'_, TxState>, session_id: String) -> Result { - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; +pub async fn tx_commit(session_id: String) -> Result { + let mut session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + if session.epoch != EPOCH.load(Ordering::SeqCst) { + end_sessions(vec![(session_id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } match run_statement(&mut session.conn, "COMMIT").await { - // The connection is dropped with `session`, returning it to the pool. + // Clean: the connection is out of its transaction, back to the pool. Ok(_) => Ok(TxStatus::closed()), Err(e) => { // The commit failed, so the transaction is neither applied nor - // cleanly closed. Drop the connection rather than hand back a - // session whose state nobody can describe. - Err(format!("Could not commit: {e}")) + // cleanly closed. Roll back what is left, or close the socket. + release(session).await; + Err(format!("Could not commit: {e}. Nothing was saved.")) } } } /// Roll the open transaction back and give the connection back. #[tauri::command] -pub async fn tx_rollback(tx: State<'_, TxState>, session_id: String) -> Result { - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; - run_statement(&mut session.conn, "ROLLBACK") - .await - .map_err(|e| format!("Could not roll back: {e}"))?; - Ok(TxStatus::closed()) +pub async fn tx_rollback(session_id: String) -> Result { + let session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + // Whatever happens the session is over: a failed ROLLBACK closes the + // socket, and the server rolls back when it sees it go. + if release(session).await { + Ok(TxStatus::closed()) + } else { + Err("The rollback did not complete, so the connection was closed. The server rolls back a closed connection's transaction, so nothing was saved.".into()) + } } /// What the UI needs to render the transaction indicator. #[tauri::command] -pub async fn tx_status(tx: State<'_, TxState>, session_id: String) -> Result { - sweep_idle(&tx); - let sessions = tx.sessions.lock().unwrap(); - Ok(sessions.get(&session_id).map_or_else(TxStatus::closed, TxStatus::of)) +pub async fn tx_status(session_id: String) -> Result { + sweep_idle().await; + let (mut status, blocker) = { + let sessions = SESSIONS.lock().unwrap(); + match sessions.get(&session_id) { + None => return Ok(TxStatus::closed()), + Some(s) => ( + TxStatus::of(s), + s.blocker.as_ref().map(|b| match b { + Blocker::Postgres(p, pid) => Blocker::Postgres(p.clone(), *pid), + Blocker::Mysql(p, id) => Blocker::Mysql(p.clone(), *id), + }), + ), + } + }; + if let Some(b) = blocker { + status.blocking = blocking_count(&b).await; + } + Ok(status) } -// ── Execution ───────────────────────────────────────────────────────────────── - /// The first word of a statement, lowercased, skipping leading comments. fn leading_keyword(sql: &str) -> Option { let mut rest = sql.trim_start(); @@ -291,10 +529,56 @@ async fn run_statement(conn: &mut TxConn, sql: &str) -> Result { TxConn::Postgres(c) => sqlx::query(sql).execute(&mut **c).await.map(|r| r.rows_affected()), TxConn::Mysql(c) => sqlx::query(sql).execute(&mut **c).await.map(|r| r.rows_affected()), TxConn::Sqlite(c) => sqlx::query(sql).execute(&mut **c).await.map(|r| r.rows_affected()), + // BEGIN / COMMIT / ROLLBACK in each engine's own words. + TxConn::Duckdb(h) => { + let stmt = if sql == "BEGIN" { "BEGIN TRANSACTION" } else { sql }; + return super::duckdb::batch(h, stmt).await.map(|_| 0); + } + TxConn::Mssql(h) => { + let stmt = match sql { + "BEGIN" => "BEGIN TRANSACTION", + "COMMIT" => "COMMIT TRANSACTION", + // A failed statement can have ended the transaction already. + "ROLLBACK" => "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION", + other => other, + }; + return super::mssql::batch(h, stmt).await.map(|_| 0); + } + TxConn::Odbc(h) => { + return match sql { + // Autocommit is off on this connection: the first statement + // opens the transaction. + "BEGIN" => Ok(0), + "COMMIT" => super::odbc::commit(h).await.map(|_| 0), + "ROLLBACK" => super::odbc::rollback(h).await.map(|_| 0), + other => super::odbc::query(h, other).await.map(|r| r.row_count.unwrap_or(0).max(0) as u64), + }; + } + TxConn::Oracle(h) => { + return match sql { + // Oracle starts a transaction with its first statement. + "BEGIN" => Ok(0), + "COMMIT" => super::oracle::commit(h).await.map(|_| 0), + "ROLLBACK" => super::oracle::rollback(h).await.map(|_| 0), + other => super::oracle::execute_in_tx(h, other).await.map(|r| r.row_count.unwrap_or(0).max(0) as u64), + }; + } } .map_err(|e| e.to_string()) } +/// A statement on one of the single-connection engines, inside its open +/// transaction. None for the pooled engines, which take the sqlx path. +async fn execute_on_handle(conn: &TxConn, stmt: &str) -> Option> { + Some(match conn { + TxConn::Duckdb(h) => super::duckdb::execute_sql(h, stmt).await, + TxConn::Mssql(h) => super::mssql::execute_sql(h, stmt).await, + TxConn::Oracle(h) => super::oracle::execute_in_tx(h, stmt).await, + TxConn::Odbc(h) => super::odbc::query(h, stmt).await, + _ => return None, + }) +} + /// Run the user's SQL, returning rows when the last statement produces them. /// /// Mirrors the autocommit executor: a script is split so a multi-statement @@ -308,6 +592,23 @@ async fn execute_in(conn: &mut TxConn, sql: &str) -> Result { let last = stmts.len() - 1; let mut affected: u64 = 0; + if matches!(conn, TxConn::Duckdb(_) | TxConn::Mssql(_) | TxConn::Oracle(_) | TxConn::Odbc(_)) { + let mut out = None; + for stmt in &stmts { + let r = execute_on_handle(conn, stmt).await.expect("single-connection engine").map_err(|e| format!("Query failed: {e}"))?; + if r.columns.is_empty() { + affected += r.row_count.unwrap_or(0).max(0) as u64; + } + out = Some(r); + } + let mut r = out.expect("non-empty"); + if r.columns.is_empty() { + r.row_count = Some(affected as i64); + r.message = Some(format!("{affected} row{} affected (not committed yet)", if affected == 1 { "" } else { "s" })); + } + return Ok(r); + } + for (i, stmt) in stmts.iter().enumerate() { if i == last && is_row_returning_sql(stmt) { return fetch_rows(conn, stmt).await; @@ -386,6 +687,9 @@ async fn fetch_rows(conn: &mut TxConn, stmt: &str) -> Result ); } } + TxConn::Duckdb(_) | TxConn::Mssql(_) | TxConn::Oracle(_) | TxConn::Odbc(_) => { + return execute_on_handle(conn, stmt).await.unwrap_or_else(|| Err("unsupported".into())); + } } let count = rows.len() as i64; @@ -403,6 +707,225 @@ async fn fetch_rows(conn: &mut TxConn, stmt: &str) -> Result mod tests { use super::leading_keyword; + /// An ODBC transaction on its own connection (STROKE_TEST_ODBC): a + /// rollback leaves nothing behind, uncommitted rows stay out of the + /// shared connection's sight, and a commit lands them. + #[tokio::test] + async fn live_odbc_transaction() { + let Ok(cs) = std::env::var("STROKE_TEST_ODBC") else { return }; + let cfg = super::super::odbc::OdbcConfig { name: "t".into(), preset: None, dsn: None, connection_string: Some(cs), user: None, password: None, ssh: None, target_host: None, target_port: None }; + let shared = super::super::odbc::connect(&cfg).await.unwrap(); + let t = format!("stroke_tx_{}", std::process::id()); + super::super::odbc::query(&shared, &format!("CREATE TABLE {t} (id INTEGER PRIMARY KEY)")).await.unwrap(); + let count = |h: super::super::odbc::OdbcHandle, t: String| async move { + super::super::odbc::query(&h, &format!("SELECT COUNT(*) FROM {t}")).await.unwrap().rows[0][0].as_i64().unwrap() + }; + + let mut tx = super::TxConn::Odbc(super::super::odbc::open_tx(&shared).await.unwrap()); + super::run_statement(&mut tx, "BEGIN").await.unwrap(); + assert_eq!(super::run_statement(&mut tx, &format!("INSERT INTO {t} VALUES (1)")).await.unwrap(), 1); + super::run_statement(&mut tx, "ROLLBACK").await.unwrap(); + assert_eq!(count(shared.clone(), t.clone()).await, 0, "a rolled-back insert is gone"); + + super::run_statement(&mut tx, &format!("INSERT INTO {t} VALUES (2)")).await.unwrap(); + let inside = super::execute_in(&mut tx, &format!("SELECT COUNT(*) FROM {t}")).await.unwrap(); + assert_eq!(inside.rows[0][0].as_i64(), Some(1), "the transaction sees its own row"); + // SQLite locks the file for a writer; elsewhere the shared connection + // simply doesn't see the uncommitted row. + if !shared.info.dbms.to_ascii_lowercase().contains("sqlite") { + assert_eq!(count(shared.clone(), t.clone()).await, 0, "uncommitted rows are not visible outside"); + } + super::run_statement(&mut tx, "COMMIT").await.unwrap(); + assert_eq!(count(shared.clone(), t.clone()).await, 1, "a commit lands the row"); + drop(tx); + super::super::odbc::query(&shared, &format!("DROP TABLE {t}")).await.unwrap(); + } + + fn live_session(conn: super::TxConn) -> super::TxSession { + super::TxSession { + conn, + epoch: 0, + blocker: None, + statements: 0, + rows_affected: 0, + started: std::time::Instant::now(), + last_used: std::time::Instant::now(), + } + } + + fn count_of(r: &super::SqlResult) -> i64 { + let v = &r.rows[0][0]; + v.as_i64().or_else(|| v.as_str().and_then(|s| s.parse().ok())).or_else(|| v.as_f64().map(|f| f as i64)).unwrap_or(-1) + } + + /// One engine's transaction, end to end through tx.rs: BEGIN, a write + /// that only the transaction sees, ROLLBACK; then BEGIN, write, COMMIT; + /// then a transaction abandoned mid-way, which must roll back on release. + /// `outside` reads through the shared handle. + async fn tx_round_trip(open: impl Fn() -> Fut, outside: F, table: &str) + where + Fut: std::future::Future, + F: Fn(String) -> std::pin::Pin>>, + { + use super::{execute_in, release, run_statement}; + let count = format!("SELECT COUNT(*) FROM {table}"); + let insert = format!("INSERT INTO {table} (v) VALUES (1)"); + + let mut c = open().await; + run_statement(&mut c, "BEGIN").await.unwrap(); + let w = execute_in(&mut c, &insert).await.unwrap(); + assert!(w.message.unwrap_or_default().contains("not committed")); + assert_eq!(count_of(&execute_in(&mut c, &count).await.unwrap()), 1, "the transaction sees its own row"); + run_statement(&mut c, "ROLLBACK").await.unwrap(); + assert_eq!(outside(count.clone()).await, 0, "rolled back"); + + run_statement(&mut c, "BEGIN").await.unwrap(); + execute_in(&mut c, &insert).await.unwrap(); + run_statement(&mut c, "COMMIT").await.unwrap(); + assert_eq!(outside(count.clone()).await, 1, "committed"); + + let mut c2 = open().await; + run_statement(&mut c2, "BEGIN").await.unwrap(); + execute_in(&mut c2, &insert).await.unwrap(); + release(live_session(c2)).await; + drop(c); + assert_eq!(outside(count.clone()).await, 1, "abandoned transaction rolled back"); + } + + // STROKE_TEST_MSSQL=127.0.0.1:11433:sa:password cargo test --lib tx::tests::mssql_live + #[tokio::test] + async fn mssql_live_transaction() { + let Ok(spec) = std::env::var("STROKE_TEST_MSSQL") else { return }; + let p: Vec<&str> = spec.splitn(4, ':').collect(); + let cfg = super::super::connection::MssqlConfig { + name: "live".into(), host: p[0].into(), port: p[1].parse().unwrap(), database: "master".into(), + user: p[2].into(), password: p[3].into(), encrypt: false, trust_cert: true, ssh: None, via: None, + }; + let shared = super::super::connection::open_mssql(&cfg).await.unwrap(); + super::super::mssql::batch(&shared, "IF OBJECT_ID('stroke_tx_live') IS NOT NULL DROP TABLE stroke_tx_live; CREATE TABLE stroke_tx_live (v int)").await.unwrap(); + let s2 = shared.clone(); + tx_round_trip( + || { let s = shared.clone(); async move { super::TxConn::Mssql(super::super::mssql::open_tx_client(&s).await.unwrap()) } }, + move |sql| { let s = s2.clone(); Box::pin(async move { count_of(&super::super::mssql::execute_sql(&s, &sql).await.unwrap()) }) }, + "stroke_tx_live", + ).await; + } + + // STROKE_TEST_ORACLE=app/pw@//127.0.0.1:11521/FREEPDB1 STROKE_ORACLE_CLIENT_DIR=... cargo test --lib tx::tests::oracle_live + #[tokio::test] + async fn oracle_live_transaction() { + let Ok(url) = std::env::var("STROKE_TEST_ORACLE") else { return }; + let (creds, cs) = url.split_once('@').unwrap(); + let (user, password) = creds.split_once('/').unwrap(); + let cfg = super::super::connection::OracleConfig { + ssh: None, name: "live".into(), host: String::new(), port: 1521, service_name: String::new(), sid: String::new(), + connect_string: cs.into(), user: user.into(), password: password.into(), + client_lib_dir: std::env::var("STROKE_ORACLE_CLIENT_DIR").unwrap_or_default(), + }; + super::super::oracle::prepare_client(&cfg.client_lib_dir).await.unwrap(); + let shared = super::super::oracle::connect(&cfg).await.unwrap(); + let _ = super::super::oracle::execute_sql(&shared, "DROP TABLE stroke_tx_live").await; + super::super::oracle::execute_sql(&shared, "CREATE TABLE stroke_tx_live (v NUMBER)").await.unwrap(); + let s2 = shared.clone(); + tx_round_trip( + || { let s = shared.clone(); async move { super::TxConn::Oracle(super::super::oracle::open_tx_session(&s).await.unwrap()) } }, + move |sql| { let s = s2.clone(); Box::pin(async move { count_of(&super::super::oracle::execute_sql(&s, &sql).await.unwrap()) }) }, + "stroke_tx_live", + ).await; + } + + #[tokio::test] + async fn duckdb_transaction_round_trip() { + let shared: super::super::connection::DuckdbHandle = std::sync::Arc::new(std::sync::Mutex::new(::duckdb::Connection::open_in_memory().unwrap())); + super::super::duckdb::batch(&shared, "CREATE TABLE stroke_tx_live (v INTEGER)").await.unwrap(); + let s2 = shared.clone(); + tx_round_trip( + || { let s = shared.clone(); async move { super::TxConn::Duckdb(super::super::duckdb::open_tx_conn(&s).await.unwrap()) } }, + move |sql| { let s = s2.clone(); Box::pin(async move { count_of(&super::super::duckdb::execute_sql(&s, &sql).await.unwrap()) }) }, + "stroke_tx_live", + ).await; + } + + // Live: a released session must give back a connection that is out of its + // transaction. Before `release`, the idle sweep dropped the PoolConnection, + // sqlx returned it to the pool still inside the BEGIN, and the next user of + // the pool ran in the abandoned transaction. + // STROKE_TEST_PG_URL=postgres://postgres@127.0.0.1:5433/postgres \ + // cargo test --lib tx::tests::release_ -- --nocapture + #[tokio::test] + async fn release_returns_a_clean_connection() { + use super::*; + let Ok(url) = std::env::var("STROKE_TEST_PG_URL") else { return }; + // One connection, so the next acquire gets the one we released. + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap(); + sqlx::query("CREATE TABLE IF NOT EXISTS stroke_tx_release (v int)").execute(&pool).await.unwrap(); + sqlx::query("TRUNCATE stroke_tx_release").execute(&pool).await.unwrap(); + + let session = |conn| TxSession { + conn, + epoch: 0, + blocker: None, + statements: 0, + rows_affected: 0, + started: Instant::now(), + last_used: Instant::now(), + }; + let open = |pool: &sqlx::PgPool| { + let pool = pool.clone(); + async move { + let mut conn = TxConn::Postgres(pool.acquire().await.unwrap()); + run_statement(&mut conn, "BEGIN").await.unwrap(); + run_statement(&mut conn, "INSERT INTO stroke_tx_release VALUES (1)").await.unwrap(); + conn + } + }; + let in_tx = |pool: &sqlx::PgPool| { + let pool = pool.clone(); + async move { + // Assigned only inside a transaction that wrote something. + sqlx::query_scalar::<_, Option>("SELECT txid_current_if_assigned()") + .fetch_one(&pool) + .await + .unwrap() + .is_some() + } + }; + + // What the sweep used to do: drop it. + drop(session(open(&pool).await)); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(in_tx(&pool).await, "a dropped session leaks its transaction into the pool"); + // Clean up after the demonstration. + sqlx::query("ROLLBACK").execute(&pool).await.unwrap(); + + // What every exit does now. + assert!(release(session(open(&pool).await)).await); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!in_tx(&pool).await, "a released session must not leave a transaction open"); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM stroke_tx_release").fetch_one(&pool).await.unwrap(); + assert_eq!(rows, 0, "the uncommitted insert must be gone"); + sqlx::query("DROP TABLE stroke_tx_release").execute(&pool).await.unwrap(); + } + + // Live: switching connections ends every open session. + #[tokio::test] + async fn connection_change_ends_sessions() { + use super::*; + let Ok(url) = std::env::var("STROKE_TEST_PG_URL") else { return }; + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(2).connect(&url).await.unwrap(); + let mut conn = TxConn::Postgres(pool.acquire().await.unwrap()); + run_statement(&mut conn, "BEGIN").await.unwrap(); + let epoch = EPOCH.load(Ordering::SeqCst); + let now = Instant::now(); + let s = TxSession { conn, epoch, blocker: None, statements: 0, rows_affected: 0, started: now, last_used: now }; + put("test-switch", s).await.unwrap(); + assert!(tx_open_sessions().contains(&"test-switch".to_string())); + connection_changed(); + assert!(!tx_open_sessions().contains(&"test-switch".to_string())); + let err = tx_execute("test-switch".into(), "SELECT 1".into()).await.unwrap_err(); + assert!(err.contains("No open transaction"), "{err}"); + } + #[test] fn finds_the_first_keyword() { assert_eq!(leading_keyword("SELECT 1").as_deref(), Some("select")); diff --git a/src-tauri/src/db/wide_columns.rs b/src-tauri/src/db/wide_columns.rs index 58b65b38..9fb3dce1 100644 --- a/src-tauri/src/db/wide_columns.rs +++ b/src-tauri/src/db/wide_columns.rs @@ -85,7 +85,21 @@ const TOAST_SAMPLE_FLOOR: i64 = 1024 * 1024; /// so it is worth about 260ms a page on the table it was measured against, and /// it is what makes the page size bounded rather than hopeful. Below the floor /// no amount of compression can reach the cap, so those rows skip it. -const TEXT_CHECK_FLOOR: usize = 4 * 1024; +const TEXT_CHECK_FLOOR: usize = 1024; + +/// Text size past which a wide column's value ships as a preview in a page. +/// +/// The grid draws about forty characters of a cell, yet everything under the +/// 256KB cap used to ship whole: a 50-row page of a resume table moved 823KB +/// of one jsonb column (1.1MB in all), and over a slower link a few of those +/// in flight left the grid on skeletons. Past 8KB the value arrives as its +/// size and its first `PREVIEW_CHARS`; that page is 50KB of the column (341KB +/// in all), and the value loads when the cell is opened or edited. +const GRID_INLINE_BYTES: usize = 8 * 1024; + +/// How much of a previewed value ships: enough for the grid, a tooltip and +/// the first lines of the JSON view. +const PREVIEW_CHARS: usize = 512; #[derive(Clone, Debug)] pub struct WideColumn { @@ -399,12 +413,14 @@ pub fn projection(all_columns: &[String], wide: &[WideColumn]) -> Option "CASE WHEN pg_column_size({quoted}) > {cap} \ THEN jsonb_build_object('__strokeOversize', true, 'dataType', '{col_type}', \ 'bytes', pg_column_size({quoted})) \ - WHEN pg_column_size({quoted}) > {floor} AND length({quoted}::text) > {cap} \ + WHEN pg_column_size({quoted}) > {floor} AND octet_length({quoted}::text) > {inline} \ THEN jsonb_build_object('__strokeOversize', true, 'dataType', '{col_type}', \ - 'bytes', octet_length({quoted}::text)) \ + 'bytes', octet_length({quoted}::text), 'preview', left({quoted}::text, {preview})) \ ELSE jsonb_build_object('__strokeInline', to_jsonb({quoted})) END AS {quoted}", cap = CELL_VALUE_CAP, floor = TEXT_CHECK_FLOOR, + inline = GRID_INLINE_BYTES, + preview = PREVIEW_CHARS, ) } else { quoted @@ -468,8 +484,13 @@ mod tests { assert!(sql.starts_with("\"id\", CASE WHEN pg_column_size(\"resume\")")); assert!(sql.contains("'__strokeOversize', true")); assert!(sql.contains("'dataType', 'jsonb'")); - // No preview: building one would detoast every over-cap value on the page. - assert!(!sql.contains("left(")); + // No preview past the cap: building one would detoast every over-cap + // value on the page. Under it the value is read for its length anyway, + // so that branch carries the first 512 characters. + let (over_cap, under_cap) = sql.split_once("WHEN pg_column_size(\"resume\") > 1024").expect("two branches"); + assert!(!over_cap.contains("left(")); + assert!(under_cap.contains("'preview', left(\"resume\"::text, 512)")); + assert!(under_cap.contains("octet_length(\"resume\"::text) > 8192")); // The compressed size is the cheap gate; the text length is the honest one. assert!(sql.contains("length(\"resume\"::text) >")); assert!(sql.contains("AS \"resume\"")); diff --git a/src-tauri/src/launch.rs b/src-tauri/src/launch.rs index 4b2ed430..73a3a702 100644 --- a/src-tauri/src/launch.rs +++ b/src-tauri/src/launch.rs @@ -61,6 +61,84 @@ pub fn parse_link(link: &str) -> Option { Some(OpenRequest { uri, name }) } +/// Where shared studios open. A debug build takes `STROKE_STUDIO_URL` (a local +/// stroke-web) so the relay can be tested without stroke.click. +fn studio_base() -> String { + #[cfg(debug_assertions)] + if let Ok(u) = std::env::var("STROKE_STUDIO_URL") { + if !u.trim().is_empty() { + return u.trim().trim_end_matches('/').to_string(); + } + } + "https://stroke.click/studio".to_string() +} + +/// `stroke://studio?relay=&key=[&open=]`: a shared web +/// studio (what `npx strokedb --share` and its MCP server print for an AI agent +/// on another machine). Returns the stroke.click page to open, built here from +/// checked parts: a link can only ever point a window at the studio itself. +pub fn parse_studio_link(link: &str) -> Option { + let url = Url::parse(link.trim()).ok()?; + if !SCHEMES.contains(&url.scheme()) { + return None; + } + let action = url.host_str().unwrap_or_else(|| url.path().trim_matches('/')); + if action != "studio" { + return None; + } + let b64u = |s: &str, min: usize, max: usize| { + (min..=max).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + }; + let (mut relay, mut key, mut open) = (None, None, None); + for (k, v) in url.query_pairs() { + match &*k { + "relay" => relay = Some(v.to_string()), + "key" => key = Some(v.to_string()), + "open" => open = Some(v.to_string()), + _ => {} + } + } + let relay = relay.filter(|r| b64u(r, 22, 64))?; + let key = key.filter(|k| b64u(k, 43, 43))?; + // Room and key are base64url, safe in a fragment as they are. + let mut frag = format!("relay={relay}&key={key}"); + if let Some(t) = open.filter(|t| !t.is_empty() && t.len() <= 200 && !t.chars().any(char::is_control)) { + frag.push_str("&open="); + frag.push_str(&urlencoding::encode(&t)); + } + Some(format!("{}#{frag}", studio_base())) +} + +/// Show a shared studio in a window of its own, one per room: a second link to +/// the same room (an agent opening another table) reuses it. The page is a +/// remote one with no access to the app's commands. +pub fn open_studio_window(app: &AppHandle, page: &str) { + let Ok(target) = Url::parse(page) else { return }; + // The room is base64url (checked in parse_studio_link), fine in a label. + let room: String = target + .fragment() + .and_then(|f| f.split('&').find_map(|kv| kv.strip_prefix("relay="))) + .unwrap_or_default() + .chars() + .take(16) + .collect(); + let label = format!("studio-{room}"); + if let Some(w) = app.get_webview_window(&label) { + let _ = w.navigate(target); + let _ = w.unminimize(); + let _ = w.set_focus(); + return; + } + let built = tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::External(target)) + .title("Stroke \u{b7} Shared studio") + .inner_size(1280.0, 820.0) + .min_inner_size(640.0, 420.0) + .build(); + if let Err(e) = built { + log::warn!("Could not open the shared studio: {e}"); + } +} + /// One command-line argument: a `stroke://` link, a connection URL, or a path to /// a database file. Flags (and macOS's `-psn_…`) are not connections. pub fn parse_arg(arg: &str, cwd: &Path) -> Option { @@ -122,6 +200,27 @@ pub fn take_open_request(state: tauri::State<'_, LaunchState>) -> Option Option<&'static str> { /// The newest build of a Postgres major ("16" → "16.11.0"). async fn pg_release(major: &str) -> Result { let url = "https://api.github.com/repos/theseus-rs/postgresql-binaries/releases?per_page=100"; - let releases: Vec = reqwest::Client::new() + let releases: Vec = crate::proxy::http_builder(crate::proxy::Kind::App).build().map_err(|e| e.to_string())? .get(url) .header("user-agent", "stroke-desktop") .header("accept", "application/vnd.github+json") @@ -332,7 +332,7 @@ async fn pg_install(app: &AppHandle, id: &str, major: &str) -> Result Self::Mongo, "redis" => Self::Redis, "elasticsearch" | "opensearch" => Self::Elastic, - "couchdb" | "firestore" => Self::ReadOnlyDoc, + "couchdb" | "firestore" | "influxdb" => Self::ReadOnlyDoc, "dynamodb" => Self::Dynamo, + "neo4j" => Self::Cypher, _ => Self::Sql, } } @@ -73,6 +76,7 @@ pub fn script_level_in(dialect: Dialect, sql: &str) -> u8 { Dialect::Redis => redis_level(sql), Dialect::Dynamo => dynamo_level(sql), Dialect::ReadOnlyDoc => READ, + Dialect::Cypher => crate::db::neo4j::cypher_level(sql), Dialect::Elastic => match crate::db::elastic::parse(sql) { Ok(crate::db::elastic::Statement::Raw { method, path, .. }) => crate::db::elastic::request_level(&method, &path), // SQL, index.search/get/count: reads. Anything unparsable is refused by the console itself. @@ -686,6 +690,9 @@ mod tests { assert_eq!(d(r#"{"operation": "DeleteTable", "input": {"TableName": "t"}}"#), DANGEROUS); assert_eq!(d(r#"{"operation": "Nope"}"#), DANGEROUS); assert_eq!(Dialect::for_driver("dynamodb"), Dialect::Dynamo); + assert_eq!(Dialect::for_driver("neo4j"), Dialect::Cypher); + assert_eq!(script_level_in(Dialect::Cypher, "MATCH (n) WITH n DETACH DELETE n"), WRITE); + assert_eq!(script_level_in(Dialect::Cypher, "MATCH (n) RETURN n"), READ); let m = |s: &str| script_level_in(Dialect::Mongo, s); assert_eq!(m(r#"db.createCollection("shop")"#), MODIFY); assert_eq!(m("db.users.createIndex({email: 1}, {unique: true})"), MODIFY); diff --git a/src-tauri/src/mcp/tools.rs b/src-tauri/src/mcp/tools.rs index 980a6313..f068e7f5 100644 --- a/src-tauri/src/mcp/tools.rs +++ b/src-tauri/src/mcp/tools.rs @@ -161,6 +161,64 @@ fn safe_ident(s: &str) -> bool { } /// `SELECT * … LIMIT n` for one table, quoted for the engine. +/// Engines whose default schema is not `public`: an agent that leaves the +/// schema out (or says `public` out of habit) gets the connection's own. +fn moves_default_schema(conn: &ActiveConnection) -> bool { + matches!( + conn, + ActiveConnection::Spanner(_) + | ActiveConnection::Bigquery(_) + | ActiveConnection::Snowflake(_) + | ActiveConnection::Odbc(_) + | ActiveConnection::Mssql(_) + | ActiveConnection::Oracle(_) + | ActiveConnection::Doc(_) + ) +} + +/// The schema a tool works in. Every tool used to default to `public`, so on +/// Spanner, BigQuery, Snowflake, ODBC, SQL Server and Oracle an agent that +/// left it out listed an empty schema and was told its tables had no columns. +/// A name given in another case (Snowflake's `PUBLIC`) becomes the real one. +async fn resolve_schema(conn: &ActiveConnection, raw: Option<&str>) -> String { + let asked = raw.map(str::trim).filter(|s| !s.is_empty()); + if !moves_default_schema(conn) { + return asked.unwrap_or("public").to_string(); + } + let schemas = crate::db::schemas_of(conn).await.unwrap_or_default(); + if let Some(a) = asked { + if let Some(real) = schemas.iter().find(|s| s.eq_ignore_ascii_case(a)) { + return real.clone(); + } + // `public` is the Postgres habit; anything else is the agent's choice. + if !a.eq_ignore_ascii_case("public") || schemas.is_empty() { + return a.to_string(); + } + } + if matches!(conn, ActiveConnection::Mssql(_)) && schemas.iter().any(|s| s == "dbo") { + return "dbo".to_string(); + } + schemas.into_iter().next().unwrap_or_default() +} + +/// A table's name as this engine writes it in SQL, schema included. +fn table_ref_for(conn: &ActiveConnection, schema: &str, table: &str) -> Option { + if let Some(e) = crate::db::backup::SqlEngine::of(conn) { + return Some(e.table_ref(schema, table)); + } + let dq = |s: &str| format!("\"{}\"", s.replace('"', "\"\"")); + Some(match conn { + ActiveConnection::Postgres(_) | ActiveConnection::Clickhouse(_) => format!("{}.{}", dq(schema), dq(table)), + ActiveConnection::Mysql(_) if schema.is_empty() => format!("`{table}`"), + ActiveConnection::Mysql(_) => format!("`{schema}`.`{table}`"), + ActiveConnection::Mssql(_) => format!("[{schema}].[{table}]"), + ActiveConnection::Oracle(_) if schema.is_empty() => dq(table), + ActiveConnection::Oracle(_) => format!("{}.{}", dq(schema), dq(table)), + ActiveConnection::Sqlite(_) | ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Duckdb(_) => dq(table), + _ => return None, + }) +} + fn sample_sql(conn: &ActiveConnection, schema: &str, table: &str, n: usize) -> Result { if !safe_ident(table) || (!schema.is_empty() && !safe_ident(schema)) { return Err("Invalid table or schema name.".to_string()); @@ -176,6 +234,25 @@ fn sample_sql(conn: &ActiveConnection, schema: &str, table: &str, n: usize) -> R ActiveConnection::Sqlite(_) | ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Duckdb(_) => { format!("SELECT * FROM {} LIMIT {n}", dq(table)) } + ActiveConnection::Spanner(_) | ActiveConnection::Bigquery(_) | ActiveConnection::Snowflake(_) => { + format!("SELECT * FROM {} LIMIT {n}", table_ref_for(conn, schema, table).unwrap_or_default()) + } + ActiveConnection::Odbc(h) => { + let from = crate::db::odbc::table_ref(&h.info, schema, table); + crate::db::odbc::page_sql(h.info.paging, &from, "", n as i64, 0).0 + } + // The document and graph engines, each in its own language (the + // query console's, which execute_sql runs). + ActiveConnection::Doc(d) => match d.driver() { + "neo4j" => format!("MATCH (n:`{table}`) RETURN n LIMIT {n}"), + "influxdb" => format!("SELECT * FROM \"{table}\" ORDER BY time DESC LIMIT {n}"), + "mongodb" => format!("db.getCollection(\"{table}\").find({{}}).limit({n})"), + "couchdb" => format!("{table}.find({{}}, {{\"limit\": {n}}})"), + "elasticsearch" | "opensearch" => format!("GET {table}/_search\n{{\"size\": {n}}}"), + "firestore" => format!("{table}.limit({n})"), + "cassandra" => format!("SELECT * FROM {}.{} LIMIT {n}", dq(schema), dq(table)), + other => return Err(format!("sample_rows is not available for {other}. Use execute_sql.")), + }, _ => return Err("sample_rows is for SQL engines. Use execute_sql with this engine's own query language.".to_string()), }) } @@ -301,25 +378,25 @@ pub async fn call_tool( execute_sql(conn, sql, max_rows, read_only).await } "list_tables" => { - let schema = args["schema"].as_str().unwrap_or("public"); - list_tables(conn, schema).await + let schema = resolve_schema(conn, args["schema"].as_str()).await; + list_tables(conn, &schema).await } "describe_table" => { let table = args["table"].as_str().ok_or("Missing table argument")?; - let schema = args["schema"].as_str().unwrap_or("public"); - describe_table(conn, schema, table).await + let schema = resolve_schema(conn, args["schema"].as_str()).await; + describe_table(conn, &schema, table).await } "check_migrations" => { - let schema = args["schema"].as_str().unwrap_or("public"); - check_migrations(conn, schema).await + let schema = resolve_schema(conn, args["schema"].as_str()).await; + check_migrations(conn, &schema).await } "explain_query" => { let sql = args["sql"].as_str().ok_or("Missing sql argument")?; explain_query(conn, sql).await } "get_database_stats" => { - let schema = args["schema"].as_str().unwrap_or("public"); - get_database_stats(conn, schema).await + let schema = resolve_schema(conn, args["schema"].as_str()).await; + get_database_stats(conn, &schema).await } "export_query" => { let sql = args["sql"].as_str().ok_or("Missing sql argument")?; @@ -337,7 +414,12 @@ pub async fn call_tool( } "sample_rows" => { let table = args["table"].as_str().ok_or("Missing table argument")?; - let schema = args["schema"].as_str().unwrap_or(if matches!(conn, ActiveConnection::Mysql(_) | ActiveConnection::Clickhouse(_) | ActiveConnection::Oracle(_)) { "" } else { "public" }); + let resolved = resolve_schema(conn, args["schema"].as_str()).await; + let schema = if moves_default_schema(conn) { + resolved.as_str() + } else { + args["schema"].as_str().unwrap_or(if matches!(conn, ActiveConnection::Mysql(_) | ActiveConnection::Clickhouse(_)) { "" } else { "public" }) + }; let schema = if schema.is_empty() { match conn { ActiveConnection::Mssql(_) => "dbo", @@ -589,18 +671,24 @@ async fn execute_sql( match conn { ActiveConnection::Postgres(pool) if read_only => { let mut tx = pool.begin_with("BEGIN READ ONLY").await.map_err(|e| format!("SQL error: {e}"))?; - let out = execute_sql_pg(&mut *tx, sql, max_rows).await; + let out = execute_sql_pg(&mut tx, sql, max_rows).await; let _ = tx.rollback().await; out } - ActiveConnection::Postgres(pool) => execute_sql_pg(pool, sql, max_rows).await, + ActiveConnection::Postgres(pool) => { + let mut c = pool.acquire().await.map_err(|e| format!("SQL error: {e}"))?; + execute_sql_pg(&mut c, sql, max_rows).await + } ActiveConnection::Sqlite(pool) if read_only => { let mut tx = pool.begin().await.map_err(|e| format!("SQL error: {e}"))?; - let out = execute_sql_sqlite(&mut *tx, sql, max_rows).await; + let out = execute_sql_sqlite(&mut tx, sql, max_rows).await; let _ = tx.rollback().await; out } - ActiveConnection::Sqlite(pool) => execute_sql_sqlite(pool, sql, max_rows).await, + ActiveConnection::Sqlite(pool) => { + let mut c = pool.acquire().await.map_err(|e| format!("SQL error: {e}"))?; + execute_sql_sqlite(&mut c, sql, max_rows).await + } ActiveConnection::D1(cfg) => execute_sql_d1(cfg, sql, max_rows).await, // Read only: the engine enforces it, not just the classifier. ActiveConnection::LibSql(cfg) if read_only => { @@ -616,11 +704,14 @@ async fn execute_sql( .begin_with("START TRANSACTION READ ONLY") .await .map_err(|e| format!("SQL error: {e}"))?; - let out = execute_sql_mysql(&mut *tx, sql, max_rows).await; + let out = execute_sql_mysql(&mut tx, sql, max_rows).await; let _ = tx.rollback().await; out } - ActiveConnection::Mysql(pool) => execute_sql_mysql(pool, sql, max_rows).await, + ActiveConnection::Mysql(pool) => { + let mut c = pool.acquire().await.map_err(|e| format!("SQL error: {e}"))?; + execute_sql_mysql(&mut c, sql, max_rows).await + } ActiveConnection::Clickhouse(cfg) if read_only => { let result = crate::db::clickhouse::query_readonly(cfg, sql).await?; Ok(truncated_result_json(&result, max_rows)) @@ -633,6 +724,35 @@ async fn execute_sql( let result = crate::db::posthog::query(cfg, sql).await?; Ok(truncated_result_json(&result, max_rows)) } + // Spanner runs reads as read-only transactions, so a read can't write. + ActiveConnection::Spanner(h) => { + if read_only && !crate::db::spanner::reads(sql) { + return Err("This connection is read-only: only SELECT statements run".into()); + } + let result = crate::db::spanner::query(h, sql).await?; + Ok(truncated_result_json(&result, max_rows)) + } + ActiveConnection::Bigquery(h) => { + if read_only && !crate::db::bigquery::reads(sql) { + return Err("This connection is read-only: only SELECT statements run".into()); + } + let result = crate::db::bigquery::query(h, sql).await?; + Ok(truncated_result_json(&result, max_rows)) + } + ActiveConnection::Snowflake(h) => { + if read_only && !crate::db::snowflake::reads(sql) { + return Err("This connection is read-only: only SELECT statements run".into()); + } + let result = crate::db::snowflake::query(h, sql).await?; + Ok(truncated_result_json(&result, max_rows)) + } + ActiveConnection::Odbc(h) => { + if read_only && !crate::db::odbc::reads(sql) { + return Err("This connection is read-only: only SELECT statements run".into()); + } + let result = crate::db::odbc::query(h, sql).await?; + Ok(truncated_result_json(&result, max_rows)) + } ActiveConnection::Redis(cfg) => { let result = crate::db::redis::query(cfg, sql).await?; Ok(truncated_result_json(&result, max_rows)) @@ -672,12 +792,9 @@ async fn execute_sql( } } -async fn execute_sql_mysql<'c, E>(ex: E, sql: &'c str, max_rows: usize) -> Result -where - E: sqlx::Executor<'c, Database = sqlx::MySql>, -{ +async fn execute_sql_mysql(conn: &mut sqlx::MySqlConnection, sql: &str, max_rows: usize) -> Result { // Stream rows instead of fetch_all - caps memory at max_rows regardless of result size. - let mut stream = sqlx::query(sql).fetch(ex); + let mut stream = sqlx::query(sql).fetch(&mut *conn); let mut columns: Vec = Vec::new(); let mut data: Vec> = Vec::with_capacity(max_rows.min(256)); let mut total = 0usize; @@ -692,6 +809,15 @@ where } } + drop(stream); + // An empty result has no row to read the columns off; an agent got + // `"columns": []` for a SELECT that matched nothing. + if total == 0 { + if let Ok(d) = sqlx::Executor::describe(&mut *conn, sql).await { + columns = d.columns().iter().map(|c| c.name().to_string()).collect(); + } + } + Ok(json!({ "columns": columns, "rows": data, @@ -700,12 +826,9 @@ where }).to_string()) } -async fn execute_sql_pg<'c, E>(ex: E, sql: &'c str, max_rows: usize) -> Result -where - E: sqlx::Executor<'c, Database = sqlx::Postgres>, -{ +async fn execute_sql_pg(conn: &mut sqlx::PgConnection, sql: &str, max_rows: usize) -> Result { // Stream rows - never materialises more than max_rows rows in memory. - let mut stream = sqlx::query(sql).fetch(ex); + let mut stream = sqlx::query(sql).fetch(&mut *conn); let mut columns: Vec = Vec::new(); let mut data: Vec> = Vec::with_capacity(max_rows.min(256)); let mut total = 0usize; @@ -720,6 +843,15 @@ where } } + drop(stream); + // An empty result has no row to read the columns off; an agent got + // `"columns": []` for a SELECT that matched nothing. + if total == 0 { + if let Ok(d) = sqlx::Executor::describe(&mut *conn, sql).await { + columns = d.columns().iter().map(|c| c.name().to_string()).collect(); + } + } + Ok(json!({ "columns": columns, "rows": data, @@ -729,12 +861,9 @@ where .to_string()) } -async fn execute_sql_sqlite<'c, E>(ex: E, sql: &'c str, max_rows: usize) -> Result -where - E: sqlx::Executor<'c, Database = sqlx::Sqlite>, -{ +async fn execute_sql_sqlite(conn: &mut sqlx::SqliteConnection, sql: &str, max_rows: usize) -> Result { // Stream rows - never materialises more than max_rows rows in memory. - let mut stream = sqlx::query(sql).fetch(ex); + let mut stream = sqlx::query(sql).fetch(&mut *conn); let mut columns: Vec = Vec::new(); let mut data: Vec> = Vec::with_capacity(max_rows.min(256)); let mut total = 0usize; @@ -749,6 +878,15 @@ where } } + drop(stream); + // An empty result has no row to read the columns off; an agent got + // `"columns": []` for a SELECT that matched nothing. + if total == 0 { + if let Ok(d) = sqlx::Executor::describe(&mut *conn, sql).await { + columns = d.columns().iter().map(|c| c.name().to_string()).collect(); + } + } + Ok(json!({ "columns": columns, "rows": data, @@ -787,6 +925,22 @@ async fn list_tables(conn: &ActiveConnection, schema: &str) -> Result>()}).to_string()) } + ActiveConnection::Spanner(h) => { + let tables = crate::db::spanner::list_tables(h, schema).await?; + Ok(json!({"tables":tables.iter().map(|t|&t.name).collect::>()}).to_string()) + } + ActiveConnection::Bigquery(h) => { + let tables = crate::db::bigquery::list_tables(h, schema).await?; + Ok(json!({"tables":tables.iter().map(|t|&t.name).collect::>()}).to_string()) + } + ActiveConnection::Snowflake(h) => { + let tables = crate::db::snowflake::list_tables(h, schema).await?; + Ok(json!({"tables":tables.iter().map(|t|&t.name).collect::>()}).to_string()) + } + ActiveConnection::Odbc(h) => { + let tables = crate::db::odbc::list_tables(h, schema).await?; + Ok(json!({"tables":tables.iter().map(|t|&t.name).collect::>()}).to_string()) + } ActiveConnection::Redis(cfg) => { let tables = crate::db::redis::list_tables(cfg).await?; Ok(json!({"tables":tables.iter().map(|t|&t.name).collect::>()}).to_string()) @@ -920,6 +1074,38 @@ async fn describe_table( let columns: Vec<_> = cols.iter().map(|c| json!({ "name": c.name, "type": c.data_type, "nullable": c.is_nullable })).collect(); Ok(json!({"table":table,"columns":columns,"note":"PostHog table, query it with HogQL"}).to_string()) } + ActiveConnection::Spanner(h) => { + let cols = crate::db::spanner::get_column_structure(h, schema, table).await?; + let columns: Vec<_> = cols.iter().map(|c| json!({ + "name": c.name, "type": c.data_type, "nullable": c.is_nullable, + "default": c.column_default, "primary_key": c.is_primary_key, "references": c.foreign_key, + })).collect(); + Ok(json!({"table":table,"columns":columns,"note":"Spanner GoogleSQL: quote names with backticks"}).to_string()) + } + ActiveConnection::Bigquery(h) => { + let cols = crate::db::bigquery::get_column_structure(h, schema, table).await?; + let columns: Vec<_> = cols.iter().map(|c| json!({ + "name": c.name, "type": c.data_type, "nullable": c.is_nullable, + "default": c.column_default, "primary_key": c.is_primary_key, "references": c.foreign_key, + })).collect(); + Ok(json!({"table":table,"columns":columns,"note":"BigQuery GoogleSQL: write `dataset.table` with backticks. Queries are billed by bytes scanned: select only the columns you need"}).to_string()) + } + ActiveConnection::Snowflake(h) => { + let cols = crate::db::snowflake::get_column_structure(h, schema, table).await?; + let columns: Vec<_> = cols.iter().map(|c| json!({ + "name": c.name, "type": c.data_type, "nullable": c.is_nullable, + "default": c.column_default, "primary_key": c.is_primary_key, "references": c.foreign_key, + })).collect(); + Ok(json!({"table":table,"columns":columns,"note":"Snowflake: unquoted names fold to upper case; quote mixed-case names with double quotes. Queries run on the connection's warehouse"}).to_string()) + } + ActiveConnection::Odbc(h) => { + let cols = crate::db::odbc::get_column_structure(h, schema, table).await?; + let columns: Vec<_> = cols.iter().map(|c| json!({ + "name": c.name, "type": c.data_type, "nullable": c.is_nullable, + "default": c.column_default, "primary_key": c.is_primary_key, "references": c.foreign_key, + })).collect(); + Ok(json!({"table":table,"columns":columns,"note":format!("{} through ODBC: write SQL in its own dialect", h.info.dbms)}).to_string()) + } ActiveConnection::Clickhouse(cfg) => { let cols = crate::db::clickhouse::get_column_structure(cfg, schema, table).await?; let columns: Vec<_> = cols.iter().map(|c| json!({ @@ -950,11 +1136,32 @@ async fn describe_table( "note": "DynamoDB is schemaless: only key attributes are declared. Query with PartiQL.", }).to_string()) } - ActiveConnection::Doc(d) => Ok(json!({ - "table": table, - "engine": d.driver(), - "note": "Schemaless or wide-column: inspect documents with the query tool instead of a column list.", - }).to_string()), + ActiveConnection::Doc(d) => { + use crate::db::docdb::DocConn; + match d { + // A label's property keys, from a sample of its nodes. + DocConn::Neo4j(c) => { + let info = crate::db::neo4j::describe(c, table).await?; + Ok(json!({"table":table,"engine":"neo4j","node_count":info["count"],"properties":info["keys"],"note":"A node label: properties seen on up to 200 of its nodes. Query with Cypher, e.g. MATCH (n:Label) RETURN n LIMIT 25"}).to_string()) + } + // A measurement's tags and fields. + DocConn::Influx(c) => { + let info = crate::db::influx::describe(c, table).await?; + Ok(json!({"table":table,"engine":"influxdb","tags":info["tags"],"fields":info["fields"],"note":"Read-only. Tags are indexed strings, fields hold the values, `time` is the timestamp. Always bound time and add LIMIT."}).to_string()) + } + // Typed columns where the engine keeps them (CQL, index mappings). + DocConn::Cassandra(_) | DocConn::Elastic(_) => { + let cols = crate::db::docdb::columns_in(d, schema, table).await?; + let columns: Vec<_> = cols.iter().map(|c| json!({ "name": c.name, "type": c.data_type, "nullable": c.is_nullable, "primary_key": c.is_primary_key })).collect(); + Ok(json!({"table":table,"engine":d.driver(),"columns":columns}).to_string()) + } + _ => Ok(json!({ + "table": table, + "engine": d.driver(), + "note": "Schemaless: inspect documents with sample_rows instead of a column list.", + }).to_string()), + } + } ActiveConnection::Duckdb(h) => { let cols = crate::db::duckdb::get_column_structure(h, table).await?; let columns: Vec<_> = cols.iter().map(|c| json!({ @@ -1231,16 +1438,52 @@ async fn check_migrations(conn: &ActiveConnection, schema: &str) -> Result check_migrations_pg(pool, schema).await, ActiveConnection::Sqlite(pool) => check_migrations_sqlite(pool).await, ActiveConnection::D1(cfg) => check_migrations_d1(cfg).await, - ActiveConnection::LibSql(_) => Ok(json!({"migrations":[],"note":"Migration detection not yet supported for LibSQL"}).to_string()), + ActiveConnection::LibSql(_) => check_migrations_generic(conn, schema).await, ActiveConnection::Mysql(pool) => check_migrations_mysql(pool, schema).await, - ActiveConnection::Clickhouse(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for ClickHouse"}).to_string()), + ActiveConnection::Clickhouse(_) => check_migrations_generic(conn, schema).await, ActiveConnection::Posthog(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for PostHog"}).to_string()), + ActiveConnection::Spanner(_) => check_migrations_generic(conn, schema).await, + ActiveConnection::Bigquery(_) => check_migrations_generic(conn, schema).await, + ActiveConnection::Snowflake(_) => check_migrations_generic(conn, schema).await, + ActiveConnection::Odbc(_) => check_migrations_generic(conn, schema).await, ActiveConnection::Redis(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for Redis"}).to_string()), - ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for DynamoDB"}).to_string()), - ActiveConnection::Duckdb(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for DuckDB"}).to_string()), - ActiveConnection::Mssql(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for MS SQL Server"}).to_string()), - ActiveConnection::Oracle(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for Oracle"}).to_string()), + ActiveConnection::Dynamodb(_) => Ok(json!({"migrations":[],"note":"Migration detection not supported for DynamoDB"}).to_string()), + ActiveConnection::Doc(d) => Ok(json!({"migrations":[],"note":format!("Migration detection not supported for {}", d.driver())}).to_string()), + ActiveConnection::Duckdb(_) => check_migrations_generic(conn, schema).await, + ActiveConnection::Mssql(_) => check_migrations_generic(conn, schema).await, + ActiveConnection::Oracle(_) => check_migrations_generic(conn, schema).await, + } +} + +/// The migration tables of the common tools, found by name in the schema's +/// table list (any case: Snowflake folds to upper), with their row count and +/// a few rows. For the engines without a dedicated check. +async fn check_migrations_generic(conn: &ActiveConnection, schema: &str) -> Result { + let listed: Value = serde_json::from_str(&list_tables(conn, schema).await?).unwrap_or(Value::Null); + let existing: Vec = listed["tables"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(String::from)).collect(); + let mut found = Vec::new(); + let mut not_found = Vec::new(); + for (tbl, framework, _, _) in MIGRATION_TABLES { + let Some(real) = existing.iter().find(|t| t.eq_ignore_ascii_case(tbl)) else { + not_found.push(json!({ "table": tbl, "framework": framework, "found": false })); + continue; + }; + let count = match table_ref_for(conn, schema, real) { + Some(r) => execute_sql(conn, &format!("SELECT COUNT(*) AS n FROM {r}"), 1, true) + .await + .ok() + .and_then(|out| serde_json::from_str::(&out).ok()) + .and_then(|v| v["rows"][0][0].as_i64().or_else(|| v["rows"][0][0].as_str()?.parse().ok())), + None => None, + }; + let recent = match sample_sql(conn, schema, real, 5) { + Ok(q) => execute_sql(conn, &q, 5, true).await.ok().and_then(|out| serde_json::from_str::(&out).ok()).unwrap_or(Value::Null), + Err(_) => Value::Null, + }; + found.push(json!({ "table": real, "framework": framework, "found": true, "total_migrations": count, "sample": recent })); } + let all: Vec = found.into_iter().chain(not_found).collect(); + Ok(json!({ "schema": schema, "migration_tables": all }).to_string()) } async fn check_migrations_mysql(pool: &sqlx::MySqlPool, schema: &str) -> Result { @@ -1446,8 +1689,50 @@ async fn explain_query(conn: &ActiveConnection, sql: &str) -> Result Ok(json!({"plan":[],"database":"redis","note":"EXPLAIN is not supported on Redis"}).to_string()), - ActiveConnection::Dynamodb(_) | ActiveConnection::Doc(_) => Ok(json!({"plan":[],"database":"dynamodb","note":"EXPLAIN is not supported on DynamoDB"}).to_string()), + ActiveConnection::Dynamodb(_) => Ok(json!({"plan":[],"database":"dynamodb","note":"EXPLAIN is not supported on DynamoDB"}).to_string()), + // The same plans the app's Explain shows, where the engine has one. + ActiveConnection::Doc(d) => { + use crate::db::docdb::DocConn; + let plan = match d { + DocConn::Neo4j(c) => crate::db::neo4j::explain_plan(c, sql).await?, + DocConn::Mongo(m) => crate::db::mongo::explain_plan(m, sql).await?, + DocConn::Couch(c) => crate::db::couchdb::explain_plan(c, sql).await?, + DocConn::Elastic(c) => crate::db::elastic::explain_plan(c, sql).await?, + DocConn::Influx(c) => { + let r = crate::db::influx::query(c, &format!("EXPLAIN {}", sql.trim().trim_end_matches(';'))).await?; + json!(r.rows) + } + other => return Ok(json!({"plan":[],"database":other.driver(),"note":format!("{} has no query plan", other.driver())}).to_string()), + }; + Ok(json!({"plan":plan,"database":d.driver()}).to_string()) + } ActiveConnection::Posthog(_) => Ok(json!({"plan":[],"database":"posthog","note":"EXPLAIN is not available through PostHog's query API"}).to_string()), + ActiveConnection::Spanner(h) => { + let plan = crate::db::spanner::explain_plan(h, sql).await?; + Ok(json!({"plan":plan,"database":"spanner"}).to_string()) + } + ActiveConnection::Bigquery(h) => { + let plan = crate::db::bigquery::explain_plan(h, sql).await?; + Ok(json!({"plan":plan,"database":"bigquery"}).to_string()) + } + ActiveConnection::Snowflake(h) => { + let plan = crate::db::snowflake::explain_plan(h, sql).await?; + Ok(json!({"plan":plan,"database":"snowflake"}).to_string()) + } + ActiveConnection::Odbc(h) => { + // ODBC has no plan API; the databases that answer a plain EXPLAIN do here. + let dbms = h.info.dbms.to_ascii_lowercase(); + let explains = ["postgres", "mysql", "mariadb", "sqlite", "duckdb", "trino", "presto", "hive", "spark", "databricks", "vertica", "redshift", "exasol", "clickhouse", "teradata", "dremio"] + .iter() + .any(|k| dbms.contains(k)); + if explains { + match crate::db::odbc::query(h, &format!("EXPLAIN {}", sql.trim().trim_end_matches(';'))).await { + Ok(r) => return Ok(json!({"plan":r.rows,"columns":r.columns.iter().map(|c| &c.name).collect::>(),"database":"odbc","dbms":h.info.dbms}).to_string()), + Err(e) => return Ok(json!({"plan":[],"database":"odbc","dbms":h.info.dbms,"note":format!("EXPLAIN failed: {e}")}).to_string()), + } + } + Ok(json!({"plan":[],"database":"odbc","dbms":h.info.dbms,"note":"This database has no plain EXPLAIN over ODBC; use its own plan command through execute_sql"}).to_string()) + } ActiveConnection::Duckdb(h) => { let r = crate::db::duckdb::execute_sql(h, &format!("EXPLAIN {sql}")).await?; Ok(json!({"plan":r.rows,"database":"duckdb"}).to_string()) @@ -1539,6 +1824,23 @@ async fn get_database_stats(conn: &ActiveConnection, schema: &str) -> Result { + let tables = crate::db::spanner::list_tables(h, schema).await?; + let dialect = if h.dialect == crate::db::spanner::Dialect::Postgres { "PostgreSQL" } else { "GoogleSQL" }; + Ok(json!({"database":"spanner","dialect":dialect,"table_count":tables.len()}).to_string()) + } + ActiveConnection::Bigquery(h) => { + let tables = crate::db::bigquery::list_tables(h, schema).await?; + Ok(json!({"database":"bigquery","dialect":"GoogleSQL","project":h.project_id,"dataset":schema,"table_count":tables.len()}).to_string()) + } + ActiveConnection::Snowflake(h) => { + let tables = crate::db::snowflake::list_tables(h, schema).await?; + Ok(json!({"database":"snowflake","dialect":"Snowflake SQL","database_name":h.cfg.database,"schema":schema,"table_count":tables.len()}).to_string()) + } + ActiveConnection::Odbc(h) => { + let tables = crate::db::odbc::list_tables(h, schema).await?; + Ok(json!({"database":"odbc","dbms":h.info.dbms,"schema":schema,"table_count":tables.len()}).to_string()) + } ActiveConnection::Redis(cfg) => { let tables = crate::db::redis::list_tables(cfg).await?; Ok(json!({"database":"redis","table_count":tables.len()}).to_string()) @@ -1857,3 +2159,100 @@ fn pg_cell(row: &sqlx::postgres::PgRow, idx: usize) -> Value { } Value::Null } + +#[cfg(test)] +mod live_tools { + //! The agent tools on the newer engines, called the way an agent calls + //! them: no schema named. STROKE_TEST_TOOLS=1 with each engine's own + //! variable (see the engines' live tests). + use super::*; + use crate::db::connection::ActiveConnection; + use serde_json::json; + + async fn tool(conn: &ActiveConnection, name: &str, args: Value) -> Value { + let out = call_tool(conn, name, &args, true).await.unwrap_or_else(|e| panic!("{name}: {e}")); + serde_json::from_str(&out).unwrap_or(json!({ "text": out })) + } + + /// list_tables, describe_table on the first table, stats, sample_rows, + /// explain and check_migrations; returns problems instead of stopping. + async fn exercise(label: &str, conn: &ActiveConnection, explain_sql: impl Fn(&str) -> String) -> Vec { + let mut bad = Vec::new(); + let tables = tool(conn, "list_tables", json!({})).await; + let names: Vec = tables["tables"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(String::from)).collect(); + println!("{label} list_tables: {names:?}"); + let Some(first) = names.iter().find(|n| !n.starts_with("stroke_odbc_")).cloned().or(names.first().cloned()) else { + return vec![format!("{label}: list_tables returned nothing")]; + }; + let d = tool(conn, "describe_table", json!({ "table": first })).await; + let cols = d["columns"].as_array().map(|c| c.len()).unwrap_or(0); + println!("{label} describe {first}: {cols} columns {}", d.to_string().chars().take(160).collect::()); + let shape = cols > 0 || d["properties"].as_array().is_some_and(|a| !a.is_empty()) || d["tags"].as_array().is_some_and(|a| !a.is_empty()) || d["fields"].as_array().is_some_and(|a| !a.is_empty()); + if !shape { + bad.push(format!("{label}: describe_table({first}) has no columns")); + } + let st = tool(conn, "get_database_stats", json!({})).await; + println!("{label} stats: {st}"); + if st["table_count"].as_u64().unwrap_or(0) == 0 { + bad.push(format!("{label}: stats table_count 0")); + } + match call_tool(conn, "sample_rows", &json!({ "table": first, "limit": 2 }), true).await { + Ok(s) => println!("{label} sample_rows: {}", s.chars().take(160).collect::()), + Err(e) => bad.push(format!("{label}: sample_rows: {e}")), + } + match call_tool(conn, "explain_query", &json!({ "sql": explain_sql(&first) }), true).await { + Ok(s) => { + println!("{label} explain: {}", s.chars().take(160).collect::()); + let v: Value = serde_json::from_str(&s).unwrap_or(Value::Null); + if v["plan"].is_null() || v["plan"].as_array().is_some_and(|a| a.is_empty()) { + bad.push(format!("{label}: explain returned no plan: {s}")); + } + } + Err(e) => bad.push(format!("{label}: explain: {e}")), + } + match call_tool(conn, "check_migrations", &json!({}), true).await { + Ok(s) => println!("{label} migrations: {}", s.chars().take(120).collect::()), + Err(e) => bad.push(format!("{label}: check_migrations: {e}")), + } + bad + } + + #[tokio::test] + async fn tools_on_every_engine() { + if std::env::var("STROKE_TEST_TOOLS").is_err() { + return; + } + let mut bad = Vec::new(); + if let Ok(spec) = std::env::var("STROKE_TEST_SPANNER") { + let p: Vec<&str> = spec.splitn(4, '/').collect(); + let cfg: crate::db::spanner::SpannerConfig = serde_json::from_value(json!({ "name": "t", "projectId": p[1], "instanceId": p[2], "databaseId": p[3], "auth": "emulator", "emulatorHost": p[0] })).unwrap(); + let conn = ActiveConnection::Spanner(crate::db::spanner::connect(&cfg).await.unwrap()); + bad.extend(exercise("spanner", &conn, |t| format!("SELECT * FROM `{t}`")).await); + } + if let Ok(spec) = std::env::var("STROKE_TEST_BIGQUERY") { + let p: Vec<&str> = spec.splitn(3, '/').collect(); + let cfg: crate::db::bigquery::BigQueryConfig = serde_json::from_value(json!({ "name": "t", "projectId": p[1], "dataset": p[2], "auth": "emulator", "emulatorHost": p[0] })).unwrap(); + let conn = ActiveConnection::Bigquery(crate::db::bigquery::connect(&cfg).await.unwrap()); + let ds = p[2].to_string(); + bad.extend(exercise("bigquery", &conn, move |t| format!("SELECT * FROM `{ds}.{t}`")).await); + } + if let Ok(cs) = std::env::var("STROKE_TEST_ODBC") { + let cfg: crate::db::odbc::OdbcConfig = serde_json::from_value(json!({ "name": "t", "connectionString": cs })).unwrap(); + let conn = ActiveConnection::Odbc(crate::db::odbc::connect(&cfg).await.unwrap()); + bad.extend(exercise("odbc", &conn, |t| format!("SELECT * FROM \"{t}\"")).await); + } + if let Ok(spec) = std::env::var("STROKE_TEST_NEO4J") { + let p: Vec<&str> = spec.splitn(3, '|').collect(); + let cfg: crate::db::neo4j::Neo4jConfig = serde_json::from_value(json!({ "name": "t", "url": p[0], "user": p[1], "password": p[2] })).unwrap(); + let conn = ActiveConnection::Doc(crate::db::docdb::DocConn::Neo4j(crate::db::neo4j::connect(&cfg).await.unwrap())); + bad.extend(exercise("neo4j", &conn, |t| format!("MATCH (n:`{t}`) RETURN n LIMIT 5")).await); + } + if let Ok(spec) = std::env::var("STROKE_TEST_INFLUX3") { + let p: Vec<&str> = spec.split('|').collect(); + let cfg: crate::db::influx::InfluxConfig = serde_json::from_value(json!({ "name": "t", "url": p[0], "version": "3", "database": p[1] })).unwrap(); + let conn = ActiveConnection::Doc(crate::db::docdb::DocConn::Influx(crate::db::influx::connect(&cfg).await.unwrap())); + bad.extend(exercise("influx3", &conn, |t| format!("SELECT * FROM \"{t}\"")).await); + } + assert!(bad.is_empty(), "\n{}", bad.join("\n")); + } +} diff --git a/src-tauri/src/nightly.rs b/src-tauri/src/nightly.rs index 80ec7355..fc190e73 100644 --- a/src-tauri/src/nightly.rs +++ b/src-tauri/src/nightly.rs @@ -37,7 +37,7 @@ impl Track { } fn client() -> reqwest::Client { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::App) .user_agent("stroke-nightly-installer") .timeout(std::time::Duration::from_secs(600)) .build() diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index cd9c00e4..b3cc7152 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -542,7 +542,7 @@ static CLIENT: OnceLock = OnceLock::new(); pub(crate) fn http() -> &'static reqwest::Client { CLIENT.get_or_init(|| { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::App) .user_agent("stroke/1.0") .tcp_keepalive(std::time::Duration::from_secs(60)) .pool_max_idle_per_host(4) diff --git a/src-tauri/src/proxy.rs b/src-tauri/src/proxy.rs new file mode 100644 index 00000000..ce4a9429 --- /dev/null +++ b/src-tauri/src/proxy.rs @@ -0,0 +1,440 @@ +//! Proxy settings by kind of traffic (Settings > Network). +//! +//! Four kinds, each System (the default: whatever the environment says, +//! `HTTPS_PROXY` and friends), Custom (a proxy URL) or Off (always direct): +//! +//! - **App**: update checks, sign-in, sync, sharing, web search, provider APIs. +//! - **AI**: requests to AI providers. +//! - **Database**: connections to databases. HTTP engines (ClickHouse, +//! Elasticsearch, D1, ...) get the proxy on their client; TCP engines +//! (Postgres, MySQL, SQL Server, ...) dial a local forwarder that opens the +//! connection through it, the same way an SSH tunnel's local end is used. +//! - **SSH**: the connection to the SSH bastion, through the same forwarder; +//! kubectl and the AWS CLI get it as `HTTPS_PROXY`. +//! +//! A custom URL is `http://host:port` (HTTP CONNECT) or `socks5://host:port`, +//! either with `user:password@`. Database and SSH traffic is not HTTP, so +//! "System" for them means direct unless a proxy is set here. + +use serde::{Deserialize, Serialize}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::RwLock; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + App, + Ai, + Database, + Ssh, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct Rule { + /// "system" (default), "custom" or "off". + #[serde(default)] + pub mode: String, + #[serde(default)] + pub url: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ProxySettings { + #[serde(default)] + pub app: Rule, + #[serde(default)] + pub ai: Rule, + #[serde(default)] + pub database: Rule, + #[serde(default)] + pub ssh: Rule, +} + +static SETTINGS: RwLock> = RwLock::new(None); +/// Bumped on every change, so cached clients know to rebuild. +static GENERATION: AtomicU64 = AtomicU64::new(0); + +pub fn generation() -> u64 { + GENERATION.load(Ordering::Relaxed) +} + +fn rule(kind: Kind) -> Rule { + let guard = SETTINGS.read().unwrap_or_else(|e| e.into_inner()); + let Some(s) = guard.as_ref() else { return Rule::default() }; + match kind { + Kind::App => s.app.clone(), + Kind::Ai => s.ai.clone(), + Kind::Database => s.database.clone(), + Kind::Ssh => s.ssh.clone(), + } +} + +/// The proxy URL a kind should go through, when it is set to Custom. +pub fn custom_url(kind: Kind) -> Option { + let r = rule(kind); + (r.mode == "custom" && !r.url.trim().is_empty()).then(|| r.url.trim().to_string()) +} + +/// True when this kind is set to Off (always direct). +pub fn is_off(kind: Kind) -> bool { + rule(kind).mode == "off" +} + +/// What a URL is, for the settings to refuse a bad one before it is used. +pub fn validate(url: &str) -> Result<(), String> { + let parsed = reqwest::Url::parse(url.trim()).map_err(|_| format!("{url} is not a proxy URL. Use http://host:port or socks5://host:port."))?; + match parsed.scheme() { + "http" | "socks5" | "socks5h" => {} + "https" => return Err("HTTPS proxies are not supported: use http://host:port (the connection through it is still encrypted).".into()), + s => return Err(format!("{s}:// is not a proxy kind Stroke speaks. Use http:// or socks5://.")), + } + if parsed.host_str().is_none() || parsed.port_or_known_default().is_none() { + return Err("The proxy URL needs a host and a port.".into()); + } + Ok(()) +} + +/// Replace the settings (from the window, on launch and on every change). +#[tauri::command] +pub fn proxy_set(settings: ProxySettings) -> Result<(), String> { + for (name, r) in [("App", &settings.app), ("AI", &settings.ai), ("Database", &settings.database), ("SSH", &settings.ssh)] { + if r.mode == "custom" { + validate(&r.url).map_err(|e| format!("{name} proxy: {e}"))?; + } + } + let mut guard = SETTINGS.write().unwrap_or_else(|e| e.into_inner()); + if guard.as_ref() != Some(&settings) { + *guard = Some(settings); + GENERATION.fetch_add(1, Ordering::Relaxed); + } + Ok(()) +} + +/// Reach `target` through `proxy`, then report whether it answered. For the +/// settings' Test button. +#[tauri::command] +pub async fn proxy_test(url: String, target: Option) -> Result { + validate(&url)?; + let target = target.unwrap_or_else(|| "example.com:443".into()); + let (host, port) = target.rsplit_once(':').ok_or("target is host:port")?; + let port: u16 = port.parse().map_err(|_| "target port")?; + let started = std::time::Instant::now(); + let stream = tokio::time::timeout(std::time::Duration::from_secs(10), dial(&url, host, port)) + .await + .map_err(|_| "The proxy did not answer within 10 seconds.".to_string())??; + drop(stream); + Ok(started.elapsed().as_millis() as u64) +} + +/// A `reqwest` builder with this kind's proxy applied. +pub fn http_builder(kind: Kind) -> reqwest::ClientBuilder { + apply(reqwest::Client::builder(), kind) +} + +/// Apply this kind's proxy to an existing builder. +pub fn apply(builder: reqwest::ClientBuilder, kind: Kind) -> reqwest::ClientBuilder { + let r = rule(kind); + match r.mode.as_str() { + "off" => builder.no_proxy(), + "custom" if !r.url.trim().is_empty() => match reqwest::Proxy::all(r.url.trim()) { + Ok(p) => builder.proxy(p), + Err(e) => { + log::warn!("proxy: ignoring {kind:?} proxy: {e}"); + builder + } + }, + _ => builder, + } +} + +/// The environment a child process (kubectl, the AWS CLI) should get: the +/// SSH kind's proxy as `HTTPS_PROXY`, or nothing to change. +pub fn child_env() -> Vec<(&'static str, String)> { + match custom_url(Kind::Ssh) { + Some(url) => vec![("HTTPS_PROXY", url.clone()), ("HTTP_PROXY", url), ("NO_PROXY", "127.0.0.1,localhost".into())], + None => Vec::new(), + } +} + +// ── Dialing through a proxy ─────────────────────────────────────────────────── + +/// A TCP connection to `host:port` through `proxy`. +pub async fn dial(proxy: &str, host: &str, port: u16) -> Result { + let u = reqwest::Url::parse(proxy.trim()).map_err(|e| format!("Bad proxy URL: {e}"))?; + let phost = u.host_str().ok_or("The proxy URL has no host")?.to_string(); + let pport = u.port_or_known_default().ok_or("The proxy URL has no port")?; + let user = urldecode(u.username()); + let pass = u.password().map(urldecode).unwrap_or_default(); + let mut s = TcpStream::connect((phost.as_str(), pport)) + .await + .map_err(|e| format!("Could not reach the proxy {phost}:{pport}: {e}"))?; + let _ = s.set_nodelay(true); + match u.scheme() { + "socks5" | "socks5h" => socks5_connect(&mut s, host, port, &user, &pass).await?, + _ => http_connect(&mut s, host, port, &user, &pass).await?, + } + Ok(s) +} + +fn urldecode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { + out.push(v); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +async fn http_connect(s: &mut TcpStream, host: &str, port: u16, user: &str, pass: &str) -> Result<(), String> { + use base64::Engine; + let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let mut req = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n"); + if !user.is_empty() { + let token = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}")); + req.push_str(&format!("Proxy-Authorization: Basic {token}\r\n")); + } + req.push_str("\r\n"); + s.write_all(req.as_bytes()).await.map_err(|e| format!("Proxy write failed: {e}"))?; + // Read the reply headers byte by byte: anything past them belongs to the + // connection being made. + let mut head = Vec::with_capacity(256); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + let n = s.read(&mut byte).await.map_err(|e| format!("Proxy read failed: {e}"))?; + if n == 0 { + return Err("The proxy closed the connection.".into()); + } + head.push(byte[0]); + if head.len() > 8192 { + return Err("The proxy sent an oversized reply.".into()); + } + } + let line = String::from_utf8_lossy(&head); + let status = line.split_whitespace().nth(1).unwrap_or(""); + match status { + "200" => Ok(()), + "407" => Err("The proxy asked for a login: add user:password@ to its URL.".into()), + "403" => Err(format!("The proxy refused to connect to {target}.")), + other => Err(format!("The proxy answered {other} to CONNECT {target}.")), + } +} + +async fn socks5_connect(s: &mut TcpStream, host: &str, port: u16, user: &str, pass: &str) -> Result<(), String> { + let io = |e: std::io::Error| format!("SOCKS proxy: {e}"); + let methods: &[u8] = if user.is_empty() { &[0x00] } else { &[0x00, 0x02] }; + let mut hello = vec![0x05, methods.len() as u8]; + hello.extend_from_slice(methods); + s.write_all(&hello).await.map_err(io)?; + let mut reply = [0u8; 2]; + s.read_exact(&mut reply).await.map_err(io)?; + match reply[1] { + 0x00 => {} + 0x02 => { + let mut auth = vec![0x01, user.len() as u8]; + auth.extend_from_slice(user.as_bytes()); + auth.push(pass.len() as u8); + auth.extend_from_slice(pass.as_bytes()); + s.write_all(&auth).await.map_err(io)?; + let mut r = [0u8; 2]; + s.read_exact(&mut r).await.map_err(io)?; + if r[1] != 0 { + return Err("The SOCKS proxy rejected the login.".into()); + } + } + 0xff => return Err("The SOCKS proxy needs a login: add user:password@ to its URL.".into()), + m => return Err(format!("The SOCKS proxy chose an unsupported method ({m}).")), + } + // The host goes by name, so the proxy resolves it (a private hostname may + // only resolve on the proxy's side). + let mut req = vec![0x05, 0x01, 0x00]; + if let Ok(ip) = host.parse::() { + match ip { + std::net::IpAddr::V4(v4) => { + req.push(0x01); + req.extend_from_slice(&v4.octets()); + } + std::net::IpAddr::V6(v6) => { + req.push(0x04); + req.extend_from_slice(&v6.octets()); + } + } + } else { + if host.len() > 255 { + return Err("Host name too long for SOCKS.".into()); + } + req.push(0x03); + req.push(host.len() as u8); + req.extend_from_slice(host.as_bytes()); + } + req.extend_from_slice(&port.to_be_bytes()); + s.write_all(&req).await.map_err(io)?; + let mut head = [0u8; 4]; + s.read_exact(&mut head).await.map_err(io)?; + if head[1] != 0x00 { + let why = match head[1] { + 0x02 => "not allowed by its rules", + 0x03 => "network unreachable", + 0x04 => "host unreachable", + 0x05 => "connection refused", + 0x06 => "timed out", + _ => "failed", + }; + return Err(format!("The SOCKS proxy could not reach {host}:{port}: {why}.")); + } + // Skip the bound address it reports. + let skip = match head[3] { + 0x01 => 4 + 2, + 0x04 => 16 + 2, + 0x03 => { + let mut l = [0u8; 1]; + s.read_exact(&mut l).await.map_err(io)?; + l[0] as usize + 2 + } + _ => return Err("The SOCKS proxy sent a malformed reply.".into()), + }; + let mut rest = vec![0u8; skip]; + s.read_exact(&mut rest).await.map_err(io)?; + Ok(()) +} + +/// A local listener whose every connection is opened to `host:port` through +/// `proxy`. Dropping it stops listening; connections already open run on. +pub struct ProxyForward { + pub local_port: u16, + task: tokio::task::JoinHandle<()>, +} + +impl Drop for ProxyForward { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl ProxyForward { + /// Start forwarding; fails when the proxy cannot reach the target, so the + /// connect says why instead of a driver timing out on a dead port. + pub async fn start(proxy: &str, host: &str, port: u16) -> Result { + // Proved once up front: the error a driver would give is "connection + // reset", which says nothing about the proxy. + drop(dial(proxy, host, port).await?); + let listener = TcpListener::bind("127.0.0.1:0").await.map_err(|e| format!("Could not open a local port: {e}"))?; + let local_port = listener.local_addr().map_err(|e| e.to_string())?.port(); + let (proxy, host) = (proxy.to_string(), host.to_string()); + let task = tokio::spawn(async move { + while let Ok((mut inbound, _)) = listener.accept().await { + let (proxy, host) = (proxy.clone(), host.clone()); + tokio::spawn(async move { + let _ = inbound.set_nodelay(true); + match dial(&proxy, &host, port).await { + Ok(mut outbound) => { + let _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound).await; + } + Err(e) => log::warn!("proxy forward to {host}:{port}: {e}"), + } + }); + } + }); + Ok(ProxyForward { local_port, task }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_urls() { + assert!(validate("http://proxy:3128").is_ok()); + assert!(validate("socks5://u:p@10.0.0.1:1080").is_ok()); + assert!(validate("https://proxy:443").is_err()); + assert!(validate("ftp://x:1").is_err()); + assert!(validate("nonsense").is_err()); + } + + #[test] + fn decodes_credentials() { + assert_eq!(urldecode("p%40ss"), "p@ss"); + assert_eq!(urldecode("plain"), "plain"); + } + + /// A tiny SOCKS5 server (no auth) and an HTTP CONNECT server in-process, + /// each forwarding to an echo server: both dial paths carry bytes. + #[tokio::test] + async fn dials_through_socks5_and_http_connect() { + let echo = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let echo_port = echo.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((mut c, _)) = echo.accept().await { + tokio::spawn(async move { + let (mut r, mut w) = c.split(); + let _ = tokio::io::copy(&mut r, &mut w).await; + }); + } + }); + + let socks = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let socks_port = socks.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((mut c, _)) = socks.accept().await { + tokio::spawn(async move { + let mut b = [0u8; 3]; + c.read_exact(&mut b).await.unwrap(); + c.write_all(&[5, 0]).await.unwrap(); + let mut h = [0u8; 4]; + c.read_exact(&mut h).await.unwrap(); + let mut l = [0u8; 1]; + c.read_exact(&mut l).await.unwrap(); + let mut name = vec![0u8; l[0] as usize]; + c.read_exact(&mut name).await.unwrap(); + let mut p = [0u8; 2]; + c.read_exact(&mut p).await.unwrap(); + let mut up = TcpStream::connect(("127.0.0.1", u16::from_be_bytes(p))).await.unwrap(); + c.write_all(&[5, 0, 0, 1, 127, 0, 0, 1, 0, 0]).await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut c, &mut up).await; + }); + } + }); + + let http = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let http_port = http.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((mut c, _)) = http.accept().await { + tokio::spawn(async move { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + c.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + let line = String::from_utf8_lossy(&head).to_string(); + let target = line.split_whitespace().nth(1).unwrap().to_string(); + let port: u16 = target.rsplit_once(':').unwrap().1.parse().unwrap(); + let mut up = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + c.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n").await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut c, &mut up).await; + }); + } + }); + + for proxy in [format!("socks5://127.0.0.1:{socks_port}"), format!("http://127.0.0.1:{http_port}")] { + let fwd = ProxyForward::start(&proxy, "localhost", echo_port).await.expect("forward"); + let mut s = TcpStream::connect(("127.0.0.1", fwd.local_port)).await.unwrap(); + s.write_all(b"ping").await.unwrap(); + let mut buf = [0u8; 4]; + s.read_exact(&mut buf).await.unwrap(); + assert_eq!(&buf, b"ping", "{proxy}"); + } + } +} diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 730832c1..43fe7a6e 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -153,6 +153,13 @@ pub async fn update_check( } let check = |target: Option<&'static str>| { let mut builder = app.updater_builder().timeout(CHECK_TIMEOUT); + // Settings > Network, App: a custom proxy carries the update check + // and the download. + if let Some(url) = crate::proxy::custom_url(crate::proxy::Kind::App).and_then(|u| reqwest::Url::parse(&u).ok()) { + builder = builder.proxy(url); + } else if crate::proxy::is_off(crate::proxy::Kind::App) { + builder = builder.no_proxy(); + } if let Some(t) = target { builder = builder.target(t); } @@ -190,6 +197,39 @@ pub async fn update_download( if is_manual(&state) { return Err(MANAGED_MESSAGE.into()); } + match download_pending(&app, &state, &on_event).await { + // The feed and the file disagree: a release was being replaced while + // this check ran (the feed is new, the file still the old one, or + // the other way round). Read the feed again and try once more. + Err(e) if is_signature_error(&e) => { + log::warn!("[updater] {e}; checking the feed again"); + tokio::time::sleep(Duration::from_secs(5)).await; + update_check(app.clone(), state.clone()).await?; + download_pending(&app, &state, &on_event).await.map_err(|e| { + if is_signature_error(&e) { + "The update didn't match its signature, which happens while a new release is being published. \ + Nothing was installed. Try again in a few minutes." + .to_string() + } else { + e + } + }) + } + other => other, + } +} + +fn is_signature_error(e: &str) -> bool { + let e = e.to_ascii_lowercase(); + e.contains("signature") || e.contains("minisign") +} + +/// Download the update the last check found and stage it on disk. +async fn download_pending( + app: &AppHandle, + state: &State<'_, UpdateState>, + on_event: &Channel, +) -> Result { let update = lock(&state.pending) .clone() .ok_or("No update to download. Check for updates first.")?; @@ -217,7 +257,7 @@ pub async fn update_download( .await .map_err(|e| e.to_string())?; - let dir = updates_dir(&app)?; + let dir = updates_dir(app)?; // The version comes from the feed but was parsed as semver by the plugin, // so it is only digits, letters, dots, dashes and plus signs. let path = dir.join(format!("{}.update", update.version)); diff --git a/src-tauri/src/web_search.rs b/src-tauri/src/web_search.rs index 4278f38b..237a23ff 100644 --- a/src-tauri/src/web_search.rs +++ b/src-tauri/src/web_search.rs @@ -34,7 +34,7 @@ pub struct SearchHit { } fn client() -> Result { - reqwest::Client::builder() + crate::proxy::http_builder(crate::proxy::Kind::Ai) .timeout(TIMEOUT) .user_agent(UA) .build() diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 44dad772..ca8103fa 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Stroke", - "version": "3.0.0", + "version": "3.7.5", "identifier": "com.broisnischal.stroke", "build": { "frontendDist": "../dist", diff --git a/src-tauri/vendor/sqlx-mysql/src/connection/establish.rs b/src-tauri/vendor/sqlx-mysql/src/connection/establish.rs index 85a9d84f..e41f1ef1 100644 --- a/src-tauri/vendor/sqlx-mysql/src/connection/establish.rs +++ b/src-tauri/vendor/sqlx-mysql/src/connection/establish.rs @@ -18,7 +18,10 @@ impl MySqlConnection { let handshake = match &options.socket { Some(path) => crate::net::connect_uds(path, do_handshake).await?, - None => crate::net::connect_tcp(&options.host, options.port, do_handshake).await?, + None => { + let dial = options.hostaddr.as_deref().unwrap_or(&options.host); + crate::net::connect_tcp(dial, options.port, do_handshake).await? + } }; let stream = handshake?; diff --git a/src-tauri/vendor/sqlx-mysql/src/options/mod.rs b/src-tauri/vendor/sqlx-mysql/src/options/mod.rs index 87732cb4..4b37970e 100644 --- a/src-tauri/vendor/sqlx-mysql/src/options/mod.rs +++ b/src-tauri/vendor/sqlx-mysql/src/options/mod.rs @@ -64,6 +64,9 @@ pub struct MySqlConnectOptions { pub(crate) host: String, pub(crate) port: u16, pub(crate) socket: Option, + /// Stroke: where to open the TCP connection when it isn't `host`. `host` + /// still names the server for TLS. Used for SSH tunnels. + pub(crate) hostaddr: Option, pub(crate) username: String, pub(crate) password: Option, pub(crate) database: Option, @@ -95,6 +98,7 @@ impl MySqlConnectOptions { port: 3306, host: String::from("localhost"), socket: None, + hostaddr: None, username: String::from("root"), password: None, database: None, @@ -123,6 +127,13 @@ impl MySqlConnectOptions { self } + /// Stroke: open the TCP connection to `addr` instead of `host`. `host` is + /// still the name TLS verifies. + pub fn hostaddr(mut self, addr: &str) -> Self { + self.hostaddr = Some(addr.to_owned()); + self + } + /// Sets the port to connect to at the server host. /// /// The default port for MySQL is `3306`. diff --git a/src-tauri/vendor/sqlx-postgres/src/connection/mod.rs b/src-tauri/vendor/sqlx-postgres/src/connection/mod.rs index 0005f8e5..818e69a8 100644 --- a/src-tauri/vendor/sqlx-postgres/src/connection/mod.rs +++ b/src-tauri/vendor/sqlx-postgres/src/connection/mod.rs @@ -45,7 +45,6 @@ pub struct PgConnectionInner { // process id of this backend // used to send cancel requests - #[allow(dead_code)] process_id: u32, // secret key of this backend @@ -81,6 +80,13 @@ impl PgConnection { self.inner.stream.server_version_num } + /// The backend process id the server sent at startup (`BackendKeyData`), + /// so a caller can cancel this connection's query by pid without asking + /// `pg_backend_pid()` first. Behind a pooler it is the pooler's id. + pub fn backend_process_id(&self) -> u32 { + self.inner.process_id + } + // will return when the connection is ready for another query pub(crate) async fn wait_until_ready(&mut self) -> Result<(), Error> { if !self.inner.stream.write_buffer_mut().is_empty() { diff --git a/src-tauri/vendor/sqlx-postgres/src/connection/stream.rs b/src-tauri/vendor/sqlx-postgres/src/connection/stream.rs index e8a1aedc..8380ac14 100644 --- a/src-tauri/vendor/sqlx-postgres/src/connection/stream.rs +++ b/src-tauri/vendor/sqlx-postgres/src/connection/stream.rs @@ -44,7 +44,10 @@ impl PgStream { pub(super) async fn connect(options: &PgConnectOptions) -> Result { let socket_result = match options.fetch_socket() { Some(ref path) => net::connect_uds(path, MaybeUpgradeTls(options)).await?, - None => net::connect_tcp(&options.host, options.port, MaybeUpgradeTls(options)).await?, + None => { + let dial = options.hostaddr.as_deref().unwrap_or(&options.host); + net::connect_tcp(dial, options.port, MaybeUpgradeTls(options)).await? + } }; let socket = socket_result?; diff --git a/src-tauri/vendor/sqlx-postgres/src/options/mod.rs b/src-tauri/vendor/sqlx-postgres/src/options/mod.rs index 723721a9..59d7b204 100644 --- a/src-tauri/vendor/sqlx-postgres/src/options/mod.rs +++ b/src-tauri/vendor/sqlx-postgres/src/options/mod.rs @@ -18,6 +18,9 @@ pub struct PgConnectOptions { pub(crate) host: String, pub(crate) port: u16, pub(crate) socket: Option, + /// Stroke: where to open the TCP connection when it isn't `host` (libpq's + /// `hostaddr`). `host` still names the server for TLS. Used for SSH tunnels. + pub(crate) hostaddr: Option, pub(crate) username: String, pub(crate) password: Option, pub(crate) database: Option, @@ -72,6 +75,7 @@ impl PgConnectOptions { port, host, socket: None, + hostaddr: None, username, password: var("PGPASSWORD").ok(), database, @@ -127,6 +131,13 @@ impl PgConnectOptions { self } + /// Stroke: open the TCP connection to `addr` instead of `host`, like + /// libpq's `hostaddr`. `host` is still the name TLS verifies. + pub fn hostaddr(mut self, addr: &str) -> Self { + self.hostaddr = Some(addr.to_owned()); + self + } + /// Sets the port to connect to at the server host. /// /// The default port for PostgreSQL is `5432`. diff --git a/src/App.svelte b/src/App.svelte index f9178eef..e671c55e 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -2,8 +2,9 @@ import { toastPosition } from '$lib/stores/toast-position.js' import { onMount } from 'svelte' import { Toaster } from '$lib/components/ui/sonner/index.js' + import ZoomIndicator from '$lib/components/ZoomIndicator.svelte' import StudioShell from './lib/components/StudioShell.svelte' - import DashboardWindow from './lib/components/DashboardWindow.svelte' + // A window opened for one dashboard (open_dashboard_window) shows only that. const params = typeof location !== 'undefined' ? new URLSearchParams(location.search) : new URLSearchParams() @@ -88,6 +89,7 @@ + {#if dashboardView} - + {#await import('./lib/components/DashboardWindow.svelte') then { default: DashboardWindow }}{/await} {:else if localServersFrom} {#await import('./lib/components/LocalServersWindow.svelte') then { default: LocalServersWindow }} diff --git a/src/app.css b/src/app.css index b7b25386..d1bca431 100644 --- a/src/app.css +++ b/src/app.css @@ -97,7 +97,13 @@ `.dark` block below (toggled for every dark theme via classList) swaps in stronger black + a dim rim, since a light drop-shadow is nearly invisible on a dark surface and depth there comes from the rim highlight instead. */ - --elevate-1: 0 1px 2px oklch(0 0 0 / 0.05), 0 1px 1px oklch(0 0 0 / 0.04); + /* Level 1 is an outline, not a shadow: things that sit in the page (a + selected segment, a raised chip, a card) get a crisp 1px hairline. Small + soft shadows rendered as a grey smudge on Linux and Windows, and against + a dark surface they did not show at all. Only what floats (menus, + popovers, dialogs: levels 2 and 3) keeps a real shadow. Tailwind's + `shadow-xs` and `shadow-sm` resolve to this too (@theme below). */ + --elevate-1: 0 0 0 1px oklch(0 0 0 / 0.09); --elevate-2: 0 2px 5px -1px oklch(0 0 0 / 0.07), 0 6px 16px -3px oklch(0 0 0 / 0.09); --elevate-3: 0 10px 22px -6px oklch(0 0 0 / 0.11), 0 22px 52px -12px oklch(0 0 0 / 0.16); /* Top rim highlight - a 1px inner catch-light that gives raised surfaces a @@ -136,7 +142,7 @@ --warning-foreground: oklch(0.20 0.04 78); --info: oklch(0.71 0.13 245); --info-foreground: oklch(0.16 0.03 245); - --elevate-1: 0 1px 2px oklch(0 0 0 / 0.4), 0 1px 3px oklch(0 0 0 / 0.3); + --elevate-1: 0 0 0 1px oklch(1 0 0 / 0.09); --elevate-2: 0 2px 5px -1px oklch(0 0 0 / 0.45), 0 8px 20px -4px oklch(0 0 0 / 0.5); --elevate-3: 0 12px 28px -8px oklch(0 0 0 / 0.55), 0 28px 60px -16px oklch(0 0 0 / 0.62); --rim: inset 0 1px 0 0 oklch(1 0 0 / 0.055); @@ -294,10 +300,10 @@ textarea:not(.no-focus-ring):not(.no-field-frame):focus-visible { /* The search row at the top of a dropdown: borderless, with the hairline under it turning accent while you type in it. */ -[data-slot="menu-search"] { +[data-slot="menu-search"]:not(.search-shell):not(:has(.search-box)) { border-bottom: 1px solid color-mix(in oklch, var(--border) 50%, transparent); } -[data-slot="menu-search"]:focus-within { +[data-slot="menu-search"]:not(.search-shell):not(:has(.search-box)):focus-within { border-bottom-color: var(--ring); } @@ -424,6 +430,9 @@ html[data-os="linux"] { --window-radius: 8px; } @theme inline { + /* In-page "shadows" are hairline outlines (see --elevate-1). */ + --shadow-xs: var(--elevate-1); + --shadow-sm: var(--elevate-1); --radius-sm: calc(var(--radius) - 2px); --radius-md: var(--radius); --radius-lg: calc(var(--radius) + 2px); @@ -492,6 +501,18 @@ html[data-os="linux"] { --window-radius: 8px; } spellcheck: false; } + /* The window's chrome (title bar and its menus, tab strip, toolbars, + status bar) always reads in a proportional face, even when the app font + is all-monospace: the data keeps the chosen font, the frame around it + stays a desktop app's. In the base layer, so a `font-mono` utility inside + (a shortcut cap, a path) still wins. */ + [data-studio-region="titlebar"], + [data-studio-region="statusbar"], + [data-studio-chrome], + .chrome-font { + font-family: var(--font-chrome, var(--font-sans)); + } + html { font-size: var(--app-font-size); font-family: var(--font-sans); @@ -722,6 +743,24 @@ html[data-os="linux"] { --window-radius: 8px; } -webkit-font-smoothing: antialiased; } + /* Appearance > Font smoothing > System: the OS's own text rendering instead + of the thin grayscale the app uses everywhere else (on a Mac, the heavier + default macOS smoothing). After every rule above that forces grayscale. */ + html[data-smoothing='system'], + html[data-smoothing='system'] :is( + [data-slot='context-menu-content'], + [data-slot='dropdown-menu-content'], + [data-slot='select-content'], + [data-slot='dialog-content'], + [data-slot='popover-content'], + [role='dialog'], + [role='menu'], + [role='listbox'] + ) { + -webkit-font-smoothing: auto; + -moz-osx-font-smoothing: auto; + } + /* Sonner - frosted notifications */ .toaster, .studio-toaster, @@ -1125,6 +1164,15 @@ html[data-os="linux"] { --window-radius: 8px; } will-change: scroll-position; } + /* The main grid doesn't bounce. Scrolling into an edge on macOS rubber-banded + the whole scroll container, header and columns included, a few pixels + down and sideways before springing back: a flicker at the top of the grid + on every scroll to the start. An embedded grid (AI chat results) keeps + `contain`, so scrolling past its edge still reaches the chat around it. */ + [data-canvas-table="full"] { + overscroll-behavior: none; + } + /* Minimal thin scrollbars - all platforms */ :is(.app-scroll, .overflow-auto, .overflow-y-auto, .overflow-x-auto) { scrollbar-width: thin; @@ -1329,6 +1377,52 @@ html[data-motion="reduced"] .animate-spin { animation-iteration-count: infinite !important; } +/* ── Search fields ───────────────────────────────────────────────────────── + One look for every search box (DESIGN_SYSTEM.md, "Search fields"): an + outlined box over a faint fill, no shadow. A 1px outline reads as a field + on every platform; the fill alone vanished on light themes and drop shadows + rendered muddy on Linux and Windows. SearchField.svelte uses it, and so do + the hand-built filters that keep their own keyboard handling (the sidebar's). + In the components layer, so a size utility on one field still wins. */ +@layer components { + .search-box { + height: 2rem; + border-radius: var(--radius-lg); + border: 1px solid color-mix(in oklab, var(--border) 80%, transparent); + background-color: color-mix(in oklab, var(--muted) 30%, transparent); + color: var(--foreground); + outline: none; + transition: border-color 150ms ease-out, background-color 150ms ease-out, box-shadow 150ms ease-out; + } + .search-box::placeholder { color: var(--muted-foreground); } + .search-box:hover:not(:disabled):not(:focus) { border-color: color-mix(in oklab, var(--foreground) 20%, transparent); } + /* Focus is one crisp accent edge, hovered or not: no halo outside it. A + halo beside a hover-gray border read as two outlines. */ + .search-box:focus { + border-color: var(--ring); + background-color: color-mix(in oklab, var(--muted) 45%, transparent); + box-shadow: none; + } + .search-box:disabled { cursor: not-allowed; opacity: 0.4; } + .search-box::-webkit-search-cancel-button { display: none; } + /* The same box for a search built as a wrapper (icon, input, buttons in one + row): the wrapper carries the outline and lights up while the input has focus. */ + .search-shell { + border-radius: var(--radius-lg); + border: 1px solid color-mix(in oklab, var(--border) 80%, transparent); + background-color: color-mix(in oklab, var(--muted) 30%, transparent); + color: var(--foreground); + transition: border-color 150ms ease-out, background-color 150ms ease-out, box-shadow 150ms ease-out; + } + .search-shell:hover:not(:focus-within) { border-color: color-mix(in oklab, var(--foreground) 20%, transparent); } + .search-shell:focus-within { + border-color: var(--ring); + background-color: color-mix(in oklab, var(--muted) 45%, transparent); + } + .search-shell input { background: transparent; color: inherit; } + .search-shell input::placeholder { color: var(--muted-foreground); } +} + /* ── Hover-revealed row actions stay reachable by keyboard ─────────────────── Row actions across the app (remove-from-recent, copy-field, JSON row tools, policy row menus) fade in on `group-hover`. A keyboard user tabs into them @@ -1831,3 +1925,53 @@ html[data-os="linux"]:has([role="dialog"][data-state="open"], [role="alertdialog :is(.app-scroll, .overflow-auto, .overflow-y-auto, .overflow-x-auto):not(:is([role="dialog"], [role="alertdialog"]) *)::-webkit-scrollbar { display: none; } + +/* ── Switches: one geometry at every zoom ───────────────────────────────────── + The thumb is sized from the track's own height and slides by percentage, so + it stays centred and the gap stays even whatever the zoom. Switches used to + mix a pixel track (h-[18px], translate-x-[14px]) with a rem thumb that grew + with zoom, so zoomed in the thumb outgrew its track. */ +.app-switch { + position: relative; + display: inline-flex; + flex-shrink: 0; + height: 1.25rem; + width: 2.25rem; + border-radius: 9999px; + background-color: color-mix(in oklab, var(--muted-foreground) 30%, transparent); + transition: background-color 150ms ease-out; +} +.app-switch[data-size='sm'] { height: 1rem; width: 1.75rem; } +.app-switch[aria-checked='true'], +.app-switch[data-state='checked'] { background-color: var(--primary); } +.app-switch:disabled { opacity: 0.5; cursor: not-allowed; } +.app-switch:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; } +.app-switch-thumb { + position: absolute; + top: 0.125rem; + bottom: 0.125rem; + left: 0.125rem; + aspect-ratio: 1; + border-radius: 9999px; + background: #fff; + box-shadow: 0 1px 2px rgb(0 0 0 / 0.25); + pointer-events: none; + transition: left 160ms cubic-bezier(0.23, 1, 0.32, 1), transform 160ms cubic-bezier(0.23, 1, 0.32, 1); +} +.app-switch[aria-checked='true'] .app-switch-thumb, +.app-switch[data-state='checked'] .app-switch-thumb { + left: calc(100% - 0.125rem); + transform: translateX(-100%); + /* The token made to contrast with --primary: a near-white accent hid a + white knob. */ + background: var(--primary-foreground); +} + +/* A dialog is h-fit (fixed, inset-0, m-auto). WebKit sizes a flex-1 child of + it from its 0% basis, to nothing: Import data showed a sliver of its drop + zone. Chrome reads that basis as the content. Starting from the content + gives both the same dialog, and min-h-0 still lets the body shrink and + scroll once the dialog reaches its max height. */ +[data-slot="dialog-content"] > .flex-1 { + flex-basis: auto; +} diff --git a/src/lib/ai-query-engine.js b/src/lib/ai-query-engine.js new file mode 100644 index 00000000..f7194973 --- /dev/null +++ b/src/lib/ai-query-engine.js @@ -0,0 +1,20 @@ +// Which code fences run as queries on the active connection. Set by the shell +// when the connection changes; read by the AI reply parser (ai.js). Apart from +// ai.js so setting it does not pull the AI client into the startup bundle. +import { runnableFences } from '$lib/ai-query-languages.js' + +/** Extra fences that hold runnable queries on the active connection (```javascript for MongoDB, ...). */ +let _queryFences = /** @type {Set | null} */ (null) + +/** + * Called when the connection changes: a NoSQL engine's own query fences get + * a Run button like SQL blocks do. + * @param {string | null | undefined} engine + */ +export function setQueryEngine(engine) { + _queryFences = runnableFences(engine) +} + +export function getQueryFences() { + return _queryFences +} diff --git a/src/lib/ai-query-languages.js b/src/lib/ai-query-languages.js index c33a1c13..71463a30 100644 --- a/src/lib/ai-query-languages.js +++ b/src/lib/ai-query-languages.js @@ -63,6 +63,28 @@ export const QUERY_LANGUAGES = { - One document: users.get("u1"). A bare collection path lists its documents: products - Range filters on one field plus orderBy on another need a composite index in Firestore. The editor is read-only for Firestore: changes are made in the Browse page.`, + }, + influxdb: { + name: 'InfluxDB queries (SQL, InfluxQL or Flux)', + fence: 'sql', + collectionNoun: 'measurement', + guide: `The connection is read-only: only queries run. The language depends on the server version (the connection's version field): +- InfluxDB 3.x: SQL. SELECT host, avg(usage) FROM cpu WHERE time > now() - INTERVAL '1 hour' GROUP BY host. Tags and fields are columns, the timestamp is "time". date_bin(INTERVAL '5 minutes', time) buckets time. Prefix a statement with "influxql:" to run InfluxQL instead. +- InfluxDB 2.x: Flux or InfluxQL. Flux: from(bucket: "b") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "cpu" and r._field == "usage") |> aggregateWindow(every: 5m, fn: mean). Always start Flux with range(). +- InfluxDB 1.x and 2.x InfluxQL: SELECT mean("usage") FROM "cpu" WHERE time > now() - 1h GROUP BY time(5m), "host". SHOW MEASUREMENTS, SHOW TAG KEYS FROM "cpu", SHOW FIELD KEYS FROM "cpu". +- Always bound time and add LIMIT; tables can hold billions of points.`, + }, + neo4j: { + name: 'Cypher (Neo4j)', + fence: 'cypher', + collectionNoun: 'label', + guide: `Write one Cypher statement per block. Not SQL. The sidebar's collections are node labels. +- Read: MATCH (p:Person)-[:KNOWS]->(f:Person) WHERE p.name = 'Ada' RETURN f.name, f.born ORDER BY f.born LIMIT 25 +- Return properties (p.name) or maps (p {.name, .born}) rather than whole nodes when a table is wanted. +- Counts and grouping: MATCH (o:Order) RETURN o.status AS status, count(*) AS n ORDER BY n DESC. Grouping is implicit in RETURN. +- Schema: CALL db.labels(), CALL db.relationshipTypes(), CALL db.schema.visualization(), SHOW INDEXES. +- Always add LIMIT unless the user asks for everything. Quote unusual labels with backticks. +- Writes, when your access level allows them: CREATE, MERGE, SET, REMOVE, DETACH DELETE. Index and constraint changes need schema access.`, }, cassandra: { name: 'CQL (Cassandra Query Language)', @@ -157,6 +179,10 @@ export function sampleQuery(engine, schema, coll, n) { return `GET ${coll}/_search\n{"size": ${n}}` case 'firestore': return `${coll}.limit(${n})` + case 'influxdb': + return `SELECT * FROM "${coll.replace(/"/g, '\\"')}" ORDER BY time DESC LIMIT ${n}` + case 'neo4j': + return `MATCH (n:${/^[A-Za-z_]\w*$/.test(coll) ? coll : `\`${coll.replace(/`/g, '``')}\``}) RETURN n LIMIT ${n}` case 'cassandra': return `SELECT * FROM ${schema ? `${q(schema)}.` : ''}${q(coll)} LIMIT ${n}` default: @@ -192,6 +218,6 @@ export function describeFromSample(coll, result) { export function runnableFences(engine) { const lang = queryLanguageFor(engine) if (!lang) return null - const extra = { mongodb: ['javascript', 'js', 'mongodb', 'mongo'], couchdb: ['javascript', 'js', 'json'], elasticsearch: ['json', 'http', 'text', 'sql'], opensearch: ['json', 'http', 'text', 'sql'], firestore: ['javascript', 'js'], cassandra: ['sql', 'cql'], dynamodb: ['sql', 'partiql'], redis: ['redis', 'text', 'bash'], valkey: ['redis', 'text', 'bash'] } + const extra = { mongodb: ['javascript', 'js', 'mongodb', 'mongo'], couchdb: ['javascript', 'js', 'json'], elasticsearch: ['json', 'http', 'text', 'sql'], opensearch: ['json', 'http', 'text', 'sql'], firestore: ['javascript', 'js'], neo4j: ['cypher', 'sql', 'text'], influxdb: ['sql', 'influxql', 'flux', 'text'], cassandra: ['sql', 'cql'], dynamodb: ['sql', 'partiql'], redis: ['redis', 'text', 'bash'], valkey: ['redis', 'text', 'bash'] } return new Set([lang.fence, ...(/** @type {Record} */ (extra)[/** @type {string} */ (engine)] ?? [])]) } diff --git a/src/lib/ai.js b/src/lib/ai.js index 61ef81d6..fb8046b5 100644 --- a/src/lib/ai.js +++ b/src/lib/ai.js @@ -15,50 +15,11 @@ */ import { formatCompactCount } from '$lib/table-list.js' -import { queryLanguageFor, queryLanguagePrompt, runnableFences } from '$lib/ai-query-languages.js' +import { queryLanguageFor, queryLanguagePrompt } from '$lib/ai-query-languages.js' +import { getQueryFences } from '$lib/ai-query-engine.js' import { engineLabel } from '$lib/db-capabilities.js' -/** - * Reduce a driver error to the sentence a human needs. - * - * Engines wrap the useful part in transport noise: D1 returns the whole HTTP - * envelope (`D1 API error 400 Bad Request: {"messages":[],"result":[],…}`) around - * a five-word cause. Dumping that raw makes a one-line "no such column: activated" - * read as a stack trace. The full text is still available on the tool channel and - * in the query log; this is only what gets shown. - * - * Returns the input trimmed when nothing better can be extracted - never empty. - * @param {string} raw - * @returns {string} - */ -export function humanizeDbError(raw) { - const text = String(raw ?? '').replace(/^Error:\s*/i, '').trim() - if (!text) return 'Query failed' - - // Cloudflare-style envelope: pull the innermost `"message"` out of the JSON tail. - const jsonStart = text.search(/[{[]/) - if (jsonStart !== -1) { - try { - const parsed = JSON.parse(text.slice(jsonStart)) - const errs = Array.isArray(parsed) ? parsed : parsed?.errors - const msg = Array.isArray(errs) ? errs.find((e) => e?.message)?.message : parsed?.message - if (typeof msg === 'string' && msg.trim()) return cleanEngineMessage(msg) - } catch { /* not JSON, fall through to the regex below */ } - // Unparseable tail (truncated payload) - lift the first "message" it contains. - const m = text.slice(jsonStart).match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)"/) - if (m) return cleanEngineMessage(m[1].replace(/\\"/g, '"')) - } - return cleanEngineMessage(text) -} - -/** Trim engine bookkeeping that means nothing to the reader. */ -function cleanEngineMessage(msg) { - return String(msg) - // SQLite appends its own error class and a byte offset into the statement. - .replace(/\s+at offset \d+/i, '') - .replace(/:\s*SQLITE_ERROR$/i, '') - .trim() || 'Query failed' -} +export { humanizeDbError } from '$lib/db-error-text.js' /** * Classify a DB error string into an actionable hint for the AI. @@ -1507,16 +1468,7 @@ export function stripThinkTags(content) { */ const SQL_LANGS = new Set(['sql', 'pgsql', 'postgresql', 'plpgsql', 'sqlite', 'tsql', 'mysql', 'mariadb']) -/** Extra fences that hold runnable queries on the active connection (```javascript for MongoDB, ...). */ -let _queryFences = /** @type {Set | null} */ (null) -/** - * Called when the connection changes: a NoSQL engine's own query fences get - * a Run button like SQL blocks do. - * @param {string | null | undefined} engine - */ -export function setQueryEngine(engine) { - _queryFences = runnableFences(engine) -} +export { setQueryEngine } from '$lib/ai-query-engine.js' export function parseAssistantMessage(rawContent) { // Strip internal chain-of-thought @@ -1555,7 +1507,7 @@ export function parseAssistantMessage(rawContent) { else parts.push({ type: 'code', lang: 'json', content: code }) } else if (lang === 'mermaid' || lang === 'mmd' || MERMAID_HEAD_RE.test(code)) { parts.push({ type: 'mermaid', content: code }) - } else if (SQL_LANGS.has(lang) || _queryFences?.has(lang) || (!lang && looksLikeQuery(code))) { + } else if (SQL_LANGS.has(lang) || getQueryFences()?.has(lang) || (!lang && looksLikeQuery(code))) { // An unlabelled block is only a query when it reads like one. A // text-art chart or a plain listing used to get the SQL card and // its Run button, and running it failed. @@ -1606,7 +1558,7 @@ export function parseAssistantMessage(rawContent) { } else if (lang === 'mermaid' || lang === 'mmd' || MERMAID_HEAD_RE.test(code.trimStart())) { parts.push({ type: 'pending', kind: 'diagram', content: code }) } else if (code.trim()) { - if (!lang || SQL_LANGS.has(lang) || _queryFences?.has(lang)) parts.push({ type: 'sql', content: code.trim() }) + if (!lang || SQL_LANGS.has(lang) || getQueryFences()?.has(lang)) parts.push({ type: 'sql', content: code.trim() }) else parts.push({ type: 'code', lang, content: code.trim() }) } else if (nl === -1 && !lang) { // Just the opening backticks so far: nothing worth drawing yet. diff --git a/src/lib/api-tls.test.js b/src/lib/api-tls.test.js new file mode 100644 index 00000000..12a02fcf --- /dev/null +++ b/src/lib/api-tls.test.js @@ -0,0 +1,23 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), Channel: class {} })) +vi.mock('$lib/stores/settings.js', () => ({ loadSettings: () => ({}) })) +vi.mock('$lib/stores/query-log.js', () => ({ recordQuery: () => {} })) +vi.mock('$lib/stores/read-only.js', () => ({ assertWritable: () => {} })) +vi.mock('$lib/stores/connections.js', () => ({ getLastConnection: () => null })) + +describe('withTlsAndParams', () => { + it('carries verify-full, its CA and the URL parameters to the backend', async () => { + const { withTlsAndParams, normalizeConnectionConfig } = await import('./api.js') + const saved = { host: 'h', port: 5432, database: 'd', user: 'u', password: 'p', ssl: true, sslMode: 'verify-full', sslRootCert: '/ca.pem', params: 'application_name=x' } + expect(withTlsAndParams(normalizeConnectionConfig(saved), saved)).toMatchObject({ + ssl: true, sslMode: 'verify-full', sslRootCert: '/ca.pem', params: 'application_name=x', + }) + }) + + it('sends no TLS mode with TLS off, so it cannot turn TLS back on', async () => { + const { withTlsAndParams } = await import('./api.js') + const out = withTlsAndParams({ ssl: false }, { ssl: false, sslMode: 'verify-full', sslRootCert: '/ca.pem' }) + expect(out).toEqual({ ssl: false }) + }) +}) diff --git a/src/lib/api.js b/src/lib/api.js index 7bc335f4..61395e0b 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -5,6 +5,8 @@ import { recordQuery } from '$lib/stores/query-log.js' import { assertWritable } from '$lib/stores/read-only.js' import { getLastConnection } from '$lib/stores/connections.js' import { isWriteSql } from '$lib/sql-write.js' +import { odbcConfigOf } from '$lib/odbc-presets.js' +import { setOdbcDialect, setSpannerDialect } from '$lib/sql-ident.js' /** @typedef {{ name: string, host: string, port: number, database: string, user: string, password: string, ssl: boolean }} PgConnectionConfig */ /** @typedef {{ name: string, filePath: string }} SqliteConnectionConfig */ @@ -191,19 +193,34 @@ export async function liveStop() { // ── PostgreSQL ──────────────────────────────────────────────────────────────── -/** @param {{ host: string, port?: number, username: string, privateKeyPath?: string }} ssh */ +/** @param {{ host: string, port?: number, username: string, privateKeyPath?: string, keepalive?: number }} ssh */ function normalizeSshConfig(ssh) { return { host: String(ssh.host || '').trim(), port: Math.min(65535, Math.max(1, Number(ssh.port) || 22)), username: String(ssh.username || '').trim(), privateKeyPath: String(ssh.privateKeyPath || '').trim(), + // Seconds; 0 turns it off. Dropped here before, so the form's value never + // reached ssh and every tunnel ran at the default 30. + keepalive: Math.max(0, Math.min(3600, Number(ssh.keepalive ?? 30) || 0)), + // Kubernetes and SSM tunnels (db/ssh_tunnel.rs): `host` is the resource or + // the target, and these say where to find it. + ...(ssh.kind === 'kubernetes' || ssh.kind === 'ssm' + ? { + kind: ssh.kind, + context: String(ssh.context || '').trim(), + namespace: String(ssh.namespace || '').trim(), + region: String(ssh.region || '').trim(), + profile: String(ssh.profile || '').trim(), + } + : {}), } } /** Attach SSH config to a connection payload when the user has configured a tunnel. */ function withSsh(payload, config) { - if (config.ssh && config.ssh.host && config.ssh.username) { + const s = config.ssh + if (s && s.host && (s.username || s.kind === 'kubernetes' || s.kind === 'ssm')) { return { ...payload, ssh: normalizeSshConfig(config.ssh) } } return payload @@ -224,12 +241,29 @@ function withTimezone(payload) { return payload } +/** + * The TLS verification level and CA, and a Postgres URL's other parameters. + * The payloads above are rebuilt field by field, and these were not among the + * fields: a connection set to verify-full with a CA connected as plain + * `require` (encrypted, certificate never checked), and a pasted URL's + * application_name or options never left the form. Sent only with TLS on, as + * the form does: `sslMode` alone would turn it back on in the backend. + * @param {Record} payload @param {Record} config + */ +export function withTlsAndParams(payload, config) { + const out = { ...payload } + if (config.ssl && config.sslMode) out.sslMode = String(config.sslMode) + if (config.ssl && config.sslRootCert) out.sslRootCert = String(config.sslRootCert) + if (config.params && String(config.params).trim()) out.params = String(config.params).trim() + return out +} + export async function testPostgresConnection(config) { - return inv('test_postgres_connection', { config: withSsh(withTimezone(normalizeConnectionConfig(config)), config) }) + return inv('test_postgres_connection', { config: withSsh(withTlsAndParams(withTimezone(normalizeConnectionConfig(config)), config), config) }) } export async function connectPostgres(config) { - return connectInv('connect_postgres', { config: withSsh(withTimezone(normalizeConnectionConfig(config)), config) }) + return connectInv('connect_postgres', { config: withSsh(withTlsAndParams(withTimezone(normalizeConnectionConfig(config)), config), config) }) } /** Toggle the WebView DevTools (no-op in release builds). */ @@ -271,7 +305,7 @@ export async function testMysqlConnection(config) { password: String(config.password || ''), ssl: Boolean(config.ssl), } - return inv('test_mysql', { config: withSsh(withTimezone(base), config) }) + return inv('test_mysql', { config: withSsh(withTlsAndParams(withTimezone(base), config), config) }) } /** @param {{ name: string, host: string, port: number, database: string, user: string, password: string, ssl: boolean, ssh?: object }} config */ @@ -285,7 +319,7 @@ export async function connectMysql(config) { password: String(config.password || ''), ssl: Boolean(config.ssl), } - return connectInv('connect_mysql_db', { config: withSsh(withTimezone(base), config) }) + return connectInv('connect_mysql_db', { config: withSsh(withTlsAndParams(withTimezone(base), config), config) }) } // ── Cloudflare D1 ───────────────────────────────────────────────────────────── @@ -418,7 +452,7 @@ export async function connectPosthog(config) { /** @param {{ name: string, host: string, port: number|string, database: string, user: string, password: string, secure?: boolean }} config */ function normalizeClickhouse(config) { - return { + return withSsh({ name: String(config.name || 'ClickHouse'), host: String(config.host || '127.0.0.1'), port: Math.min(65535, Math.max(1, Number(config.port) || 8123)), @@ -426,7 +460,7 @@ function normalizeClickhouse(config) { user: String(config.user || 'default'), password: String(config.password || ''), secure: Boolean(config.secure), - } + }, config) } /** @param {{ name: string, host: string, port: number|string, database: string, user: string, password: string, secure?: boolean }} config */ @@ -443,7 +477,7 @@ export async function connectClickhouse(config) { /** @param {{ name: string, host: string, port: number|string, password?: string, db?: number|string, tls?: boolean }} config */ function normalizeRedis(config) { - return { + return withSsh({ type: 'redis', name: String(config.name || 'Redis'), host: String(config.host || '127.0.0.1'), @@ -451,7 +485,7 @@ function normalizeRedis(config) { password: config.password || null, db: Number(config.db) || 0, tls: !!config.tls, - } + }, config) } /** @param {{ name: string, host: string, port: number|string, password?: string, db?: number|string, tls?: boolean }} config */ @@ -609,13 +643,13 @@ export async function dynamoRequest(op, body = {}) { /** @param {CouchConnConfig} config */ function normalizeCouch(config) { - return { + return withSsh({ type: 'couchdb', name: String(config.name || 'CouchDB'), url: String(config.url || 'http://localhost:5984').trim(), user: (config.user && String(config.user).trim()) || null, password: config.password || null, - } + }, config) } /** @param {CouchConnConfig} config */ @@ -646,7 +680,7 @@ export async function couchRequest(method, path, body) { /** @param {EsConnConfig} config */ function normalizeEs(config) { const flavor = config.type === 'opensearch' ? 'opensearch' : 'elasticsearch' - return { + return withSsh({ type: flavor, flavor, name: String(config.name || (flavor === 'opensearch' ? 'OpenSearch' : 'Elasticsearch')), @@ -655,7 +689,7 @@ function normalizeEs(config) { password: config.password || null, apiKey: (config.apiKey && String(config.apiKey).trim()) || null, insecure: !!config.insecure, - } + }, config) } /** @@ -702,12 +736,12 @@ export async function elasticImport(index, path, opts = {}) { /** @param {MongoConnConfig} config */ function normalizeMongo(config) { - return { + return withSsh({ type: 'mongodb', name: String(config.name || 'MongoDB'), uri: String(config.uri || 'mongodb://localhost:27017').trim(), database: (config.database && String(config.database).trim()) || null, - } + }, config) } /** @param {MongoConnConfig} config */ @@ -888,6 +922,110 @@ export async function connectFirestore(config) { return connectInv('connect_firestore_db', { config: normalizeFirestore(config) }) } +// ── InfluxDB (beta, read-only) ──────────────────────────────────────────────── + +/** + * @typedef {{ name?: string, url?: string, version?: '1'|'2'|'3', database?: string, org?: string, + * token?: string, user?: string, password?: string }} InfluxConnConfig + */ + +/** @param {InfluxConnConfig} config */ +function normalizeInflux(config) { + /** @param {string | undefined} s */ + const opt = (s) => (s && String(s).trim()) || null + const version = config.version || '2' + return { + type: 'influxdb', + name: String(config.name || 'InfluxDB'), + url: String(config.url || '').trim(), + version, + database: String(config.database || '').trim(), + org: version === '2' ? opt(config.org) : null, + token: version === '1' ? null : (config.token || null), + user: version === '1' ? opt(config.user) : null, + password: version === '1' ? (config.password || null) : null, + } +} + +/** @param {InfluxConnConfig} config */ +export async function testInflux(config) { + return inv('test_influx', { config: normalizeInflux(config) }) +} + +/** @param {InfluxConnConfig} config */ +export async function connectInflux(config) { + return connectInv('connect_influx_db', { config: normalizeInflux(config) }) +} + +export async function influxMeasurements() { + return inv('influx_measurements') +} + +/** @param {string} measurement */ +export async function influxDescribe(measurement) { + return inv('influx_describe', { measurement }) +} + +/** @param {string} measurement @param {string} filter @param {number} skip @param {number} limit */ +export async function influxPage(measurement, filter, skip, limit) { + return inv('influx_page', { measurement, filter: filter || null, skip, limit }) +} + +// ── Neo4j (beta) ────────────────────────────────────────────────────────────── + +/** @typedef {{ name?: string, url?: string, database?: string, user?: string, password?: string }} Neo4jConnConfig */ + +/** @param {Neo4jConnConfig} config */ +function normalizeNeo4j(config) { + /** @param {string | undefined} s */ + const opt = (s) => (s && String(s).trim()) || null + return { + type: 'neo4j', + name: String(config.name || 'Neo4j'), + url: String(config.url || '').trim(), + database: opt(config.database), + user: opt(config.user), + password: config.password || null, + } +} + +/** @param {Neo4jConnConfig} config */ +export async function testNeo4j(config) { + return inv('test_neo4j', { config: normalizeNeo4j(config) }) +} + +/** @param {Neo4jConnConfig} config */ +export async function connectNeo4j(config) { + return connectInv('connect_neo4j_db', { config: normalizeNeo4j(config) }) +} + +/** Node labels with their node counts. @returns {Promise<[string, number][]>} */ +export async function neo4jLabels() { + return inv('neo4j_labels') +} + +/** @param {string} label */ +export async function neo4jDescribe(label) { + return inv('neo4j_describe', { label }) +} + +/** @param {string} label @param {string} filter @param {number} skip @param {number} limit */ +export async function neo4jPage(label, filter, skip, limit) { + return inv('neo4j_page', { label, filter: filter || null, skip, limit }) +} + +/** @param {string} label @param {Record} doc */ +export async function neo4jSave(label, doc) { + assertWritable('change nodes') + return inv('neo4j_save', { label, doc }) +} + +/** @param {string} id */ +export async function neo4jDelete(id) { + assertWritable('delete nodes') + return inv('neo4j_delete', { id }) +} + /** * One Firestore REST call on the active connection; `path` starts with * `projects/...`. Only this database's documents are reachable. @@ -899,6 +1037,131 @@ export async function firestoreRequest(method, path, body) { return inv('firestore_request', { method, path, body: body ?? null }) } +// ── Spanner (beta) ─────────────────────────────────────────────────────────── + +/** + * @typedef {{ name?: string, projectId?: string, instanceId?: string, databaseId?: string, + * auth?: 'emulator' | 'serviceAccount' | 'gcloud', keyFile?: string, emulatorHost?: string }} SpannerConnConfig + */ + +/** @param {SpannerConnConfig} config */ +function normalizeSpanner(config) { + /** @param {string | undefined} s */ + const opt = (s) => (s && String(s).trim()) || null + return { + name: String(config.name || 'Spanner'), + projectId: String(config.projectId || '').trim(), + instanceId: String(config.instanceId || '').trim(), + databaseId: String(config.databaseId || '').trim(), + auth: config.auth || 'gcloud', + keyFile: opt(config.keyFile), + emulatorHost: opt(config.emulatorHost), + } +} + +/** @param {SpannerConnConfig} config */ +export async function testSpanner(config) { + return inv('test_spanner', { config: normalizeSpanner(config) }) +} + +/** @param {SpannerConnConfig} config */ +export async function connectSpanner(config) { + const dialect = await connectInv('connect_spanner_db', { config: normalizeSpanner(config) }) + setSpannerDialect(/** @type {string} */ (dialect)) + return dialect +} + +// ── BigQuery (beta) ────────────────────────────────────────────────────────── + +/** + * @typedef {{ name?: string, projectId?: string, dataset?: string, location?: string, + * auth?: 'emulator' | 'serviceAccount' | 'gcloud', keyFile?: string, emulatorHost?: string }} BigqueryConnConfig + */ + +/** @param {BigqueryConnConfig} config */ +function normalizeBigquery(config) { + /** @param {string | undefined} s */ + const opt = (s) => (s && String(s).trim()) || null + return { + name: String(config.name || 'BigQuery'), + projectId: String(config.projectId || '').trim(), + dataset: opt(config.dataset), + location: opt(config.location), + auth: config.auth || 'gcloud', + keyFile: opt(config.keyFile), + emulatorHost: opt(config.emulatorHost), + } +} + +/** @param {BigqueryConnConfig} config */ +export async function testBigquery(config) { + return inv('test_bigquery', { config: normalizeBigquery(config) }) +} + +/** @param {BigqueryConnConfig} config */ +export async function connectBigquery(config) { + return connectInv('connect_bigquery_db', { config: normalizeBigquery(config) }) +} + +// ── Snowflake (beta) ───────────────────────────────────────────────────────── + +/** @param {any} c a saved-connection shaped Snowflake config */ +function normalizeSnowflake(c) { + /** @param {string | undefined} s */ + const opt = (s) => (s && String(s).trim()) || null + return { + name: String(c.name || 'Snowflake'), + account: String(c.account || '').trim(), + user: String(c.user || '').trim(), + auth: c.auth === 'token' ? 'token' : 'keypair', + privateKeyFile: opt(c.privateKeyFile), + password: c.auth === 'token' ? c.password || null : null, + warehouse: opt(c.warehouse), + database: String(c.database || '').trim(), + schema: opt(c.schema), + role: opt(c.role), + host: opt(c.host), + } +} + +/** @param {any} config */ +export async function testSnowflake(config) { + return inv('test_snowflake', { config: normalizeSnowflake(config) }) +} + +/** @param {any} config */ +export async function connectSnowflake(config) { + return connectInv('connect_snowflake_db', { config: normalizeSnowflake(config) }) +} + +// ── ODBC (beta) ────────────────────────────────────────────────────────────── + +/** + * Test an ODBC connection; resolves to what the driver says it is + * (`DB2/LINUXX8664`, `HDB`, ...). + * @param {any} config a saved-connection shaped ODBC config + */ +export async function testOdbc(config) { + return /** @type {Promise} */ (inv('test_odbc', { config: odbcConfigOf(config) })) +} + +/** @param {any} config */ +export async function connectOdbc(config) { + const info = await connectInv('connect_odbc_db', { config: odbcConfigOf(config) }) + setOdbcDialect(info) + return info +} + +/** The ODBC drivers installed here. @returns {Promise<{ name: string, path?: string }[]>} */ +export async function odbcDrivers() { + return inv('odbc_drivers') +} + +/** The ODBC data sources (DSNs) set up here. @returns {Promise<{ name: string, driver: string }[]>} */ +export async function odbcDataSources() { + return inv('odbc_data_sources') +} + // ── Cassandra ───────────────────────────────────────────────────────────────── /** @typedef {{ name?: string, hosts?: string, user?: string, password?: string, keyspace?: string }} CassandraConnConfig */ @@ -907,14 +1170,14 @@ export async function firestoreRequest(method, path, body) { function normalizeCassandra(config) { /** @param {string | undefined} s */ const opt = (s) => (s && String(s).trim()) || null - return { + return withSsh({ type: 'cassandra', name: String(config.name || 'Cassandra'), hosts: String(config.hosts || '127.0.0.1').trim(), user: opt(config.user), password: config.password || null, keyspace: opt(config.keyspace), - } + }, config) } /** @param {CassandraConnConfig} config */ @@ -985,7 +1248,7 @@ export async function connectDuckdb(config) { /** @param {{ name: string, host: string, port: number|string, database: string, user: string, password: string, encrypt?: boolean, trustCert?: boolean }} config */ function normalizeMssql(config) { - return { + return withSsh({ name: String(config.name || 'SQL Server'), host: String(config.host || '127.0.0.1'), port: Math.min(65535, Math.max(1, Number(config.port) || 1433)), @@ -994,7 +1257,7 @@ function normalizeMssql(config) { password: String(config.password || ''), encrypt: Boolean(config.encrypt), trustCert: Boolean(config.trustCert), - } + }, config) } /** @param {{ name: string, host: string, port: number|string, database: string, user: string, password: string, encrypt?: boolean, trustCert?: boolean }} config */ @@ -1016,7 +1279,7 @@ export async function connectMssql(config) { /** @param {OracleConnConfig} config */ function normalizeOracle(config) { - return { + return withSsh({ name: String(config.name || 'Oracle'), host: String(config.host || '127.0.0.1').trim(), port: Math.min(65535, Math.max(1, Number(config.port) || 1521)), @@ -1026,7 +1289,7 @@ function normalizeOracle(config) { user: String(config.user ?? '').trim(), password: String(config.password ?? ''), clientLibDir: String(config.clientLibDir ?? '').trim(), - } + }, config) } /** @param {OracleConnConfig} config */ @@ -1383,6 +1646,23 @@ export async function getTableRows(schema, table, limit, offset, query = {}) { table, limit, offset, + ...tableRowsQueryArgs(query), + // The grid view this is for ({ group: tab id, generation: its load number}); + // a newer load of the same tab cancels it on the server. + fetchTag: query.fetchTag ?? null, + }) + recordQuery({ sql: r?.sql, durationMs: r?.queryMs ?? Math.round(performance.now() - _t0), schema, table, source: 'browse', success: true }) + traceRows('pg_get_table_rows', r, performance.now() - _t0) + return r +} + +/** + * The query half of a table-rows call, shared by getTableRows and the table + * mirror so both run exactly the same SELECT. + * @param {any} query + */ +function tableRowsQueryArgs(query) { + return { search: query.search?.trim() || null, searchIsRegex: query.searchIsRegex ?? false, searchCaseSensitive: query.searchCaseSensitive ?? false, @@ -1403,10 +1683,21 @@ export async function getTableRows(schema, table, limit, offset, query = {}) { // Fetch a wide column as a size and load its value per cell (Settings → // Data). Off means every value on the page, whatever it weighs. previewWide: (() => { try { return loadSettings().lazyWideColumns !== false } catch { return true } })(), - }) - recordQuery({ sql: r?.sql, durationMs: r?.queryMs ?? Math.round(performance.now() - _t0), schema, table, source: 'browse', success: true }) - traceRows('pg_get_table_rows', r, performance.now() - _t0) - return r + } +} + +/** + * Copy a windowed table view into the backend's result store, page by page, so + * its windows can be read locally (`resultWindow`) instead of by a remote OFFSET. + * Resolves with the rows mirrored once the walk ends; `resultDrop(id)` stops it. + * @param {string} id @param {string} schema @param {string} table @param {any} query as for getTableRows + * @param {{ column: string, sqlType: string, desc: boolean, index: number }} seek + * @param {number} maxRows + * @returns {Promise} + */ +export async function startTableMirror(id, schema, table, query, seek, maxRows, { pageRows, parallel } = /** @type {{ pageRows?: number, parallel?: number }} */ ({})) { + const { keyset: _k, includeMeta: _m, includeCount: _c, ...args } = tableRowsQueryArgs(query) + return await inv('table_mirror', { id, schema, table, ...args, seek, maxRows, pageRows: pageRows ?? null, parallel: parallel ?? null }) } /** @@ -1690,10 +1981,11 @@ export async function instanceSetConfig(name, value) { /** * The query plan. `analyze` (Postgres) runs the statement for actual rows and * times, inside a transaction that is rolled back; off, only estimates. - * @param {string} sql @param {{ analyze?: boolean }} [opts] + * `queryId` lets `cancelQuery` stop an ANALYZE on the server. + * @param {string} sql @param {{ analyze?: boolean, queryId?: string }} [opts] */ export async function explainSql(sql, opts = {}) { - return inv('pg_explain_sql', { sql, analyze: opts.analyze ?? true }) + return inv('pg_explain_sql', { sql, analyze: opts.analyze ?? true, queryId: opts.queryId ?? null }) } /** @@ -1966,6 +2258,7 @@ export async function backupCancel() { * @property {number} rowsAffected * @property {number} openMs how long the transaction has been held * @property {string|null} engine + * @property {number|null} [blocking] sessions waiting on a lock it holds (null: the engine can't say) */ /** @@ -2012,6 +2305,11 @@ export async function txStatus(sessionId) { return inv('tx_status', { sessionId }) } +/** Ids of every open transaction session, for the quit guard. @returns {Promise} */ +export async function txOpenSessions() { + return inv('tx_open_sessions', {}) +} + /** * A read for a console write's undo copy (sql-undo.js), outside any * transaction. Not logged as a query of the user's, and stoppable through the @@ -2161,6 +2459,18 @@ export async function openNotebookFile() { return { path, content } } +/** + * Show an open dialog for one file of `filter`'s kind and read it as text. + * @param {{ name: string, extensions: string[] }} filter + * @returns {Promise<{ path: string, content: string } | null>} null when cancelled + */ +export async function openTextFileAs(filter) { + const { open } = await import('@tauri-apps/plugin-dialog') + const path = await open({ filters: [filter], multiple: false }) + if (!path || typeof path !== 'string') return null + return { path, content: await readFile(path) } +} + /** * Show a save dialog for .sqlnb files, then write the content. * @param {string} content diff --git a/src/lib/app-reveal.js b/src/lib/app-reveal.js index ba807040..3f460e0c 100644 --- a/src/lib/app-reveal.js +++ b/src/lib/app-reveal.js @@ -47,6 +47,36 @@ export function revealApp() { // rather than a page fading in. document.documentElement.dataset.revealed = '' void showWindow() + recordBootTiming() +} + +/** + * Where the last launch spent its time before the first screen, in ms from + * navigation start: the page parsed (`html`), every statically imported + * module evaluated (`main`), the app mounted (`mount`), the first screen was + * ready (`reveal`). Kept in + * localStorage as `stroke:last-boot`, so a slow start can be read back + * instead of guessed at. Marks only; nothing is sent anywhere. + */ +function recordBootTiming() { + try { + const at = (/** @type {string} */ name) => { + const m = performance.getEntriesByName(name, 'mark')[0] + return m ? Math.round(m.startTime) : null + } + const nav = /** @type {PerformanceNavigationTiming | undefined} */ (performance.getEntriesByType('navigation')[0]) + const timing = { + html: nav ? Math.round(nav.domInteractive) : null, + main: at('stroke:main'), + settings: at('stroke:settings'), + connections: at('stroke:connections'), + mount: at('stroke:mount'), + lockReady: at('stroke:lock-ready'), + shell: at('stroke:shell'), + reveal: Math.round(performance.now()), + } + localStorage.setItem('stroke:last-boot', JSON.stringify(timing)) + } catch { /* storage blocked: nothing to record */ } } /** Never leave a blank window: reveal regardless if no screen claimed it. */ diff --git a/src/lib/cell-format.js b/src/lib/cell-format.js index 1a1cd7a3..a4c1d47f 100644 --- a/src/lib/cell-format.js +++ b/src/lib/cell-format.js @@ -1,3 +1,4 @@ +import { displayInstant } from './timezone.js'; /** * Cell values as text: CSV, Markdown, SQL literals and JSON for the grid's * copy and export, plus the type checks and comparison the grid's editing @@ -68,7 +69,7 @@ export function cellJsonString(value) { /** Escape a cell value for CSV (RFC 4180). */ export function csvCell(value) { if (value === null || value === undefined) return ''; - const s = typeof value === 'object' ? cellJsonString(value) : String(value); + const s = typeof value === 'object' ? cellJsonString(value) : typeof value === 'string' ? displayInstant(value) : String(value); if (s.includes(',') || s.includes('"') || s.includes('\n') || s.includes('\r')) { return '"' + s.replace(/"/g, '""') + '"'; } @@ -90,7 +91,7 @@ export function cellSqlLiteral(value) { /** Markdown-safe cell text. */ export function mdCell(value) { if (value === null || value === undefined) return 'NULL'; - const s = typeof value === 'object' ? cellJsonString(value) : String(value); + const s = typeof value === 'object' ? cellJsonString(value) : typeof value === 'string' ? displayInstant(value) : String(value); return s.replace(/\|/g, '\\|').replace(/\n/g, ' '); } diff --git a/src/lib/cell-value.js b/src/lib/cell-value.js index 0056ea28..1936052f 100644 --- a/src/lib/cell-value.js +++ b/src/lib/cell-value.js @@ -49,8 +49,11 @@ export function oversizeCellText(over) { // value costs a full detoast of it. The cell says what is there and how big; // the dock loads it when someone opens it. if (!over.preview) return `${formatByteSize(over.bytes)} ${over.dataType || 'value'}` - const head = over.preview.length > 200 ? over.preview.slice(0, 200) + '…' : over.preview - return `[${over.dataType || 'value'} · ${formatByteSize(over.bytes)}, truncated] ${head}` + // The value first: a grid cell shows about forty characters, and with the + // label in front all of them said "[jsonb · 15 KB, truncated]". The size + // follows (and the cell's Load button says the rest is not here). + const head = over.preview.length > 200 ? over.preview.slice(0, 200) : over.preview + return `${head}… (${formatByteSize(over.bytes)} ${over.dataType || 'value'})` } /** @@ -175,6 +178,19 @@ export function isBooleanType(dataType) { return t === 'boolean' || t === 'bool' } +/** + * A boolean column's value as `true`/`false`. SQLite, libSQL and D1 store a + * boolean as 0 or 1; shown raw it reads as a number, and a true/false picker + * given "0" matches none of its options. Anything else comes back unchanged. + * @param {unknown} value + * @returns {unknown} + */ +export function asBooleanValue(value) { + if (value === 0 || value === '0') return false + if (value === 1 || value === '1') return true + return value +} + /** * @param {string} dataType */ diff --git a/src/lib/cell-value.test.js b/src/lib/cell-value.test.js index c2622d69..e1f88422 100644 --- a/src/lib/cell-value.test.js +++ b/src/lib/cell-value.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { formatTimestampForDb, parseCellInput } from "./cell-value.js"; +import { asBooleanValue, formatTimestampForDb, parseCellInput } from "./cell-value.js"; describe("formatTimestampForDb", () => { it("keeps the instant when the value carries an explicit zone", () => { @@ -80,3 +80,18 @@ describe("parseCellInput — timestamps", () => { expect(parseCellInput("NULL", "timestamptz")).toEqual({ ok: true, value: null }); }); }); + +describe('asBooleanValue', () => { + it('reads 0/1 stored booleans as false/true', () => { + expect(asBooleanValue(0)).toBe(false) + expect(asBooleanValue(1)).toBe(true) + expect(asBooleanValue('0')).toBe(false) + expect(asBooleanValue('1')).toBe(true) + }) + it('leaves real booleans, NULL and other values alone', () => { + expect(asBooleanValue(true)).toBe(true) + expect(asBooleanValue(null)).toBe(null) + expect(asBooleanValue(2)).toBe(2) + expect(asBooleanValue('yes')).toBe('yes') + }) +}) diff --git a/src/lib/changelog.js b/src/lib/changelog.js index 191ab96d..6caea024 100644 --- a/src/lib/changelog.js +++ b/src/lib/changelog.js @@ -123,14 +123,15 @@ export function parseReleases(markdown) { /** * The releases someone skipped over by updating from `previous` to `current`: * every version in (previous, current], newest first, up to `limit` of them. - * `omitted` counts the older ones left out. + * `omitted` counts the older ones left out; `versions` counts them all. * @param {string} markdown CHANGELOG.md * @param {string} previous @param {string} current * @param {number} [limit] - * @returns {{ releases: ChangelogRelease[], omitted: number }} + * @param {{ merge?: boolean }} [opts] see releasesInRange + * @returns {{ releases: ChangelogRelease[], omitted: number, versions: number }} */ -export function releasesBetween(markdown, previous, current, limit = 5) { - return releasesInRange(parseReleases(markdown), previous, current, limit) +export function releasesBetween(markdown, previous, current, limit = 5, opts = {}) { + return releasesInRange(parseReleases(markdown), previous, current, limit, opts) } /** @@ -146,20 +147,64 @@ export function changelogVersion(v) { /** * Releases in (previous, current], newest first, up to `limit`. + * + * With `merge`, a range longer than `limit` comes back as ONE release holding + * every change in it instead of the newest `limit` versions. An update from + * stable 3.0.0 to 3.7.5 spans 66 versions: the newest 8 were 21 small fixes, + * and the features people were getting (shared studios, new engines, + * languages) sat behind "And 58 earlier releases in the full changelog". * @param {ChangelogRelease[]} all * @param {string} previous @param {string} current * @param {number} [limit] - * @returns {{ releases: ChangelogRelease[], omitted: number }} + * @param {{ merge?: boolean }} [opts] + * @returns {{ releases: ChangelogRelease[], omitted: number, versions: number }} */ -export function releasesInRange(all, previous, current, limit = 5) { +export function releasesInRange(all, previous, current, limit = 5, { merge = false } = {}) { const from = changelogVersion(previous) const to = changelogVersion(current) - if (!(compareVersions(to, from) > 0)) return { releases: [], omitted: 0 } + if (!(compareVersions(to, from) > 0)) return { releases: [], omitted: 0, versions: 0 } const inRange = all .filter((r) => r.sections.length > 0) .filter((r) => compareVersions(r.version, from) > 0 && compareVersions(r.version, to) <= 0) .sort((a, b) => compareVersions(b.version, a.version)) - return { releases: inRange.slice(0, limit), omitted: Math.max(0, inRange.length - limit) } + if (merge && inRange.length > limit) return { releases: [mergeReleases(inRange)], omitted: 0, versions: inRange.length } + return { releases: inRange.slice(0, limit), omitted: Math.max(0, inRange.length - limit), versions: inRange.length } +} + +/** Order of the merged sections by kind: what's new first. */ +const KIND_ORDER = /** @type {ChangeType[]} */ (['feature', 'fix', 'change', 'other']) + +/** + * Several releases as one, named for the newest: every section's items under + * one section per kind (New, Fixed, Improved), and one per sub-section + * (#### Performance) within its kind, newest items first. + * @param {ChangelogRelease[]} releases newest first + * @returns {ChangelogRelease} + */ +export function mergeReleases(releases) { + /** @type {Map} */ + const byKey = new Map() + for (const r of releases) { + for (const s of r.sections) { + const sub = s.title !== s.group + // Top-level sections merge by kind ("Bug Fixes" and "Fixes" are both + // Fixed); a sub-section by its kind and its own title. + const key = sub ? `${s.type}\u0000${s.title}` : s.type + let m = byKey.get(key) + if (!m) { + m = sub ? { title: s.title, group: `${s.type}`, type: s.type, items: [] } : { title: s.type, group: s.type, type: s.type, items: [] } + byKey.set(key, m) + } + m.items.push(...s.items) + } + } + const sections = [...byKey.values()].sort((a, b) => { + const k = KIND_ORDER.indexOf(a.type) - KIND_ORDER.indexOf(b.type) + if (k) return k + // Within a kind, its own items before its sub-sections. + return Number(a.title !== a.group) - Number(b.title !== b.group) + }) + return { version: releases[0]?.version ?? '', date: releases[0]?.date ?? '', sections } } /** @@ -181,3 +226,38 @@ export function splitInlineCode(text) { if (last < text.length) parts.push({ text: text.slice(last), code: false }) return parts } + +/** + * A changelog line as code, bold and plain runs. Every entry opens with a + * `**Title**`; without this the release-notes windows printed the asterisks. + * Bold is not looked for inside code. An unclosed `**` stays literal. + * @param {string} text + * @returns {{ text: string, code: boolean, bold: boolean }[]} + */ +export function splitInlineMarks(text) { + return splitInlineCode(String(text)).flatMap((p) => { + if (p.code) return [{ ...p, bold: false }] + return p.text + .split(/(\*\*[^*]+\*\*)/g) + .filter(Boolean) + .map((s) => (/^\*\*[^*]+\*\*$/.test(s) ? { text: s.slice(2, -2), code: false, bold: true } : { text: s, code: false, bold: false })) + }) +} + +/** + * A changelog entry as its title and the text after it. Entries read + * `**Title** - text`; the update feed strips the asterisks (an older app + * printed them), so a plain `Title - text` with a short title counts too. + * No title: the whole entry is the text. + * @param {string} text + * @returns {{ title: string, body: string }} + */ +export function splitEntry(text) { + const s = String(text ?? '').trim() + const bold = /^\*\*([^*]+)\*\*\s*(?:-|:)\s*([\s\S]*)$/.exec(s) + if (bold) return { title: bold[1].trim(), body: bold[2].trim() } + // A title is a short phrase, not a sentence: no full stop before the dash. + const plain = /^([^.!?\n`]{2,60}?) - ([\s\S]+)$/.exec(s) + if (plain) return { title: plain[1].trim(), body: plain[2].trim() } + return { title: '', body: s } +} diff --git a/src/lib/changelog.test.js b/src/lib/changelog.test.js index 6f9d079f..c26a220d 100644 --- a/src/lib/changelog.test.js +++ b/src/lib/changelog.test.js @@ -4,7 +4,10 @@ import { parseChangelog, parseReleases, releasesBetween, + mergeReleases, splitInlineCode, + splitInlineMarks, + splitEntry, } from './changelog.js' const CHANGELOG = `# Changelog @@ -112,6 +115,40 @@ describe('releasesBetween', () => { }) }) +describe('releasesBetween with merge', () => { + it('keeps one block per version while the range fits the limit', () => { + const { releases, versions } = releasesBetween(CHANGELOG, '2.2.4', '2.3.0', 8, { merge: true }) + expect(releases.map((r) => r.version)).toEqual(['2.3.0', '2.2.5']) + expect(versions).toBe(2) + }) + + it('merges a range longer than the limit into one release, nothing left out', () => { + const { releases, omitted, versions } = releasesBetween(CHANGELOG, '2.0.0', '2.3.0', 2, { merge: true }) + expect(omitted).toBe(0) + expect(versions).toBe(4) + expect(releases).toHaveLength(1) + expect(releases[0].version).toBe('2.3.0') + expect(releases[0].sections.map((s) => [s.title, s.type, s.items])).toEqual([ + ['Sidebar', 'feature', ['Objects tab', 'Sort tables by creation time']], + ['fix', 'fix', ['`Esc` ends an AI reply', 'Shortcuts fire once', 'Older fix']], + ['change', 'change', ['Faster startup']], + ]) + }) +}) + +describe('mergeReleases', () => { + it('puts a kind\'s own items before its sub-sections', () => { + const merged = mergeReleases([ + { version: '3.1.0', date: '', sections: [{ title: 'Performance', group: 'Changes', type: 'change', items: ['Fast'] }] }, + { version: '3.0.1', date: '', sections: [{ title: 'Changes', group: 'Changes', type: 'change', items: ['Plain'] }] }, + ]) + expect(merged.sections.map((s) => [s.title, s.items])).toEqual([ + ['change', ['Plain']], + ['Performance', ['Fast']], + ]) + }) +}) + describe('splitInlineCode', () => { it('marks backtick spans as code', () => { expect(splitInlineCode('Press `Esc` to stop')).toEqual([ @@ -125,3 +162,31 @@ describe('splitInlineCode', () => { expect(splitInlineCode('a ` b')).toEqual([{ text: 'a ` b', code: false }]) }) }) + +describe('splitInlineMarks', () => { + it('splits a bold title, code and plain text', () => { + expect(splitInlineMarks('**Notebook** - inside `\'{{name}}\'` now')).toEqual([ + { text: 'Notebook', code: false, bold: true }, + { text: ' - inside ', code: false, bold: false }, + { text: "'{{name}}'", code: true, bold: false }, + { text: ' now', code: false, bold: false }, + ]) + }) + it('leaves an unclosed ** and ** inside code alone', () => { + expect(splitInlineMarks('a ** b')).toEqual([{ text: 'a ** b', code: false, bold: false }]) + expect(splitInlineMarks('`**x**`')).toEqual([{ text: '**x**', code: true, bold: false }]) + }) +}) + +describe('splitEntry', () => { + it('reads a bold title', () => { + expect(splitEntry('**Redis sidebar** - Says "1 client".')).toEqual({ title: 'Redis sidebar', body: 'Says "1 client".' }) + }) + it('reads a plain title, as the update feed sends it', () => { + expect(splitEntry('Redis sidebar - Says "1 client".')).toEqual({ title: 'Redis sidebar', body: 'Says "1 client".' }) + }) + it('leaves a sentence with a dash in it whole', () => { + expect(splitEntry('Fixed the grid. It no longer jumps - at all.')).toEqual({ title: '', body: 'Fixed the grid. It no longer jumps - at all.' }) + expect(splitEntry('Materialized views in the sidebar (#363)')).toEqual({ title: '', body: 'Materialized views in the sidebar (#363)' }) + }) +}) diff --git a/src/lib/chart-utils.js b/src/lib/chart-utils.js index 660302c9..3567c3eb 100644 --- a/src/lib/chart-utils.js +++ b/src/lib/chart-utils.js @@ -1492,7 +1492,9 @@ export function buildOption({ type, columns, rows, xCol, yCol, zCol, groupCol, i xAxis: categoryXAxis(isDark, xData), yAxis: valueYAxis(isDark), series, - ...(needsZoom ? { grid: { ...base.grid, bottom: 44 } } : {}), + // Labels above the bars need room: the tallest bar reaches the axis max, + // and its label sat above the plot, cut off at the top edge. + grid: { ...base.grid, ...(series[0]?.label?.show ? { top: titleOpt(title ?? '').title ? 44 : 28 } : {}), ...(needsZoom ? { bottom: 44 } : {}) }, ...(needsZoom ? { dataZoom } : {}), ...titleOpt(title ?? ''), } diff --git a/src/lib/cm-sql-complete.js b/src/lib/cm-sql-complete.js index 2487dbd9..7c8e5189 100644 --- a/src/lib/cm-sql-complete.js +++ b/src/lib/cm-sql-complete.js @@ -27,6 +27,7 @@ import { import { EditorSelection } from '@codemirror/state' import { isStatementSnippet, snippetEndsStatement } from './sql-terminator.js' import { statementAt } from '$lib/cm-sql-statements.js' +import { currentSnippets, snippetsFor } from '$lib/stores/sql-snippets.js' import { sqlCompletionContext } from '$lib/sql-complete-context.js' import { PG_KEYWORDS, DDL_KEYWORDS, DIALECT_KEYWORDS, PG_FUNCTIONS, PG_FUNCTION_FAMILIES, DIALECT_FUNCTIONS, @@ -230,6 +231,33 @@ function staticTemplates(family) { return built } +/** + * Your own snippets (Settings > Snippets) for a family, as completions. + * Rebuilt only when the list changes: it is a new array on every edit. + * @type {WeakMap>>} + */ +const userSnippetCache = new WeakMap() +/** @param {string} family */ +function userSnippetOptions(family) { + const list = currentSnippets() + let byFamily = userSnippetCache.get(list) + if (!byFamily) { byFamily = new Map(); userSnippetCache.set(list, byFamily) } + let out = byFamily.get(family) + if (!out) { + out = snippetsFor(list, family).map((s) => { + // The `;` that closes a statement snippet is added on accept; one typed + // into the body as well would write two. + const body = s.body.replace(/;\s*$/, '') + return { + ...statementSnippet(body, { label: s.name, type: 'snippet', detail: s.trigger, info: snippetPreview(body) }), + aliases: [s.trigger], + } + }) + byFamily.set(family, out) + } + return out +} + /** Capitals typed (`VARC`, `I`): write the type in capitals too. @param {string} prefix */ const typedInCapitals = (prefix) => /[A-Z]/.test(prefix) && prefix === prefix.toUpperCase() @@ -500,9 +528,11 @@ function buildCandidates(ctx, H, S, dialect, statement, rowTable) { for (const e of H.enums) add(e, TIER[6]) for (const t of H.tables) tableOption(t, 7) for (const s of H.schemas) schemaOption(s, 8) - if (typed) for (const s of S.snippets) add(s, TIER[6], s.aliases) + if (typed) for (const s of [...userSnippetOptions(family), ...S.snippets]) add(s, TIER[6], s.aliases) } else { - // Start of a statement. + // Start of a statement. Yours first: a trigger of your own beats a + // built-in one with the same word. + for (const s of userSnippetOptions(family)) add(s, TIER[0], s.aliases) for (const s of S.snippets) add(s, TIER[0], s.aliases) keywords(1, null) } diff --git a/src/lib/cm-sql-dialects.js b/src/lib/cm-sql-dialects.js index 5f236d1c..b50b8eda 100644 --- a/src/lib/cm-sql-dialects.js +++ b/src/lib/cm-sql-dialects.js @@ -27,6 +27,8 @@ const SQL_DIALECTS = /** @type {Record} */ ({ sqlite: LITE, d1: LITE, libsql: LITE, mssql: narrowed(MSSQL), oracle: narrowed(PLSQL), + spanner: MY, + bigquery: MY, }) /** The highlighting dialect for an app Dialect id. @param {string} id */ diff --git a/src/lib/cm-step-over-paren.js b/src/lib/cm-step-over-paren.js new file mode 100644 index 00000000..efadb9c1 --- /dev/null +++ b/src/lib/cm-step-over-paren.js @@ -0,0 +1,40 @@ +/** + * Typing `)` right before a `)` steps over it when the line's parentheses are + * already balanced. + * + * A function completion is a snippet, `st_astext(${})`, and CodeMirror only + * steps over the brackets its own closeBrackets inserted: finishing the call + * by typing `geom)` left `st_astext(geom))`, an extra `)` that broke the + * statement. Balance is the test so a nested call still gets the `)` it + * needs: in `f(g(x|)` the line is one short and the typed `)` is inserted. + */ +import { EditorView } from '@codemirror/view' + +/** + * Whether a `)` typed at `pos` in `line` should step over the `)` already there. + * Parentheses inside '...' and "..." are not counted. + * @param {string} line @param {number} pos offset into `line` + */ +export function stepsOverParen(line, pos) { + if (line[pos] !== ')') return false + let depth = 0 + /** @type {string | null} */ + let quote = null + for (let i = 0; i < line.length; i++) { + const ch = line[i] + if (quote) { if (ch === quote) quote = null; continue } + if (ch === "'" || ch === '"') { quote = ch; continue } + if (ch === '(') depth++ + else if (ch === ')') depth-- + } + return depth <= 0 +} + +/** The CodeMirror side: an input handler for `)`. */ +export const stepOverParen = EditorView.inputHandler.of((view, from, to, text) => { + if (text !== ')' || from !== to) return false + const line = view.state.doc.lineAt(from) + if (!stepsOverParen(line.text, from - line.from)) return false + view.dispatch({ selection: { anchor: from + 1 }, scrollIntoView: true, userEvent: 'input.type' }) + return true +}) diff --git a/src/lib/cm-step-over-paren.test.js b/src/lib/cm-step-over-paren.test.js new file mode 100644 index 00000000..eb61658c --- /dev/null +++ b/src/lib/cm-step-over-paren.test.js @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest' +import { stepsOverParen } from './cm-step-over-paren.js' + +describe('stepsOverParen', () => { + it('steps over the closing paren of a completed call', () => { + const line = 'select st_astext(geom) from pings' + expect(stepsOverParen(line, line.indexOf(')'))).toBe(true) + }) + it('inserts when a nested call still needs its own', () => { + const line = 'select f(g(x)' + expect(stepsOverParen(line, line.length - 1)).toBe(false) + }) + it('ignores parens in strings and needs a ) at the caret', () => { + expect(stepsOverParen("select f(')') ", 12)).toBe(true) + expect(stepsOverParen("select f('(')", 12)).toBe(true) + expect(stepsOverParen('select f(x', 10)).toBe(false) + }) +}) diff --git a/src/lib/components/AccountCard.svelte b/src/lib/components/AccountCard.svelte index c4f65373..d9109088 100644 --- a/src/lib/components/AccountCard.svelte +++ b/src/lib/components/AccountCard.svelte @@ -60,7 +60,7 @@ {@render planPill()}

- {#if user?.name}{user.email} · {/if}{devices} {devices === 1 ? 'device' : 'devices'}{#if $account?.offline} · offline{/if} + {#if user?.name}{user.email} · {/if}{devices} {devices === 1 ? 'device' : 'devices'}{#if $account?.offline}{' '}· offline{/if}

diff --git a/src/lib/components/AddThemeDialog.svelte b/src/lib/components/AddThemeDialog.svelte index 1c921e2f..007c56f4 100644 --- a/src/lib/components/AddThemeDialog.svelte +++ b/src/lib/components/AddThemeDialog.svelte @@ -8,7 +8,7 @@ import { Button } from '$lib/components/ui/button/index.js' import Icon from './Icon.svelte' import SearchField from './SearchField.svelte' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' import { parseThemeFile } from '$lib/themes/theme-file.js' import { addImportedTheme } from '$lib/stores/imported-themes.js' import { updateSettings } from '$lib/stores/settings.js' @@ -160,7 +160,7 @@ bind:value={json} spellcheck="false" placeholder={'{\n "version": 1,\n "name": "Aurora",\n "appearance": "dark",\n "colors": { "background": "#0f1117", "foreground": "#e6e6e6", "primary": "#7aa2f7" }\n}'} - class="field-surface app-scroll h-36 w-full resize-none bg-transparent p-3 font-mono text-ui-xs text-foreground placeholder:text-muted-foreground/70" + class="field-surface app-scroll h-36 w-full resize-none bg-transparent p-3 font-mono text-ui-xs text-foreground placeholder:text-muted-foreground" > {#if pasted?.error}

{pasted.error}

@@ -175,7 +175,7 @@ - diff --git a/src/lib/components/AdvisorPage.svelte b/src/lib/components/AdvisorPage.svelte index 117b0a49..58f2111b 100644 --- a/src/lib/components/AdvisorPage.svelte +++ b/src/lib/components/AdvisorPage.svelte @@ -283,7 +283,7 @@ bind:value={query} placeholder="Filter by table, check…" aria-label="Filter findings" - class="field-surface h-7 w-52 bg-background pl-7 pr-2 text-ui-xs text-foreground placeholder:text-muted-foreground focus:border-primary/40 focus:outline-none" + class="search-box no-field-frame h-7 w-52 pl-7 pr-2 text-ui-xs" /> diff --git a/src/lib/components/AiChartRenderer.svelte b/src/lib/components/AiChartRenderer.svelte index 5f40b3ad..36a8cfa7 100644 --- a/src/lib/components/AiChartRenderer.svelte +++ b/src/lib/components/AiChartRenderer.svelte @@ -1,4 +1,5 @@ @@ -274,180 +275,136 @@ {#if hasEffort}{effortLabel}{/if} - -
- -
- - - {#each groups as g (g.key)} - - {/each} -
- -
- + + -
- {#if blockedAgent} -
-

- {blockedAgent.name} {blockedAgent.status === 'missing' ? 'is not installed' : 'needs you to sign in'} -

- {#if blockedAgent.setup} - -

{copied ? 'Copied. Run it in a terminal, then reopen this menu.' : 'Run this in a terminal, then reopen this menu.'}

- {:else if blockedAgent.hint} -

{blockedAgent.hint}

+
+ {#if flat.length === 0 && !sections.some((s) => s.agent && s.agent.status !== 'ready')} +

+ {query.trim() ? 'No model matches.' : 'No models yet. Add one in Manage models.'} +

+ {/if} + {#each sections as sec (sec.key)} + {#if sec.label} +
+ {#if sec.key === 'fav'} + + {:else} + {@render mark(sec.brand, 'size-3 shrink-0')} + {/if} + {sec.label} + {#if sec.agent && sec.agent.status !== 'ready'} + {@const agent = sec.agent} + {agent.status === 'missing' ? 'Not installed' : 'Sign in first'} + {#if agent.setup} + + {/if} {/if}
- {:else if visible.length === 0} -

- {query.trim() ? 'No model matches.' : railKey === 'fav' ? 'Star a model to keep it here.' : 'No models.'} -

- {:else} - {#each visible as e, i (e.key)} -
(highlight = i)} - onclick={() => choose(e)} - onkeydown={(ev) => ev.key === 'Enter' && choose(e)} - > + {/if} + {#each sec.rows as e (sec.key + e.key)} + {@const i = flat.indexOf(e, sections.slice(0, sections.indexOf(sec)).reduce((n, x) => n + x.rows.length, 0))} +
(highlight = i)} + onclick={() => choose(e)} + onkeydown={(ev) => ev.key === 'Enter' && choose(e)} + > + {#if query.trim() || sec.key === 'fav'} {@render mark(e.brand, 'size-3.5 shrink-0 text-muted-foreground')} - {e.label} - {#if e.active}{/if} - - - {#if i < 4} - {modKey}{i + 1} - {/if} -
- {/each} - {#if hiddenCount > 0} + {/if} + {e.label} + {#if (e.tag || e.note) && !e.label.toLowerCase().includes((e.tag || e.note).toLowerCase())} + {e.tag || e.note} + {/if} + - {/if} +
+ {/each} + {#if sec.more > 0} + {/if} -
+ {/each}
{#if hasEffort} - -
-
- Reasoning · {displayName} -
-
+ +
+ Reasoning +
{#each EFFORTS as ef (ef.id)} {@const on = $agentPrefs.effort === ef.id} + >{EFFORT_SHORT[ef.id] ?? ef.label} {/each}
{/if} -
{#if accessLabel} diff --git a/src/lib/components/AiSettingsDialog.svelte b/src/lib/components/AiSettingsDialog.svelte index 6381ca72..af9116e1 100644 --- a/src/lib/components/AiSettingsDialog.svelte +++ b/src/lib/components/AiSettingsDialog.svelte @@ -1028,7 +1028,7 @@ placeholder="sk-…" bind:value={formApiKey} /> - {/if} {#if editingId} - -
@@ -1307,7 +1307,7 @@ > {#if running}{/if} {running ? 'Working' : `Worked for ${formatElapsed((item.endedAt ?? item.startedAt) - item.startedAt)}`} - {#if summary}· {summary}{/if} + {#if summary}· {summary}{/if} {#if failed}· {failed} failed{/if} diff --git a/src/lib/components/AppLockGate.svelte b/src/lib/components/AppLockGate.svelte index 2ea5426b..35eb3ae6 100644 --- a/src/lib/components/AppLockGate.svelte +++ b/src/lib/components/AppLockGate.svelte @@ -49,6 +49,7 @@ // and says locked, the screen still comes up - just a beat later. const giveUp = setTimeout(() => (ready = true), 1500) initAppLock().finally(() => { + performance.mark('stroke:lock-ready') clearTimeout(giveUp) ready = true teardown = installAutoLock() diff --git a/src/lib/components/AppLockScreen.svelte b/src/lib/components/AppLockScreen.svelte index f65aa3c7..d27c2c3b 100644 --- a/src/lib/components/AppLockScreen.svelte +++ b/src/lib/components/AppLockScreen.svelte @@ -65,7 +65,7 @@ ondblclick={onDragRegionDblClick} > {#if isMac} -
+
{/if}
@@ -79,7 +79,7 @@ >
-
+
diff --git a/src/lib/components/AppMenuBar.svelte b/src/lib/components/AppMenuBar.svelte index 7b273d78..f40d031f 100644 --- a/src/lib/components/AppMenuBar.svelte +++ b/src/lib/components/AppMenuBar.svelte @@ -1,4 +1,5 @@ {#snippet logToggle()} @@ -607,7 +629,7 @@ > {#each logLines as line (line.id)}
- {logTime(line.at)} + {logTime(line.at)} {:else} - + {/if} {/snippet} @@ -655,7 +677,7 @@

{title}

-

{body}

+

{body}

{/snippet} @@ -685,7 +707,7 @@
- + diff --git a/src/lib/components/ErdCanvas.svelte b/src/lib/components/ErdCanvas.svelte index 2d7f2416..d467f332 100644 --- a/src/lib/components/ErdCanvas.svelte +++ b/src/lib/components/ErdCanvas.svelte @@ -1078,7 +1078,7 @@ nameW -= bw + 8 } if (zoom >= LOD_ROWS) { - drawTableGlyph(p.x + 16, p.y + HDR_H / 2 - 6, c('mfg', 0.7)) + drawTableGlyph(p.x + 16, p.y + HDR_H / 2 - 6, c('mfg', 0.7), !!d.view) forgetStyle() setFont(`600 14.5px ${FONT_SANS}`) setFill(c('fg', 1)) @@ -1089,7 +1089,8 @@ setFont(FONT_TYPE) setFill(c('mfg', 0.55)) ctx.textAlign = 'right' - ctx.fillText(String((d.columns?.length ?? 0) + (d.hiddenCount ?? 0)), p.x + NODE_W - 16, p.y + HDR_H / 2 + 0.5) + // A view says so where the column count would be. + ctx.fillText(d.matView ? 'mat. view' : d.view ? 'view' : String((d.columns?.length ?? 0) + (d.hiddenCount ?? 0)), p.x + NODE_W - 16, p.y + HDR_H / 2 + 0.5) } } } @@ -1137,6 +1138,10 @@ // from the type, which then cut off at numeric(1… and timestamp…. if (isPk) drawKeyGlyph(p.x + 21, midY, PK_INK, zoom) else if (isFk) drawLinkGlyph(p.x + 21, midY, FK_INK) + // A key column that is also a foreign key (order_items.order_id in a + // composite key) showed only the key, and the reference it holds was + // invisible on the row. A small link sits on the key's corner. + if (isPk && isFk) drawLinkBadge(p.x + 26, midY + 4, FK_INK) forgetStyle() // A key into a hub names the hub (that relationship has no line). let refW = 0 @@ -1222,11 +1227,28 @@ ctx.restore() } + /** The link glyph at a third of its size on a card-coloured disc, for a key + * column that is also a foreign key. */ + function drawLinkBadge(/** @type {number} */ cx, /** @type {number} */ cy, /** @type {string} */ color) { + ctx.save() + ctx.fillStyle = c('card', 1) + ctx.beginPath() + ctx.arc(cx, cy, 4.2, 0, Math.PI * 2) + ctx.fill() + ctx.translate(cx, cy) + ctx.scale(0.62, 0.62) + ctx.translate(-cx, -cy) + drawLinkGlyph(cx, cy, color) + ctx.restore() + } + /** A small table glyph for the card header. */ - function drawTableGlyph(/** @type {number} */ x, /** @type {number} */ y, /** @type {string} */ color) { + /** A table, or with `view` a dashed one: the usual ER mark for a view. */ + function drawTableGlyph(/** @type {number} */ x, /** @type {number} */ y, /** @type {string} */ color, view = false) { ctx.save() ctx.strokeStyle = color ctx.lineWidth = 1.4 + if (view) ctx.setLineDash([2.5, 1.5]) roundRect(x, y, 13, 12, 2.5) ctx.stroke() ctx.beginPath() diff --git a/src/lib/components/ErdHierarchy.svelte b/src/lib/components/ErdHierarchy.svelte index d00a395e..3fe26dd5 100644 --- a/src/lib/components/ErdHierarchy.svelte +++ b/src/lib/components/ErdHierarchy.svelte @@ -509,7 +509,7 @@ {t.name} - {colCount.get(t.name) ?? 0} {plural(colCount.get(t.name) ?? 0, 'col')}{#if n !== undefined} · {formatTableRowCount(n)} {plural(n, 'row')}{/if} + {colCount.get(t.name) ?? 0} {plural(colCount.get(t.name) ?? 0, 'col')}{#if n !== undefined}{' '}· {formatTableRowCount(n)} {plural(n, 'row')}{/if} {#if downN} used by {downN} {/if} @@ -524,7 +524,7 @@ {#if refs} ← {refs} {/if} diff --git a/src/lib/components/ExplainPlan.svelte b/src/lib/components/ExplainPlan.svelte index 817681d9..6e133eb3 100644 --- a/src/lib/components/ExplainPlan.svelte +++ b/src/lib/components/ExplainPlan.svelte @@ -11,10 +11,12 @@ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js' import { normalizePlan, annotatePlan, planInsights, describeNode, CONDITION_KEYS, conditionText, fmtMs, fmtCount, planText, + planOutline, foldLabel, } from '$lib/explain-plan.js' /** @typedef {{ plan: object, planningTime: number, executionTime: number, driver: string }} ExplainResult */ /** @typedef {import('$lib/explain-plan.js').PlanNode} PlanNode */ + /** @typedef {import('$lib/explain-plan.js').PlanFold} PlanFold */ /** * @type {{ @@ -70,20 +72,37 @@ } const ROW_H = $derived(Math.max(...a.nodes.map(cardH), 60) + ROW_GAP) - /** @typedef {{ n: PlanNode, col: number, row: number }} Placed */ + // Wide steps (an Append over hundreds of partitions) draw the children that + // ran and fold the rest into one card; `expanded` holds the ones opened. + let expanded = $state(/** @type {Set} */ (new Set())) + $effect(() => { void plan; untrack(() => { expanded = new Set() }) }) + const outline = $derived(planOutline(a.root, expanded)) + /** @param {string} parentId */ + function toggleFold(parentId) { + const next = new Set(expanded) + if (next.has(parentId)) next.delete(parentId) + else next.add(parentId) + expanded = next + } + const FOLD_H = 32 + + /** @typedef {{ id: string, parentId: string | null, n: PlanNode | null, fold: PlanFold | null, col: number, row: number }} Placed */ const layout = $derived.by(() => { /** @type {Map} */ const at = new Map() let leaf = 0 - /** @param {PlanNode} n @returns {Placed} */ - const lay = (n) => { - if (!n.children.length) { - const p = { n, col: 0, row: leaf++ } - at.set(n.id, p) + /** @param {PlanNode | PlanFold} item @returns {Placed} */ + const lay = (item) => { + if ('kind' in item && item.kind === 'fold') { + const p = { id: item.id, parentId: item.parentId, n: null, fold: item, col: 0, row: leaf++ } + at.set(p.id, p) return p } - const kids = n.children.map(lay) - const p = { n, col: Math.max(...kids.map((k) => k.col)) + 1, row: (Math.min(...kids.map((k) => k.row)) + Math.max(...kids.map((k) => k.row))) / 2 } + const n = /** @type {PlanNode} */ (item) + const kids = (outline.childrenOf.get(n.id) ?? []).map(lay) + const p = kids.length + ? { id: n.id, parentId: n.parentId, n, fold: null, col: Math.max(...kids.map((k) => k.col)) + 1, row: (Math.min(...kids.map((k) => k.row)) + Math.max(...kids.map((k) => k.row))) / 2 } + : { id: n.id, parentId: n.parentId, n, fold: null, col: 0, row: leaf++ } at.set(n.id, p) return p } @@ -91,11 +110,13 @@ return at }) const placed = $derived([...layout.values()]) + const placedNodes = $derived(placed.filter((p) => p.n)) + const placedFolds = $derived(placed.filter((p) => p.fold)) const maxCol = $derived(placed.reduce((m, p) => Math.max(m, p.col), 0)) const maxRow = $derived(placed.reduce((m, p) => Math.max(m, p.row), 0)) const px = (/** @type {Placed} */ p) => PAD + p.col * (NODE_W + COL_GAP) const py = (/** @type {Placed} */ p) => PAD + p.row * ROW_H - const cy = (/** @type {Placed} */ p) => py(p) + cardH(p.n) / 2 + const cy = (/** @type {Placed} */ p) => py(p) + (p.n ? cardH(p.n) : FOLD_H) / 2 const qrX = $derived(PAD + (maxCol + 1) * (NODE_W + COL_GAP)) const canvasW = $derived(qrX + QR_W + PAD) const canvasH = $derived(PAD * 2 + (maxRow + 1) * ROW_H) @@ -104,7 +125,7 @@ const r = n.actualRows ?? n.planRows ?? 1 return Math.min(6, 1.25 + Math.log10(Math.max(1, r)) * 0.8) } - const edges = $derived(placed.filter((p) => p.n.parentId).map((p) => ({ from: p, to: /** @type {Placed} */ (layout.get(/** @type {string} */ (p.n.parentId))) }))) + const edges = $derived(placed.filter((p) => p.parentId).map((p) => ({ from: p, to: /** @type {Placed} */ (layout.get(/** @type {string} */ (p.parentId))) }))) /** @param {Placed} f @param {Placed} t */ const edgeD = (f, t) => { const x1 = px(f) + NODE_W, y1 = cy(f), x2 = px(t), y2 = cy(t), mx = (x1 + x2) / 2 @@ -115,15 +136,24 @@ let panX = $state(0) let panY = $state(0) let panning = $state(false) - let start = { x: 0, y: 0, px: 0, py: 0, moved: false } + // State: the grabbing cursor reads `start.moved`, and as a plain object it + // never switched while the plan was dragged. + let start = $state({ x: 0, y: 0, px: 0, py: 0, moved: false }) let cw = $state(0) let ch = $state(0) - function fit() { + /** The smallest first view whose step text still reads. */ + const MIN_FIT = 0.75 + /** @param {boolean} [whole] the Fit button: the whole plan, however small */ + function fit(whole = false) { if (!cw || !ch) return const s = Math.min(1, (cw - 16) / canvasW, (ch - 16) / canvasH) - scale = Math.max(0.2, s) - panX = (cw - canvasW * scale) / 2 + // A plan wider than the pane used to shrink until it fit: four steps in + // the results-beside pane came out at 27%, text a few pixels tall. Below + // the floor, open readable at the leaves (the left, where the plan + // starts) and let the pane pan; zoom out still shows the whole of it. + scale = Math.max(whole ? 0.2 : MIN_FIT, s) + panX = canvasW * scale <= cw ? (cw - canvasW * scale) / 2 : 8 panY = Math.max(8, (ch - canvasH * scale) / 2) } /** @param {number} next @param {number} [ox] @param {number} [oy] */ @@ -138,7 +168,7 @@ const p = plan, w = cw, h = ch, v = view if (!p || !w || !h || v !== 'diagram' || p === fittedFor) return fittedFor = p - untrack(fit) + untrack(() => fit()) }) /** @param {PointerEvent} e */ @@ -239,8 +269,11 @@
-
-
+ +
+
{a.analyzed ? 'Measured' : 'Estimated'} {#if result?.executionTime > 0} @@ -285,7 +318,7 @@ {#if onaskai} {/if}
@@ -302,7 +335,7 @@ {ins.title} {ins.detail} - {#if ins.nodeId}{/if} + {#if ins.nodeId}{/if} {/each} {#if insights.length > 3} @@ -333,9 +366,10 @@
- {#each edges as e (e.from.n.id)} - + {#each edges as e (e.from.id)} + {/each} {#if a.root && layout.get(a.root.id)} {@const r = /** @type {Placed} */ (layout.get(a.root.id))} @@ -343,14 +377,29 @@ {/if} - {#each placed as p (p.n.id)} - {@const n = p.n} + {#each placedFolds as p (p.id)} + {@const f = /** @type {PlanFold} */ (p.fold)} + + {/each} + + {#each placedNodes as p (p.id)} + {@const n = /** @type {PlanNode} */ (p.n)} {@const sel = selectedId === n.id}
@@ -400,7 +449,7 @@
- +
{:else} @@ -416,7 +465,24 @@
- {#each a.nodes as n (n.id)} + {#each outline.entries as entry (entry.kind === 'fold' ? entry.id : entry.node.id)} + {#if entry.kind === 'fold'} + + + + {:else} + {@const n = entry.node} (selectedId = selectedId === n.id ? null : n.id)} @@ -439,6 +505,7 @@ + {/if} {/each}
NameName Values Used by n
+ +
diff --git a/src/lib/components/ExtensionsPage.svelte b/src/lib/components/ExtensionsPage.svelte index a3a768a6..eb2b197f 100644 --- a/src/lib/components/ExtensionsPage.svelte +++ b/src/lib/components/ExtensionsPage.svelte @@ -1,4 +1,5 @@ {#snippet toggle(on, onclick, label)} + {/snippet} @@ -446,7 +434,7 @@ aria-pressed={show === v} class={cn( "inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-ui-xs transition-colors", - show === v ? "bg-background text-foreground shadow-sm ring-1 ring-border/50" : "text-muted-foreground hover:text-foreground", + show === v ? "bg-background text-foreground ring-1 ring-border/50" : "text-muted-foreground hover:text-foreground", )} onclick={() => (show = /** @type {'all' | 'on'} */ (v))} > @@ -485,8 +473,8 @@ {#if $externalPlugins.length === 0}

- No plugins yet. A plugin is a folder with a manifest.json and one script; see - docs/PLUGIN_API.md. + No plugins yet. A plugin is a folder with a manifest.json and one script; see the + .

{#if pluginsDir}
-
+
{#if p.loadable} {@render toggle(on, () => void setExternalEnabled(p.id, !on), `Toggle ${p.name}`)} {:else} @@ -791,7 +779,7 @@ {#if it.country && it.country !== it.label} {it.country} {/if} - {timeZoneOffsetLabel(it.value)} + {timeZoneOffsetLabel(it.value)} {#if it.value === (c.timeZone ?? "local")}{/if} {/snippet} diff --git a/src/lib/components/ExtensionsSidebarPanel.svelte b/src/lib/components/ExtensionsSidebarPanel.svelte index f5ca6af7..af2bd3f9 100644 --- a/src/lib/components/ExtensionsSidebarPanel.svelte +++ b/src/lib/components/ExtensionsSidebarPanel.svelte @@ -1,4 +1,5 @@
- + {column} - {dataType.replace(/\(.*$/, '')}{#if geom} · {geom.type}{/if} + {dataType.replace(/\(.*$/, '')}{#if geom}{' '}· {geom.type}{/if} {#if nullable} nullable diff --git a/src/lib/components/Icon.svelte b/src/lib/components/Icon.svelte index c84b92a5..b24d1674 100644 --- a/src/lib/components/Icon.svelte +++ b/src/lib/components/Icon.svelte @@ -33,7 +33,12 @@ {#if Phosphor} {:else if useHuge} - + + {#key entry.huge} + + {/key} {:else if Lucide} {/if} diff --git a/src/lib/components/ImportDataDialog.svelte b/src/lib/components/ImportDataDialog.svelte index 16bd805d..940f23c9 100644 --- a/src/lib/components/ImportDataDialog.svelte +++ b/src/lib/components/ImportDataDialog.svelte @@ -1,4 +1,5 @@ -
+ +
$ @@ -172,13 +187,23 @@ > {#if copied} - Copied + Copied {:else} - Copy + Copy {/if} + + {#if ondownload}
diff --git a/src/lib/components/JsonViewerPage.svelte b/src/lib/components/JsonViewerPage.svelte index 94a6d118..07499167 100644 --- a/src/lib/components/JsonViewerPage.svelte +++ b/src/lib/components/JsonViewerPage.svelte @@ -8,10 +8,13 @@ import ResizeHandle from './ResizeHandle.svelte' import { loadLayout, saveLayout } from '$lib/stores/layout.js' import Copy from '@lucide/svelte/icons/copy' + import Share2 from '@lucide/svelte/icons/share-2' + import { requestShare } from '$lib/share-flow.js' import CheckCheck from '@lucide/svelte/icons/check-check' import Braces from '@lucide/svelte/icons/braces' import Wand2 from '@lucide/svelte/icons/wand-2' import Trash2 from '@lucide/svelte/icons/trash-2' + import { layoutJsonText } from '$lib/json-layout.js' import { evalJsonPath, getCompletionItems, applyCompletion, describeResult } from '$lib/jsonpath.js' let { active = false } = $props() @@ -154,6 +157,13 @@ }) } + /** Share the query's result when there is one, else the whole document. */ + function handleShare() { + const p = jsonPath.trim() + if (pathResult?.ok) requestShare({ kind: 'json', title: `JSON ${p}`, value: pathResult.value }) + else if (parsedJson !== null) requestShare({ kind: 'json', title: 'JSON', value: parsedJson }) + } + function handleCopyInput() { navigator.clipboard.writeText(rawJson).then(() => { copiedInput = true @@ -184,6 +194,16 @@ /** Typing in the input: the header follows at once, the parse 250ms after it stops. @param {string} val */ function onInput(val) { + // JSON pasted into an empty input as one long line (a cell, an API + // response, a log entry) is laid out at once instead of sitting on one + // line until Format is found. + if (!rawJson.trim() && val.length > 60 && !val.includes('\n')) { + const pretty = layoutJsonText(val) + if (pretty !== null) { + setInput(pretty) + return + } + } rawJson = val // Debounce the expensive parse so it runs at most once per 250ms // instead of on every single keystroke. For a 500kb JSON file this @@ -229,7 +249,7 @@ {#if copiedInput}{:else}{/if} Copy - @@ -300,6 +320,14 @@ Copy result {/if} +
diff --git a/src/lib/components/JsonWrapToggle.svelte b/src/lib/components/JsonWrapToggle.svelte index 4a311507..3c78ad88 100644 --- a/src/lib/components/JsonWrapToggle.svelte +++ b/src/lib/components/JsonWrapToggle.svelte @@ -40,5 +40,5 @@ )} > - {#if !compact}Wrap{/if} + {#if !compact}Wrap{/if} diff --git a/src/lib/components/KeybindingsSettings.svelte b/src/lib/components/KeybindingsSettings.svelte index df609cf7..8d701b23 100644 --- a/src/lib/components/KeybindingsSettings.svelte +++ b/src/lib/components/KeybindingsSettings.svelte @@ -223,7 +223,7 @@ type="search" placeholder="Search by command or key" aria-label="Search keybindings" - class="no-field-frame h-8 w-full rounded-full bg-muted/50 pl-8 pr-3 text-ui-xs text-foreground outline-none placeholder:text-muted-foreground focus:bg-muted/70" + class="search-box no-field-frame h-8 w-full pl-8 pr-3 text-ui-xs" />
{#if overrideCount > 0} diff --git a/src/lib/components/KeyboardShortcutsPage.svelte b/src/lib/components/KeyboardShortcutsPage.svelte index 13ff0e53..e6bd3124 100644 --- a/src/lib/components/KeyboardShortcutsPage.svelte +++ b/src/lib/components/KeyboardShortcutsPage.svelte @@ -20,7 +20,7 @@ import Network from "@lucide/svelte/icons/network"; import X from "@lucide/svelte/icons/x"; - import { SHORTCUT_GROUPS, keycaps, comboText, IS_MAC, rowCommandIds } from "$lib/shortcuts.js"; + import { SHORTCUT_GROUPS, keycaps, comboText, rowCommandIds } from "$lib/shortcuts.js"; import ShortcutRecorder from "./ShortcutRecorder.svelte"; import Kbd from "./Kbd.svelte"; import { keybindings, effectiveShortcutGroups } from "$lib/stores/keybindings.js"; @@ -34,8 +34,6 @@ // Platform flag comes from the index too, so this dialog and the bindings // agree on what machine they are running on. - const isMac = IS_MAC; - const mod = isMac ? "⌘" : "Ctrl"; // The shortcut list lives in $lib/shortcuts.js. It used to be written out here // as per-platform keycap arrays, which meant this dialog could - and did - @@ -159,13 +157,13 @@ {group.label} {group.shortcuts.length} diff --git a/src/lib/components/LauncherScreen.svelte b/src/lib/components/LauncherScreen.svelte new file mode 100644 index 00000000..bacd6cf0 --- /dev/null +++ b/src/lib/components/LauncherScreen.svelte @@ -0,0 +1,166 @@ + + + +
diff --git a/src/lib/components/LicenseGate.svelte b/src/lib/components/LicenseGate.svelte index ffdb8f64..5e2a913c 100644 --- a/src/lib/components/LicenseGate.svelte +++ b/src/lib/components/LicenseGate.svelte @@ -1,7 +1,7 @@
@@ -175,7 +175,7 @@
    {#each features as f (f.label)}
  • - + {f.label}
  • {/each} diff --git a/src/lib/components/LocalServersWindow.svelte b/src/lib/components/LocalServersWindow.svelte index ada88ae7..dd230acf 100644 --- a/src/lib/components/LocalServersWindow.svelte +++ b/src/lib/components/LocalServersWindow.svelte @@ -15,7 +15,7 @@ import DbIcon from './DbIcon.svelte' import { revealApp } from '$lib/app-reveal.js' import { detectOs } from '$lib/platform.js' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' import { ENGINES, engineOf, nextPort, connectionFor, connectionUrl, envName, formatBytes, uptime, localEnv, listServers, createServer, startServer, stopServer, deleteServer, serverLogs, brewServices, brewAction, @@ -98,7 +98,7 @@ if (e.brew) brew = await brewServices().catch(() => []) if (selected && selected !== 'new' && !selected.startsWith('found:') && !s.some((x) => x.id === selected)) selected = s[0]?.id ?? null } catch (e) { - if (!quiet) toast.error('Could not list local servers', { description: String(e) }) + if (!quiet) toast.error('Could not list local servers', { description: errorText(e) }) } finally { loading = false loaded = true @@ -149,7 +149,7 @@ await refresh(true) selected = servers[0]?.id ?? null } catch (e) { - toast.error(`Could not delete ${s.name}`, { description: String(e) }) + toast.error(`Could not delete ${s.name}`, { description: errorText(e) }) } finally { busy = null } @@ -160,7 +160,7 @@ try { await connectIn(from, conn) } catch (e) { - toast.error('Could not open the connection', { description: String(e) }) + toast.error('Could not open the connection', { description: errorText(e) }) } } @@ -219,7 +219,7 @@ await updateServer(s.id, { autostart: on }) await refresh(true) } catch (e) { - toast.error('Could not save that', { description: String(e) }) + toast.error('Could not save that', { description: errorText(e) }) } } @@ -231,7 +231,7 @@ await updateServer(current.id, { name: newName.trim() }) await refresh(true) } catch (e) { - toast.error('Could not rename it', { description: String(e) }) + toast.error('Could not rename it', { description: errorText(e) }) } finally { renaming = false } @@ -365,7 +365,7 @@ brew = await brewServices() void scan() } catch (e) { - toast.error(`Could not ${b.running ? 'stop' : 'start'} ${b.name}`, { description: String(e) }) + toast.error(`Could not ${b.running ? 'stop' : 'start'} ${b.name}`, { description: errorText(e) }) } finally { busy = null } @@ -669,7 +669,7 @@ void editPort()}>Change port… {#if s.runtime === 'native'} - void revealServer(s.id).catch((err) => toast.error('Could not open the folder', { description: String(err) }))}>Show data folder + void revealServer(s.id).catch((err) => toast.error('Could not open the folder', { description: errorText(err) }))}>Show data folder {/if} void remove(s)}>Delete with its data diff --git a/src/lib/components/LogPanel.svelte b/src/lib/components/LogPanel.svelte index 2379a2ca..3371caac 100644 --- a/src/lib/components/LogPanel.svelte +++ b/src/lib/components/LogPanel.svelte @@ -167,7 +167,7 @@ )} title={entry.detail || entry.error || entry.title} > - + {hms(entry.timestamp)} diff --git a/src/lib/components/LogsPage.svelte b/src/lib/components/LogsPage.svelte index fc607354..01096d6f 100644 --- a/src/lib/components/LogsPage.svelte +++ b/src/lib/components/LogsPage.svelte @@ -196,7 +196,7 @@ @@ -220,7 +220,7 @@ class={cn( "inline-flex h-6 items-center rounded-md px-2 font-mono text-ui-2xs transition-colors", typeFilter === f.id - ? "bg-card text-foreground shadow-sm ring-1 ring-border/50" + ? "bg-card text-foreground ring-1 ring-border/50" : "text-muted-foreground hover:text-foreground", )} onclick={() => { @@ -322,7 +322,7 @@ {fmtTime(entry.timestamp)} diff --git a/src/lib/components/MapPage.svelte b/src/lib/components/MapPage.svelte index 3ccc7cca..a5ad2a93 100644 --- a/src/lib/components/MapPage.svelte +++ b/src/lib/components/MapPage.svelte @@ -14,9 +14,10 @@ * recognise gives a cluster nothing to mean. Everything else is left out, so * the only thing competing for attention is the data. */ - import { onMount } from 'svelte' + import { onMount, untrack } from 'svelte' import { geoOverview, geoFeatures } from '$lib/api.js' import { getWorldGeoJson } from '$lib/geo.js' + import { compileGeometry, screenTransform, onScreen, traceRings, hitCompiled, boundsWithin } from '$lib/geo-cache.js' import { FILTER_OPS } from '$lib/table-query.js' import { cn } from '$lib/utils.js' import { @@ -30,8 +31,6 @@ fitExtent, degreesPerPixel, clusterCell, - walkGeometry, - hitTest, } from '$lib/geo-map.js' import Globe from '@lucide/svelte/icons/globe' import Layers from '@lucide/svelte/icons/layers' @@ -52,6 +51,8 @@ */ scopeSchema = '', scopeTable = '', + /** The connection whose layers these are. The page is kept across connections. */ + connectionId = '', } = $props() /** @@ -163,6 +164,23 @@ let frame = 0 /** Bumped on every viewport fetch so a slow one can't overwrite a newer one. */ let fetchSeq = 0 + /** + * The features and the basemap, projected to world units once (geo-cache.js). + * Plain arrays, not state: they change only with `features` and `world`, and + * a frame reads them thousands of times. + * @type {import('$lib/geo-cache.js').Compiled[]} + */ + let compiled = [] + /** @type {import('$lib/geo-cache.js').Compiled[]} */ + let worldCompiled = [] + /** + * What the last viewport fetch covered. When it held every matching row and + * the view has only moved inside it, the next fetch would return the same + * rows, so it is skipped. Zooming in on lines and polygons still refetches + * past 1.5x: their vertices were simplified for the old zoom. + * @type {{ bounds: { minLon: number, minLat: number, maxLon: number, maxLat: number }, scale: number, complete: boolean, key: string } | null} + */ + let lastFetch = null /** * The grid size, in degrees, the server actually clustered by. Kept because a * cluster disc has to be drawn at the size of its own cell, and the view can @@ -234,6 +252,28 @@ // ── Data ──────────────────────────────────────────────────────────────────── + // Layers were read once, on mount: after a switch the map kept the last + // database's layers and features. A new connection starts the list over. + // svelte-ignore state_referenced_locally + let layersFor = connectionId + $effect(() => { + const id = connectionId + if (id === layersFor) return + layersFor = id + untrack(() => { + layers = [] + layer = null + features = [] + compiled = [] + selected = null + lastFetch = null + matched = 0 + error = '' + void loadLayers() + requestDraw() + }) + }) + async function loadLayers() { try { const res = await geoOverview() @@ -254,6 +294,8 @@ layer = next selected = null features = [] + compiled = [] + lastFetch = null matched = 0 // A filter names a column of the old table; carrying it over would either // error or, worse, silently match a same-named column that means something @@ -274,6 +316,12 @@ /** @param {{ fit?: boolean }} [opts] */ async function fetchFeatures(opts = {}) { if (!layer) return + const key = fetchKey() + if (!opts.fit && lastFetch?.complete && lastFetch.key === key && width && height) { + const now = viewBounds(view, width, height) + const pointsOnly = /POINT/i.test(String(layer.geomType ?? '')) + if (boundsWithin(now, lastFetch.bounds) && (pointsOnly || view.scale <= lastFetch.scale * 1.5)) return + } const seq = ++fetchSeq loading = true error = '' @@ -305,6 +353,7 @@ // A viewport moved on while this was in flight - its answer is stale. if (seq !== fetchSeq) return features = res?.features || [] + compiled = features.map((f) => compileGeometry(f?.geometry)) if (res?.mode === 'clusters') clusterCellDeg = cell // The server sends the column list alongside the extent, i.e. once per // layer. Deriving it from a returned feature instead meant a table big @@ -313,6 +362,9 @@ mode = res?.mode || 'features' matched = Number(res?.matched ?? 0) queryMs = Number(res?.queryMs ?? 0) + lastFetch = bounds + ? { bounds, scale: view.scale, complete: res?.mode !== 'clusters' && Number(res?.returned ?? features.length) >= matched, key } + : null if (opts.fit && Array.isArray(res?.extent) && width && height) { view = fitExtent( /** @type {[number, number, number, number]} */ (res.extent), @@ -328,11 +380,18 @@ if (seq !== fetchSeq) return error = err instanceof Error ? err.message : String(err) features = [] + compiled = [] + lastFetch = null } finally { if (seq === fetchSeq) loading = false } } + /** The layer and filters a fetch was for: a cached answer is only good for the same ones. */ + function fetchKey() { + return JSON.stringify([layer?.schema, layer?.table, layer?.column, activeFilters]) + } + function scheduleRefetch() { clearTimeout(refetchTimer) refetchTimer = setTimeout(() => void fetchFeatures(), REFETCH_DELAY) @@ -360,18 +419,16 @@ ctx.setTransform(dpr, 0, 0, dpr, 0, 0) ctx.clearRect(0, 0, width, height) - const project = (/** @type {number} */ x, /** @type {number} */ y) => - toScreen(view, width, height, x, y) - // The bundled vector map is always drawn. Tiles go OVER it rather than // instead of it, so a provider that is slow, blocked, or offline degrades to // the map that ships with the app instead of to a black rectangle - and the // first paint after switching basemaps has something on it while the tiles // are still in flight. + const t = screenTransform(view, width, height) drawGraticule(ctx) - drawWorld(ctx, project) + drawWorld(ctx, t) if (!basemap.offline) drawTiles(ctx) - drawFeatures(ctx, project) + drawFeatures(ctx, t) } /** @param {CanvasRenderingContext2D} ctx */ @@ -470,42 +527,26 @@ /** * @param {CanvasRenderingContext2D} ctx - * @param {(x: number, y: number) => { px: number, py: number }} project + * @param {{ s: number, ox: number, oy: number }} t */ - function drawWorld(ctx, project) { - if (!world) return - // Zoomed into one city, 216 of the 217 countries are off screen. Culling on - // a precomputed bounding box skips their vertices entirely, which is what - // keeps a drag at 60fps instead of re-walking the whole basemap per frame. - const b = viewBounds(view, width, height) + function drawWorld(ctx, t) { + if (!worldCompiled.length) return + // Zoomed into one city, 216 of the 217 countries are off screen; their box + // test is all they cost. ctx.save() // Land is FILLED, not outlined. An outline-only basemap disappears the // moment data is drawn over it, and a map you cannot recognise is not a map // - the continent is the frame that makes a cluster mean something. The tone // comes from the foreground rather than the border token so it holds its - // contrast in either polarity: 10% of near-white on black reads as land, - // and 10% of near-black on white does too. + // contrast in either polarity. ctx.strokeStyle = `rgba(${palette.ink},0.22)` ctx.fillStyle = `rgba(${palette.ink},0.1)` ctx.lineWidth = 1 ctx.lineJoin = 'round' - for (const feature of world.features || []) { - const box = feature.__bbox - if ( - box && - (box[2] < b.minLon || box[0] > b.maxLon || box[3] < b.minLat || box[1] > b.maxLat) - ) { - continue - } + for (const c of worldCompiled) { + if (!onScreen(c, t, width, height, 2)) continue ctx.beginPath() - walkGeometry(feature.geometry, project, { - point() {}, - ring(pts) { - ctx.moveTo(pts[0], pts[1]) - for (let i = 2; i + 1 < pts.length; i += 2) ctx.lineTo(pts[i], pts[i + 1]) - ctx.closePath() - }, - }) + traceRings(ctx, c, t) ctx.fill() ctx.stroke() } @@ -513,28 +554,11 @@ } /** - * Stamp a lon/lat bounding box onto each basemap feature, once, at load. + * Project the basemap once, at load (see geo-cache.js). * @param {any} data */ function indexWorld(data) { - for (const feature of data?.features || []) { - let minLon = Infinity - let minLat = Infinity - let maxLon = -Infinity - let maxLat = -Infinity - const visit = (/** @type {any} */ coords) => { - if (typeof coords[0] === 'number') { - if (coords[0] < minLon) minLon = coords[0] - if (coords[0] > maxLon) maxLon = coords[0] - if (coords[1] < minLat) minLat = coords[1] - if (coords[1] > maxLat) maxLat = coords[1] - return - } - for (const c of coords) visit(c) - } - if (feature?.geometry?.coordinates) visit(feature.geometry.coordinates) - feature.__bbox = [minLon, minLat, maxLon, maxLat] - } + worldCompiled = (data?.features || []).map((/** @type {any} */ f) => compileGeometry(f?.geometry)) return data } @@ -554,10 +578,10 @@ /** * @param {CanvasRenderingContext2D} ctx - * @param {(x: number, y: number) => { px: number, py: number }} project + * @param {{ s: number, ox: number, oy: number }} t */ - function drawFeatures(ctx, project) { - if (!features.length) return + function drawFeatures(ctx, t) { + if (!features.length || compiled.length !== features.length) return const accent = palette.accent // Every mark carries a ring in the page background colour. Over the offline // basemap it is nearly invisible; over satellite imagery it is the only @@ -575,11 +599,12 @@ /** @type {Array<{x: number, y: number, r: number, n: number}>} */ const marks = [] - for (const f of features) { - const n = Number(f?.properties?.count) || 0 - let px = 0 - let py = 0 - walkGeometry(f.geometry, project, { point: (x, y) => ((px = x), (py = y)), ring() {} }) + for (let i = 0; i < features.length; i++) { + const p = compiled[i].points + if (p.length < 2) continue + const n = Number(features[i]?.properties?.count) || 0 + const px = p[0] * t.s + t.ox + const py = p[1] * t.s + t.oy if (px < -60 || px > width + 60 || py < -60 || py > height + 60) continue // Area, not radius, tracks the count - radius alone exaggerates a busy // cell by the square of how busy it is. @@ -623,41 +648,39 @@ // this did - paints every dot at the polygon's alpha and turns the whole // layer into hollow rings. const dotted = features.length > 3000 ? 1.8 : 3 + const isSel = (/** @type {number} */ i) => !!selected && features[i] === selected.feature - /** @param {any} f @param {boolean} pointsOnly */ - const trace = (f, pointsOnly) => { + /** Every point of one shape into the current path, culled to the screen. @param {import('$lib/geo-cache.js').Compiled} c */ + const tracePoints = (c) => { + const p = c.points let drew = false - walkGeometry(f.geometry, project, { - point(px, py) { - if (!pointsOnly) return - if (px < -8 || px > width + 8 || py < -8 || py > height + 8) return - ctx.moveTo(px + dotted, py) - ctx.arc(px, py, dotted, 0, Math.PI * 2) - drew = true - }, - ring(pts, closed) { - if (pointsOnly) return - ctx.moveTo(pts[0], pts[1]) - for (let i = 2; i + 1 < pts.length; i += 2) ctx.lineTo(pts[i], pts[i + 1]) - if (closed) ctx.closePath() - drew = true - }, - }) + for (let j = 0; j < p.length; j += 2) { + const px = p[j] * t.s + t.ox + const py = p[j + 1] * t.s + t.oy + if (px < -8 || px > width + 8 || py < -8 || py > height + 8) continue + ctx.moveTo(px + dotted, py) + ctx.arc(px, py, dotted, 0, Math.PI * 2) + drew = true + } return drew } // Areas and lines, one feature at a time so each polygon's wash is its own // and a hole is subtracted from its own shell rather than a neighbour's. + // Only areas are washed: filling an open line painted a wedge between its ends. ctx.strokeStyle = `rgba(${accent},0.85)` ctx.fillStyle = `rgba(${accent},0.18)` ctx.lineWidth = 1.4 - for (const f of features) { - if (selected && f === selected.feature) continue + for (let i = 0; i < compiled.length; i++) { + const c = compiled[i] + if (!c.rings.length || isSel(i) || !onScreen(c, t, width, height)) continue ctx.beginPath() - if (trace(f, false)) { + if (c.polygons) { + traceRings(ctx, c, t, 'areas') ctx.fill() - ctx.stroke() } + traceRings(ctx, c, t, 'lines') + ctx.stroke() } // Every point in one path: stroke first for a rim in the page colour, then @@ -665,9 +688,10 @@ // against satellite imagery of roughly its own colour. ctx.beginPath() let anyPoint = false - for (const f of features) { - if (selected && f === selected.feature) continue - if (trace(f, true)) anyPoint = true + for (let i = 0; i < compiled.length; i++) { + const c = compiled[i] + if (!c.points.length || isSel(i) || !onScreen(c, t, width, height)) continue + if (tracePoints(c)) anyPoint = true } if (anyPoint) { ctx.strokeStyle = ring @@ -677,14 +701,17 @@ ctx.fill() } - // The selection last, so it is never painted over by a neighbour. - if (selected?.feature) { + // The selection last, so it is never painted over by a neighbour. It keeps + // its own compiled shape: a refetch may have replaced the list it came from. + const sel = selected?.compiled + if (sel) { ctx.beginPath() - const isArea = trace(selected.feature, false) - if (isArea) { + if (sel.polygons) { + traceRings(ctx, sel, t, 'areas') ctx.fillStyle = `rgba(${accent},0.3)` ctx.fill() } + traceRings(ctx, sel, t, 'lines') ctx.strokeStyle = ring ctx.lineWidth = 4 ctx.stroke() @@ -693,7 +720,7 @@ ctx.stroke() ctx.beginPath() - if (trace(selected.feature, true)) { + if (tracePoints(sel)) { ctx.strokeStyle = ring ctx.lineWidth = 4 ctx.stroke() @@ -758,11 +785,9 @@ // more than it tells you: mid-drag (the cursor is already 'grabbing'), in // cluster mode (nothing there is selectable), and on a set large enough // that the walk would eat the frame it is trying to stay ahead of. - hoveringFeature = - mode === 'features' && - !dragging && - features.length <= 4000 && - !!hitTest(features, (x, y) => toScreen(view, width, height, x, y), px, py, 7) + // Against the projected cache this is a box test per feature and a few + // segments for the ones under the cursor, cheap enough for every frame. + hoveringFeature = mode === 'features' && !dragging && pick(px, py) >= 0 }) } @@ -796,17 +821,22 @@ // A click that didn't drag is a pick. const rect = canvas?.getBoundingClientRect() if (!rect) return - const hit = hitTest( - features, - (x, y) => toScreen(view, width, height, x, y), - e.clientX - rect.left, - e.clientY - rect.top, - 7, - ) - selected = mode === 'clusters' ? null : hit + const i = mode === 'clusters' ? -1 : pick(e.clientX - rect.left, e.clientY - rect.top) + selected = i >= 0 ? { index: i, feature: features[i], compiled: compiled[i] } : null requestDraw() } + /** + * The feature under a screen point: within 7px of a point or edge, or inside + * a polygon. -1 for none. + * @param {number} px @param {number} py + */ + function pick(px, py) { + if (compiled.length !== features.length) return -1 + const w = fromScreen(view, width, height, px, py) + return hitCompiled(compiled, w.x, w.y, 7 / view.scale) + } + /** @param {WheelEvent} e */ function onWheel(e) { e.preventDefault() @@ -933,7 +963,7 @@ if (next) selectLayer(next) }} items={layers.map((l) => ({ value: layerLabel(l), label: layerLabel(l), hint: `${l.geomType} · ${rowsLabel(l.rows)}` }))} - triggerClass="h-7 w-[290px]" + triggerClass="h-7 w-[18.125rem]" contentClass="w-[22rem]" /> @@ -946,7 +976,7 @@ placeholder="Column" onValueChange={(v) => (filterColumn = v ?? '')} items={[{ value: '', label: 'No filter' }, ...filterColumns.map((c) => ({ value: c, label: c }))]} - triggerClass="h-7 w-[130px]" + triggerClass="h-7 w-[8.125rem]" contentClass="w-56" /> @@ -956,13 +986,13 @@ value={filterOp} onValueChange={(v) => v && (filterOp = v)} items={FILTER_OPS.map((o) => ({ value: o.value, label: o.label }))} - triggerClass="h-7 w-[120px]" + triggerClass="h-7 w-[7.5rem]" contentClass="w-48" /> {#if opNeedsValue} e.key === 'Enter' && applyFilter()} @@ -1015,7 +1045,7 @@ > {error} -
@@ -1088,7 +1118,7 @@ {#if selected}
{layer?.table} diff --git a/src/lib/components/McpPanel.svelte b/src/lib/components/McpPanel.svelte index 9fe6c6e6..9b6f02b9 100644 --- a/src/lib/components/McpPanel.svelte +++ b/src/lib/components/McpPanel.svelte @@ -191,18 +191,11 @@
@@ -287,7 +280,7 @@
-

+

Connect to a database first, then start the MCP server.

diff --git a/src/lib/components/MigrationsPage.svelte b/src/lib/components/MigrationsPage.svelte index 2332c375..7c127b11 100644 --- a/src/lib/components/MigrationsPage.svelte +++ b/src/lib/components/MigrationsPage.svelte @@ -10,7 +10,7 @@ import { Button } from '$lib/components/ui/button/index.js' import SegmentedControl from './SegmentedControl.svelte' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' import RefreshCw from '@lucide/svelte/icons/refresh-cw' import FolderOpen from '@lucide/svelte/icons/folder-open' import ChevronRight from '@lucide/svelte/icons/chevron-right' @@ -20,7 +20,6 @@ import GitMerge from '@lucide/svelte/icons/git-merge' import TriangleAlert from '@lucide/svelte/icons/triangle-alert' import Search from '@lucide/svelte/icons/search' - import { Input } from '$lib/components/ui/input/index.js' let { /** @type {{ id: string, name?: string } | null} */ @@ -136,7 +135,7 @@ await loadProject() if (project && project.tool !== tool) setTool(project.tool) } catch (e) { - toast.error('Could not open the folder', { description: String(e) }) + toast.error('Could not open the folder', { description: errorText(e) }) } } @@ -367,7 +366,7 @@
- +
{#if known} 3 ? 'w-[26rem] max-w-full' : 'w-80 max-w-full'} onchange={(v) => { filter = v; open = null }} /> diff --git a/src/lib/components/MiniJsonViewer.svelte b/src/lib/components/MiniJsonViewer.svelte index 38a31fba..d5dafffc 100644 --- a/src/lib/components/MiniJsonViewer.svelte +++ b/src/lib/components/MiniJsonViewer.svelte @@ -41,13 +41,13 @@
diff --git a/src/lib/components/NetworkSettings.svelte b/src/lib/components/NetworkSettings.svelte new file mode 100644 index 00000000..5a84140a --- /dev/null +++ b/src/lib/components/NetworkSettings.svelte @@ -0,0 +1,124 @@ + + +
+

+ Send each kind of traffic through a proxy, or straight out. A proxy is http://host:port or socks5://host:port, with user:password@ when it needs a login. New connections use the change; open ones keep their route until they reconnect. +

+ {#each KINDS as k (k.id)} + {@const mode = proxy[k.id].mode === 'system' && !k.system ? 'off' : proxy[k.id].mode} +
+
+
+

{k.label}

+

{k.desc}

+
+
+ {#if k.system} + + {/if} + + +
+
+ {#if mode === 'custom'} +
+ commitUrl(k.id)} + onkeydown={(e) => { if (e.key === 'Enter') commitUrl(k.id) }} + /> + +
+ {#if errors[k.id]}

{errors[k.id]}

{/if} + {/if} +
+ {/each} +
diff --git a/src/lib/components/NewTabPage.svelte b/src/lib/components/NewTabPage.svelte new file mode 100644 index 00000000..69da4523 --- /dev/null +++ b/src/lib/components/NewTabPage.svelte @@ -0,0 +1,191 @@ + + +{#snippet chord(/** @type {string[]} */ keys)} + +{/snippet} + + +{#snippet row(/** @type {any} */ Icon, /** @type {string} */ label, /** @type {string} */ desc, /** @type {() => void} */ onclick, /** @type {{ pro?: boolean, keys?: string[], tone?: 'info' | 'success' | 'primary' | 'warning' }} */ opts = {})} + {@const locked = !!opts.pro && !$hasPro} + {@const toneCls = { info: 'text-info', success: 'text-success', primary: 'text-primary', warning: 'text-warning' }[opts.tone ?? 'info']} + {@const chordText = opts.keys ? ` (${opts.keys.join(isMac ? '' : '+')})` : ''} + + +{/snippet} + + +{#snippet jump(/** @type {any} */ Icon, /** @type {string} */ label, /** @type {() => void} */ onclick)} + +{/snippet} + + +
+ +
+ + {#if connection} + +
+ + + +
+

{welcomeTitle}

+

{shortWhere(welcomeWhere)}

+
+
+ + + {/if} + + +
+ {#if isDoc} + {@render row(Database, $tx('tile.Browse', "Browse"), $tx('tile.Browse.desc', "Open collections and edit documents"), ondocs, { tone: 'info' })} + {@render row(Terminal, $tx('tile.Query', "Query"), $tx('tile.Query.desc', "Run queries in the SQL editor"), onsql, { keys: [mod, shiftKey, "S"], tone: 'success' })} + {:else if isDynamo} + {@render row(Database, $tx('tile.Tables', "Tables"), $tx('tile.Tables.desc', "Scan, query and edit items"), ondynamo, { tone: 'info' })} + {@render row(Terminal, $tx('tile.PartiQL', "PartiQL"), $tx('tile.PartiQL.desc', "Query in the SQL editor"), onsql, { keys: [mod, shiftKey, "S"], tone: 'success' })} + {:else if isRedis} + {@render row(KeyRound, $tx('tile.Keyspace', "Keyspace"), $tx('tile.Keyspace.desc', "Browse keys and values"), onredis, { tone: 'info' })} + {:else} + {@render row(Terminal, $tx('tile.SQL', "SQL"), $tx('tile.SQL.desc', "Write and run a query"), onsql, { keys: [mod, shiftKey, "S"], tone: 'info' })} + {/if} + {#if connection && !isDynamo && !isDoc} + {@render row(SquareTerminal, $tx('tile.Terminal', "Terminal"), terminalClient ? $tx('tile.Terminal.client', "{client}, docked below", { client: terminalClient }) : $tx('tile.Terminal.builtin', "Built-in SQL prompt, docked below"), onterminal, { keys: [IS_MAC ? "⌘" : "Ctrl", "J"], tone: 'success' })} + {/if} + {@render row(Sparkles, $tx('tile.AI', "AI"), $tx('tile.AI.desc', "Ask about this database"), onai, { pro: true, keys: [mod, "I"], tone: 'primary' })} + {#if connection && !isKV} + {@render row(Search, $tx('tile.Search', "Search"), $tx('tile.Search.desc', "Find in database: search every table at once"), onsearch, { keys: [mod, shiftKey, "G"], tone: 'warning' })} + {/if} + {@render row(Blocks, $tx('tile.Extensions', "Extensions"), $tx('tile.Extensions.desc', "Add and manage extensions"), onextensions, { pro: true, keys: [mod, shiftKey, "X"], tone: 'info' })} + {@render row(Database, $tx('tile.Connect', "Connect"), $tx('tile.Connect.desc', "Switch or add a connection"), onconnect, { keys: [mod, shiftKey, "C"], tone: 'success' })} +
+ + +
+
diff --git a/src/lib/components/NotebookEditor.svelte b/src/lib/components/NotebookEditor.svelte index 1af9641b..d4d8e2b2 100644 --- a/src/lib/components/NotebookEditor.svelte +++ b/src/lib/components/NotebookEditor.svelte @@ -10,7 +10,7 @@ * - {{name}} variables, filled from the bar under the toolbar before a run. * - Autosave once the notebook has a file; a recent list to come back to. */ - import { onDestroy } from 'svelte' + import { onDestroy, tick } from 'svelte' import { Button } from '$lib/components/ui/button/index.js' import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js' import { comboTitle } from '$lib/shortcuts.js' @@ -191,8 +191,16 @@ // ── Variables ──────────────────────────────────────────────────────────── /** @param {string} [name] */ function addVariable(name = '') { + const i = vars.length update({ variables: [...vars, { name, value: '' }] }) + // Straight to what is still missing: the value for a name a cell already + // uses, the name for a blank one. Focus stayed on the button that vanished. + void tick().then(() => { + /** @type {HTMLInputElement | null | undefined} */ (varsBar?.querySelector(`[data-var="${i}"][data-part="${name ? 'value' : 'name'}"]`))?.focus() + }) } + /** @type {HTMLElement | null} */ + let varsBar = $state(null) /** @param {number} i @param {Partial<{ name: string, value: string }>} patch */ function setVariable(i, patch) { update({ variables: vars.map((v, j) => (j === i ? { ...v, ...patch } : v)) }) @@ -441,13 +449,13 @@ {#if vars.length || undefinedVars.length} -
+
Variables {#each vars as v, i (i)} - setVariable(i, { name: /** @type {HTMLInputElement} */ (e.target).value.replace(/[^\w]/g, '') })} /> + setVariable(i, { name: /** @type {HTMLInputElement} */ (e.target).value.replace(/[^\w]/g, '') })} /> = - setVariable(i, { value: /** @type {HTMLInputElement} */ (e.target).value })} /> + setVariable(i, { value: /** @type {HTMLInputElement} */ (e.target).value })} /> {/each} @@ -523,7 +531,7 @@

- {comboTitle('Mod+Enter')} run · ⇧↵ run and next · {comboTitle('Mod+Shift+Enter')} run all · write {'{{name}}'} in a query for a variable + {comboTitle('Mod+Enter')} run · {comboTitle('Shift+Enter')} run and next · {comboTitle('Mod+Shift+Enter')} run all · write {'{{name}}'} in a query for a variable

{/if} diff --git a/src/lib/components/ObjectsPage.svelte b/src/lib/components/ObjectsPage.svelte index 17d61163..894f55cd 100644 --- a/src/lib/components/ObjectsPage.svelte +++ b/src/lib/components/ObjectsPage.svelte @@ -1,4 +1,5 @@ @@ -304,7 +308,7 @@ {:else} {schema} {/if} - {#if tableCount} · {tableCount} {tableCount === 1 ? 'table' : 'tables'}{/if} + {#if tableCount}{' '}· {tableCount} {tableCount === 1 ? 'table' : 'tables'}{/if} @@ -364,10 +368,15 @@

{active.label} doesn't support this engine

{active.label} has no {dbType} driver, so there's no schema to write. - {#if TARGETS.some((t) => t.id !== active.id && t.engines.includes(dbType))} - Switch to {TARGETS.find((t) => t.id !== active.id)?.label} above. - {/if}

+ + {#if TARGETS.find((t) => t.id !== active.id && t.engines.includes(dbType))} + {@const alt = TARGETS.find((t) => t.id !== active.id && t.engines.includes(dbType))} + + {/if}
{:else if effectiveScope === 'database' ? (dbLoading && !dbModels.length) : (loading && !model)} diff --git a/src/lib/components/ProviderConnect.svelte b/src/lib/components/ProviderConnect.svelte index 3c509ed6..1757e69c 100644 --- a/src/lib/components/ProviderConnect.svelte +++ b/src/lib/components/ProviderConnect.svelte @@ -875,7 +875,7 @@ items={dbItems} placeholder="Search {databases.length} databases…" empty="No matching database" - contentClass="w-[var(--bits-popover-anchor-width)] min-w-[280px]" + contentClass="w-[var(--bits-popover-anchor-width)] min-w-[17.5rem]" align="start" onselect={(it) => { clearTimeout(hoverTimer); pick(it.value) }} onhover={(it) => hoverRow(it.value)} diff --git a/src/lib/components/ProviderCreateDatabase.svelte b/src/lib/components/ProviderCreateDatabase.svelte index 3b5b8751..271bcc2c 100644 --- a/src/lib/components/ProviderCreateDatabase.svelte +++ b/src/lib/components/ProviderCreateDatabase.svelte @@ -201,7 +201,7 @@ placeholder="Search {p.items.length} {p.noun}s…" empty="No matching {p.noun}" searchThreshold={6} - contentClass="z-[120] w-[var(--bits-popover-anchor-width)] min-w-[260px]" + contentClass="z-[120] w-[var(--bits-popover-anchor-width)] min-w-[16.25rem]" align="start" onselect={(it) => p.onpick(it.value)} > diff --git a/src/lib/components/QueriesPage.svelte b/src/lib/components/QueriesPage.svelte new file mode 100644 index 00000000..bf6e7e95 --- /dev/null +++ b/src/lib/components/QueriesPage.svelte @@ -0,0 +1,74 @@ + + +
+
+
+

Queries

+ {#if connectionName}

{connectionName}

{/if} +
+
+ {#each VIEWS as v (v.id)} + {@const on = view === v.id} + + {/each} +
+
+ {#key view} + onopen(sql)} + onrun={(sql) => onrun(sql)} + {onrefresh} + /> + {/key} +
diff --git a/src/lib/components/QueryHistoryPanel.svelte b/src/lib/components/QueryHistoryPanel.svelte index 602ae314..23393642 100644 --- a/src/lib/components/QueryHistoryPanel.svelte +++ b/src/lib/components/QueryHistoryPanel.svelte @@ -1,4 +1,5 @@ +{#snippet inline(/** @type {string} */ text)} + {#each splitInlineMarks(text) as p, k (k)} + {#if p.code}{p.text}{:else if p.bold}{p.text}{:else}{p.text}{/if} + {/each} +{/snippet} + {#if versions.length} -
+
{#each versions as r (r.version)} -
+
{#if multi} -

+

{r.version} {#if r.date}{shortDate(r.date)}{/if}

{/if} -
    - {#each r.items as item, i (i)} -
  • - - - {#if TAG[item.type]} - {TAG[item.type]?.label} - {/if} - {#each parts(item.text) as p, k (k)} - {#if p.code}{p.text}{:else}{p.text}{/if} - {/each} - -
  • - {/each} -
+ {#each r.groups as g, gi (gi)} +
+

+ + {g.heading} +

+
    + {#each g.items as item, i (i)} +
  • + {#if item.title} +

    {@render inline(item.title)}

    + {#if item.body}

    {@render inline(item.body)}

    {/if} + {:else} +

    {@render inline(item.body)}

    + {/if} +
  • + {/each} +
+
+ {/each}
{/each} diff --git a/src/lib/components/ResultMap.svelte b/src/lib/components/ResultMap.svelte new file mode 100644 index 00000000..cb33e4b9 --- /dev/null +++ b/src/lib/components/ResultMap.svelte @@ -0,0 +1,537 @@ + + +
+ +
+ + {#if spatial.length > 1} + + {:else} + {columns[col]?.name ?? ''} + {/if} + + {shown} {shown === 1 ? 'shape' : 'shapes'}{selected.size ? ` · ${selected.size} selected` : ''}{partial ? ' · loaded rows' : ''} + + +
+ +
+ + (dragFrom = null)} + onpointerleave={() => { cursor = null; hoverRow = null }} + onwheel={onWheel} + ondblclick={() => zoomBy(2)} + > + +
+ {#each BASEMAPS as b (b.id)} + + {/each} +
+ +
+ + + + +
+ + {#if card && cardPos} + + {/if} + + {#if layer && !shown} +
+

+ {hint || 'No shapes in this column to draw.'} +

+
+ {/if} + +
+ + {cursor ? formatLonLat(cursor.lon, cursor.lat) : 'drag to pan · scroll to zoom · click a shape'} + + {#if !basemap.offline} + {basemap.attribution} + {/if} +
+
+ + {#if hint && shown} +

{hint}

+ {:else if layer?.assumed} +

+ {layer.assumed} {layer.assumed === 1 ? 'value has' : 'values have'} no SRID and {layer.assumed === 1 ? 'is' : 'are'} drawn as WGS 84 (EPSG:4326). +

+ {/if} +
diff --git a/src/lib/components/RowDetailPanel.svelte b/src/lib/components/RowDetailPanel.svelte index 3164705e..c1001a26 100644 --- a/src/lib/components/RowDetailPanel.svelte +++ b/src/lib/components/RowDetailPanel.svelte @@ -1,4 +1,5 @@ + +{#snippet bodyView(/** @type {string} */ body)} +
{#each bodyParts(body) as p, i (i)}{#if p.stop}{p.text || `$${p.stop}`}{:else}{p.text}{/if}{/each}
+{/snippet} + +{#snippet scopeChips(/** @type {string[]} */ scope)} + {#if scope.length} + {#each scope as id (id)} + {scopeLabel(id)} + {/each} + {/if} +{/snippet} + +
+

+ SQL you reuse, a word away. Type a snippet's trigger in the SQL editor and pick it from the list; Tab moves between its fields. +

+ +
+ + +
+ + {#if draft} +
+
+ + +
+ +
+ SQL +
+ {#key draftKey} + { if (draft) draft.body = v }} ariaLabel="Snippet SQL" /> + {/key} +
+

{'${1:table}'} is a field Tab moves to, with "table" as its placeholder. The same number twice is one field typed in both places.

+
+
+ Engines +
+ + {#each SNIPPET_SCOPES as s (s.id)} + + {/each} +
+
+
+

+ {#if draftError}{draftError}{:else if triggerClash}"{triggerClash.name}" uses {triggerClash.trigger} too; both will be offered.{/if} +

+ + +
+
+ {/if} + +
+
+

Yours {$userSnippets.length}

+ + + +
+ {#if !$userSnippets.length} +
+

No snippets of your own yet

+

Add one, import a file, or duplicate a built-in one below to change it.

+
+ {:else if !mine.length} +

None of yours match.

+ {:else} +
    + {#each mine as s (s.id)} +
  • +
    +
    +

    + {s.name} + {s.trigger} + {@render scopeChips(s.scope)} +

    + {#if s.description}

    {s.description}

    {/if} +
    +
    + + + +
    +
    + {@render bodyView(s.body)} +
  • + {/each} +
+ {/if} +
+ +
+ + {#if builtinOpen || query.trim()} +
    + {#each builtins as s, i (i)} +
  • +
    + {s.name} + {s.trigger} + {@render scopeChips(s.scope.filter((id) => SNIPPET_SCOPES.some((x) => x.id === id)))} + + +
    + {@render bodyView(s.body)} +
  • + {/each} +
+ {/if} +
+
diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index b7ec723e..f4d17412 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -1,5 +1,6 @@ +{#if dialogMounted.onboarding} + {#await lazyDialogs.onboarding() then { default: Onboarding }} (showConnectionModal = true)} onsample={handleSampleConnect} /> + {/await} +{/if} +{#if dialogMounted.connection} + {#await lazyDialogs.connection() then { default: ConnectionModal }} onConnected(conn, id)} @@ -9897,26 +10879,32 @@ let rowSearch = $state('') ondisconnect={requestDisconnect} onremoved={handleConnectionRemoved} /> + {/await} +{/if} +{#if dialogMounted.createDb} + {#await lazyDialogs.createDb() then { default: CreateDatabaseDialog }} + {/await} +{/if} {#if dbNameDialog} - + />{/await} {/if} { try { await executeDdl(sql) } - catch (e) { toast.error('Could not create schema', { description: String(e) }); throw e } + catch (e) { toast.error('Could not create schema', { description: errorText(e) }); throw e } }} oncreated={async (schemaName) => { toast.success(`Schema "${schemaName}" created`) @@ -9960,6 +10948,8 @@ let rowSearch = $state('') await handleSchemaChange(schemaName) }} /> +{#if dialogMounted.generateSql} + {#await lazyDialogs.generateSql() then { default: GenerateSqlDialog }} { if (aiMode) exitAiMode(); void openQueryInEditor(sql) }} /> + {/await} +{/if} {#if dialogMounted.docker} {#await lazyDialogs.docker() then { default: DockerLaunchModal }} @@ -9978,7 +10970,11 @@ let rowSearch = $state('') {/await} {/if} +{#if dialogMounted.mcp} + {#await lazyDialogs.mcp() then { default: McpPanel }} + {/await} +{/if} {#if dialogMounted.settings} {#await lazyDialogs.settings() then { default: SettingsDialog }} @@ -10002,7 +10998,7 @@ let rowSearch = $state('') table={activeTable ?? ''} {columns} {primaryKey} - onimported={() => reloadTableFromQuery(false)} + onimported={async () => { await reloadTableFromQuery(false); void recountActiveTable() }} /> {/await} {/if} @@ -10016,9 +11012,19 @@ let rowSearch = $state('') +{#if dialogMounted.insider} + {#await lazyDialogs.insider() then { default: InsiderDialog }} + {/await} +{/if} +{#if dialogMounted.about} + {#await lazyDialogs.about() then { default: AboutDialog }} (showReportIssueDialog = true)} /> + {/await} +{/if} +{#if dialogMounted.report} + {#await lazyDialogs.report() then { default: ReportIssueDialog }} + {/await} +{/if} {#if showStudioShare || studioShare} {#await import('./StudioShareDialog.svelte') then { default: StudioShareDialog }} @@ -10052,7 +11060,7 @@ let rowSearch = $state('') - +
@@ -10087,6 +11095,7 @@ let rowSearch = $state('') void confirmRevert()} oncancel={() => settleRevert(false)} /> {/await} {/if} + 0 ? (/** @type {string} */ f) => void handleExport(f) : null} + exportTableName={activeTable ?? ''} + onexplainquery={activeTab?.kind === 'sql' && /** @type {any} */ (activeTab).draft !== false && !aiMode ? () => sqlConsoleRef?.explainEditor?.() : null} + onimporttable={activeTab?.kind === 'table' && activeTable && !aiMode && !tableReadonly ? () => (importDataOpen = true) : null} connected={!!connection} {schemas} {tables} @@ -10133,10 +11146,12 @@ let rowSearch = $state('') onopenSchema={() => { if (aiMode) exitAiMode(); openSchemaTab() }} onopensecurity={() => { if (aiMode) exitAiMode(); openSecurityTab() }} onopenlogs={() => { if (aiMode) exitAiMode(); openLogsTab() }} + onopenqueries={() => { if (aiMode) exitAiMode(); openQueriesTab('history') }} onopenterminal={() => { if (aiMode) exitAiMode(); if (!terminalDockOpen) toggleTerminalDock() }} onnewterminal={() => { commandOpen = false; if (aiMode) exitAiMode(); openNewTerminalTab() }} onopenwhatsnew={() => { commandOpen = false; void updateDialog?.showWhatsNew?.() }} onsharestudio={studioShareEnabled ? () => { commandOpen = false; showStudioShare = true } : null} + onsharedconsole={studioShare ? () => { commandOpen = false; openSharedConsole() } : null} onopeninsights={() => { if (aiMode) exitAiMode(); openInsightsTab() }} onopenadvisor={() => { if (aiMode) exitAiMode(); openAdvisorTab() }} onopenobjects={() => { if (aiMode) exitAiMode(); openObjectsTab() }} @@ -10157,9 +11172,11 @@ let rowSearch = $state('') {hasInsights} {hasAdvisor} onopenJsonViewer={() => { if (aiMode) exitAiMode(); openJsonTab() }} + onfiledb={(how) => void handleFileDatabase(how)} onopenshortcuts={() => openShortcuts()} onopenmyshares={() => openSharesTab()} onopenkeybindings={() => { settingsSection = 'keybindings'; showSettingsModal = true }} + onopenappearance={() => { settingsSection = 'appearance'; showSettingsModal = true }} onopenabout={() => (showAboutModal = true)} onopenreport={() => (showReportIssueDialog = true)} oncheckupdate={() => void updateDialog?.checkNow()} @@ -10187,7 +11204,7 @@ let rowSearch = $state('') -{#if autoConnecting && !connection} +{#if overlayWanted || overlayHeld} @@ -10204,6 +11221,7 @@ let rowSearch = $state('') verb={autoConnectVerb} name={autoConnectName ? shortConnLabel(autoConnectName) : ''} delay={autoConnectVerb === 'Reconnecting' ? 350 : 0} + offline={autoConnectOffline} oncancel={() => void cancelAutoConnect()} />
@@ -10273,10 +11291,10 @@ let rowSearch = $state('') > console.error('[sidebar] crashed:', e)}> {#snippet failed(err, reset)} -
+

Sidebar error

-

{String(/** @type {any} */ (err)?.message ?? err)}

+

{String(/** @type {any} */ (err)?.message ?? err)}

- or press -
- - - {#if recentConnections.length} -
-
-

Recent

- -
-
    - {#each recentConnections as conn (conn.id)} - {@const slot = savedConnections.indexOf(conn) + 1} -
  • - -
  • - {/each} -
-
- {/if} - - -
-

Start with

-
- {#each [['postgres','PostgreSQL'],['mysql','MySQL'],['sqlite','SQLite'],['mongodb','MongoDB'],['redis','Redis'],['d1','Cloudflare D1']] as [id, label] (id)} - - {/each} -
-
-
- - -

- {#if appVersion} - v{appVersion} - - {/if} - - - made with care by - { e.preventDefault(); void openExternalUrl('https://nischal-dahal.com.np') }} - >@broisnees -

-
+ { if (engine) connectionModalEngine = engine; showConnectionModal = true }} + onopen={(conn) => void handleSwitchDatabase(conn)} + oncheckupdates={() => void updateDialog?.checkNow?.()} + onopenlink={(url) => void openExternalUrl(url)} + onfiledb={(how) => void handleFileDatabase(how)} + /> {:else} {#if aiEverOpened} @@ -10691,7 +11624,7 @@ let rowSearch = $state('') > {#await import('./SecurityPage.svelte')}{:then { default: SecurityPage }} - + {/await} @@ -10705,7 +11638,7 @@ let rowSearch = $state('') > {#await import('./BackupPage.svelte')}{:then { default: BackupPage }} - c.id === activeConnectionId) ?? null} tables={tables.map((t) => ({ name: t.name, rowCount: t.rowCount }))} onrestored={async () => { await loadSchemas(); await loadTables({ force: true }); bumpObjects() }} /> + c.id === activeConnectionId) ?? null} tables={tables.filter((t) => !/view|foreign/i.test(t.kind ?? '')).map((t) => ({ name: t.name, rowCount: t.rowCount }))} onrestored={async () => { await loadSchemas(); await loadTables({ force: true }); bumpObjects() }} /> {/await} @@ -10791,7 +11724,7 @@ let rowSearch = $state('') > {#await import('./InstanceInsightsPage.svelte')}{:then { default: InstanceInsightsPage }} - + {/await} @@ -10837,6 +11770,7 @@ let rowSearch = $state('') {#await import('./ObjectsPage.svelte')}{:then { default: ObjectsPage }} void openTableTab(schema || activeSchema, name)} @@ -10899,6 +11833,7 @@ let rowSearch = $state('') adapter={docAdapter} collection={/** @type {any} */ (dt).collection ?? ''} where={docWhere} + collectionCount={loadingTables ? -1 : tables.length} onopensql={(text, coll) => { if (aiMode) exitAiMode(); openSqlTabWith(text, coll ? `${docAdapter.consoleLabel} · ${coll}` : docAdapter.consoleLabel) }} /> {/key} @@ -10916,7 +11851,7 @@ let rowSearch = $state('') > {#await import('./MapPage.svelte')}{:then { default: MapPage }} - + {/await} @@ -10949,6 +11884,25 @@ let rowSearch = $state('') {/key} {/if} + + {#if activeTab?.kind === 'queries'} +
+ + {#await import('./QueriesPage.svelte')}{:then { default: QueriesPage }} + void openQueryInEditor(sql)} + onrun={async (sql) => { await openQueryInEditor(sql); await tick(); sqlConsoleRef?.runEditor?.() }} + onrefresh={refreshQueryStores} + /> + {/await} + +
+ {/if} + {#if activeTab?.kind === 'shares'}
@@ -11051,6 +12005,7 @@ let rowSearch = $state('') {#await import('./EntityRelationPage.svelte')}{:then { default: EntityRelationPage }} openDiagramsTab()} schema={activeSchema} {schemas} @@ -11073,6 +12028,7 @@ let rowSearch = $state('') {#await import('./SearchPage.svelte')}{:then { default: SearchPage }} void endSqlTransaction('commit')} onrollbacktransaction={() => void endSqlTransaction('rollback')} bind:sql={sqlText} + collab={sharedConsoleOn ? sharedConsoleExt : null} bind:queryHistoryVisible {queryHistory} {savedQueries} @@ -11275,6 +12232,7 @@ let rowSearch = $state('') onmodshifto={() => { if (connection) openOrmTab() }} onqueryrefresh={refreshQueryStores} onhistoryselect={(sql) => openQueryInEditor(sql)} + onopenqueries={(view) => openQueriesTab(view)} onsavequery={handleSaveQuery} onsaveinplace={handleSaveInPlace} savedQueryName={activeSavedQuery?.name ?? ''} @@ -11287,79 +12245,27 @@ let rowSearch = $state('')
{/if} - {#if activeTab?.kind === 'table'} + {#if tableEverOpened} + +
- {#if error} - - {@const kind = connectionErrorKind(error)} - {@const humanized = humanizeDbError(error)} - - {:else if !activeTable} + {#if error && onTableTab} + void retryTableLoad()} + ondismiss={() => { error = '' }} + /> + {:else if !activeTable && onTableTab}

Select a table from the sidebar or press @@ -11521,22 +12427,22 @@ let rowSearch = $state('') {#await loadDataTable() then { default: DataTable }} tableToolbar?.focusRowSearch?.()} dialect={dbType} - indexes={activeTableIndexes} + indexes={gridData.indexes} {hiddenColumns} {reloadToken} {dataVersion} @@ -11545,12 +12451,12 @@ let rowSearch = $state('') {windowStatus} onvisiblerange={handleVisibleRange} onretrywindows={retryFailedWindows} - columnWidthsKey={activeTable ? `${persistConnectionId}\x00${activeSchema}.${activeTable}` : undefined} + columnWidthsKey={gridData.columnWidthsKey} loading={loadingRows} {loadingMore} {infiniteScroll} - endOfResults={infiniteScroll && !windowed && total > 0 && rows.length >= total} - filtered={rowSearch.trim() !== '' || activeFilters(rowFilters).length > 0} + endOfResults={gridData.endOfResults} + filtered={gridData.filtered} onclearfilters={clearRowFilters} onloadmore={handleLoadMore} saving={savingCell || deletingRows || insertingRow} @@ -11570,13 +12476,15 @@ let rowSearch = $state('') bind:canScrollHorizontally={tableCanScrollH} bind:focusColumn={focusTableColumn} bind:focusCell={tableFocusCell} + peers={gridPeers} + onpresence={studioShare ? publishGridPresence : null} bind:getScroll={tableGetScroll} bind:getExpanded={tableGetExpanded} bind:applyScroll={tableApplyScroll} bind:vcolPanelOpen - {rowSort} - {rowSortMore} - searchQuery={rowSearch} + rowSort={gridData.rowSort} + rowSortMore={gridData.rowSortMore} + searchQuery={gridData.searchQuery} {searchOptions} onsortchange={(s) => void handleRowSortChange(s)} onhidecolumn={(colName) => { @@ -11649,6 +12557,8 @@ let rowSearch = $state('') onprevpage={() => void handlePageChange(page - 1)} onnextpage={() => void handlePageChange(page + 1)} onsave={handleSaveCell} + onloadvalue={dbType === 'postgres' ? handleLoadCellValue : null} + {dataVersion} /> {:else if dataViewMode === 'text'} {#await import('./TableTextView.svelte')}{:then { default: TableTextView }} @@ -11684,7 +12594,7 @@ let rowSearch = $state('') {/if} {#if dataViewMode === 'table'} - + />{/await}{/if} {/if}

{/if} {/if} +
{/if} - {#if !activeTab || activeTab.kind === 'welcome'} - - {@const isMac = IS_MAC} - {@const mod = isMac ? '⌘' : 'Ctrl'} - - - {@const cell = 'group relative flex min-h-[5.25rem] min-w-0 flex-col justify-between overflow-hidden rounded-lg border border-border/60 bg-card/50 p-2.5 text-left transition-[background-color,border-color,box-shadow,transform] duration-150 ease-[var(--ease-out)] hover:border-border hover:bg-accent/40 hover:shadow-sm active:scale-[0.98]'} - {@const proCell = 'group relative flex min-h-[5.25rem] min-w-0 cursor-not-allowed flex-col justify-between overflow-hidden rounded-lg border border-border/40 bg-card/30 p-2.5 text-left transition-[background-color,border-color] duration-150 hover:border-warning/30 hover:bg-warning/[0.04]'} - {@const iconCls = 'size-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground'} - {@const proIconCls = 'size-4 shrink-0 text-muted-foreground'} - {@const labelCls = 'text-ui-2xs font-medium leading-[1.25] text-foreground/85 transition-colors group-hover:text-foreground [overflow-wrap:anywhere]'} - {@const proLabelCls = 'text-ui-2xs font-medium leading-[1.25] text-muted-foreground [overflow-wrap:anywhere]'} - - - {@const shiftKey = isMac ? '⇧' : 'Shift'} - {#snippet chord(/** @type {string[]} */ keys)} - - {/snippet} - - - {#snippet row(/** @type {any} */ Icon, /** @type {string} */ label, /** @type {string} */ desc, /** @type {() => void} */ onclick, /** @type {{ pro?: boolean, keys?: string[], tone?: 'info' | 'success' | 'primary' | 'warning' }} */ opts = {})} - {@const locked = !!opts.pro && !$hasPro} - {@const toneCls = { info: 'text-info', success: 'text-success', primary: 'text-primary', warning: 'text-warning' }[opts.tone ?? 'info']} - {@const chordText = opts.keys ? ` (${opts.keys.join(isMac ? '' : '+')})` : ''} - - - {/snippet} - - - {#snippet jump(/** @type {any} */ Icon, /** @type {string} */ label, /** @type {() => void} */ onclick)} - - {/snippet} - - -
- -
- - {#if connection} - -
- - - -
-

{welcomeTitle}

-

{shortWhere(welcomeWhere)}

-
-
- - - {/if} - - -
- {#if isDoc} - {@render row(Database, "Browse", "Open collections and edit documents", openDocsTab, { tone: 'info' })} - {@render row(Terminal, "Query", "Run queries in the SQL editor", openSqlTab, { keys: [mod, shiftKey, "S"], tone: 'success' })} - {:else if isDynamo} - {@render row(Database, "Tables", "Scan, query and edit items", openDynamoTab, { tone: 'info' })} - {@render row(Terminal, "PartiQL", "Query in the SQL editor", openSqlTab, { keys: [mod, shiftKey, "S"], tone: 'success' })} - {:else if isRedis} - {@render row(KeyRound, "Keyspace", "Browse keys and values", openRedisTab, { tone: 'info' })} - {:else} - {@render row(Terminal, "SQL", "Write and run a query", openSqlTab, { keys: [mod, shiftKey, "S"], tone: 'info' })} - {/if} - {#if connection && !isDynamo && !isDoc} - {@render row(SquareTerminal, "Terminal", isRedis ? "redis-cli, docked below" : "psql, mysql or sqlite3, docked below", () => { if (aiMode) exitAiMode(); if (!terminalDockOpen) toggleTerminalDock() }, { keys: [IS_MAC ? "⌘" : "Ctrl", "J"], tone: 'success' })} - {/if} - {@render row(Sparkles, "AI", "Ask about this database", openAiTab, { pro: true, keys: [mod, shiftKey, "E"], tone: 'primary' })} - {#if connection && !isKV} - {@render row(Search, "Search", "Find in database: search every table at once", openSearchTab, { keys: [mod, shiftKey, "G"], tone: 'warning' })} - {/if} - {@render row(Blocks, "Extensions", "Add and manage extensions", openExtensionsTab, { pro: true, keys: [mod, shiftKey, "X"], tone: 'info' })} - {@render row(Database, "Connect", "Switch or add a connection", () => (showConnectionModal = true), { keys: [mod, shiftKey, "C"], tone: 'success' })} -
- - -
-
+ {#if (!activeTab || activeTab.kind === 'welcome') && !restoringTabs} + { commandPage = page; commandOpen = true }} + ondocs={openDocsTab} + onsql={openSqlTab} + ondynamo={openDynamoTab} + onredis={openRedisTab} + onterminal={() => { if (aiMode) exitAiMode(); if (!terminalDockOpen) toggleTerminalDock() }} + onai={openAiTab} + onsearch={openSearchTab} + onextensions={openExtensionsTab} + onconnect={() => (showConnectionModal = true)} + /> {/if} {/snippet} {/if} {/if} - {#if connection && terminalDockEver} + + {#if connection && terminalDockEver && (terminalDockOpen || connectSettled)}
{#if queryLogOpen && connection} - { queryLogOpen = false }} /> + {#await import('./QueryLogConsole.svelte') then { default: QueryLogConsole }} { queryLogOpen = false }} />{/await} {/if} diff --git a/src/lib/components/SyncSection.svelte b/src/lib/components/SyncSection.svelte index ca937f1c..9ebf55ab 100644 --- a/src/lib/components/SyncSection.svelte +++ b/src/lib/components/SyncSection.svelte @@ -6,7 +6,7 @@ import { Input } from '$lib/components/ui/input/index.js' import { syncStatus, syncLabel, syncNow, setupSync, unlockSync, resetSync, lockSync } from '$lib/sync/runtime.js' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' import RefreshCw from '@lucide/svelte/icons/refresh-cw' import LockKeyhole from '@lucide/svelte/icons/lock-keyhole' import CircleAlert from '@lucide/svelte/icons/circle-alert' @@ -82,7 +82,7 @@ await lockSync() toast.success('Sync locked on this device', { description: 'Your synced data stays in your account.' }) } catch (e) { - toast.error('Could not lock sync', { description: String(e) }) + toast.error('Could not lock sync', { description: errorText(e) }) } } diff --git a/src/lib/components/TabBar.svelte b/src/lib/components/TabBar.svelte index c31a1183..6b0918c6 100644 --- a/src/lib/components/TabBar.svelte +++ b/src/lib/components/TabBar.svelte @@ -52,6 +52,19 @@ ondragtabend = () => {}, } = $props() + /** Titles that tabs from different databases share (two "orders" tables): + * those tabs name their database after the title. */ + const clashing = $derived.by(() => { + /** @type {Map>} */ + const by = new Map() + for (const t of tabs) { + if (!t.connLabel) continue + const title = tabDisplayTitle(t) + by.set(title, (by.get(title) ?? new Set()).add(t.connLabel)) + } + return new Set([...by].filter(([, dbs]) => dbs.size > 1).map(([title]) => title)) + }) + // ── Pointer-based tab drag (HTML5 DnD is unreliable in Tauri's WebKit) ────── /** @type {{ id: string, startX: number, startY: number, active: boolean } | null} */ let _tabDrag = null @@ -101,10 +114,12 @@ const el = scrollEl if (!el) return const _n = tabs.length - updateFades() + // In the frame, not now: read during the render it forced an early layout + // of the whole page (see Sidebar's scheduleMeasureTables). + const frame = requestAnimationFrame(updateFades) const ro = new ResizeObserver(updateFades) ro.observe(el) - return () => ro.disconnect() + return () => { cancelAnimationFrame(frame); ro.disconnect() } }) /** A plain mouse wheel scrolls the strip sideways. @param {WheelEvent} e */ @@ -125,13 +140,19 @@ return () => cancelAnimationFrame(raf) }) + /** The tab the strip's right-click menu is for. */ + let menuTabId = $state(/** @type {string | null} */ (null)) + const menuTab = $derived(menuTabId ? tabs.find((t) => t.id === menuTabId) ?? null : null) + /** @param {StudioTab} tab */ function tabIcon(tab) { if (tab.kind === 'sql') return 'terminal' if (tab.kind === 'terminal') return 'square-terminal' if (tab.kind === 'table') { const entityKind = /** @type {any} */ (tab.state)?.tableKind - if (entityKind === 'view' || entityKind === 'materialized_view') return 'eye' + // The sidebar's marks: an eye for a view, layers for a materialized view. + if (entityKind === 'materialized_view') return 'layers' + if (entityKind === 'view') return 'eye' return 'table-2' } if (tab.kind === 'ai') return 'bot' @@ -145,8 +166,33 @@ if (tab.kind === 'license') return 'key-round' if (tab.kind === 'shortcuts') return 'keyboard' if (tab.kind === 'shares') return 'share-2' + if (tab.kind === 'queries') return 'history' if (tab.kind === 'migrations') return 'git-merge' - return 'file-text' + // The rest match the command palette's icon for the same page; they all + // fell through to a page icon, so a diagram looked like a notebook. + const PAGE_ICONS = /** @type {Record} */ ({ + erd: 'network', + diagrams: 'git-branch', + reltree: 'list-tree', + 'schema-timeline': 'git-branch', + 'data-diff': 'git-compare', + backup: 'archive', + json: 'braces', + charts: 'bar-chart-2', + dashboard: 'layout-dashboard', + logs: 'history', + insights: 'database', + advisor: 'shield-check', + objects: 'shapes', + 'extension-detail': 'blocks', + ddl: 'file-code', + notebook: 'notebook-pen', + // A collection, a measurement, a label, a DynamoDB table: rows, like a table tab. + docs: 'table-2', + dynamodb: 'table-2', + redis: 'key-round', + }) + return PAGE_ICONS[tab.kind] ?? 'file-text' } @@ -175,93 +221,106 @@ onscroll={updateFades} onwheel={onStripWheel} > + + + { + const id = /** @type {HTMLElement | null} */ (/** @type {Element} */ (e.target).closest('[data-tab-id]'))?.dataset.tabId + menuTabId = id ?? null + }} + > {#each tabs as tab, i (tab.id)} {@const tabIconName = tabIcon(tab)} {@const active = tab.id === activeTabId} + + +
tabPointerDown(e, tab.id)} + onpointerup={(e) => { + // Middle-click closes (pinned tabs stay protected, like the ✕ button) + if (e.button === 1 && !tab.pinned) { e.preventDefault(); onclose(tab.id) } + }} + class={cn( + // rem, not px: a px cap held less text at every zoom step up, and the + // floor keeps a short title from being squeezed to "New t…". + // A pill, not a folder tab: the active one is a soft lighter fill, + // the rest are just text until you hover them. + 'group/tab relative flex h-7 min-w-24 max-w-50 shrink-0 items-stretch rounded-md transition-colors duration-100', + active + ? 'bg-sidebar-accent shadow-[inset_0_0_0_1px_var(--color-border)]' + : 'hover:bg-sidebar-accent/50', + )} + > + + - - - {#snippet child({ props: ctxProps })} -
tabPointerDown(e, tab.id)} - onpointerup={(e) => { - // Middle-click closes (pinned tabs stay protected, like the ✕ button) - if (e.button === 1 && !tab.pinned) { e.preventDefault(); onclose(tab.id) } - }} + {#if tab.pinned} + + - - {#if tab.pinned} - - - {:else} - - - {/if} - -
- {/snippet} -
+ + + {:else} + + + {/if} - {@const hasOtherClosable = tabs.some((t) => t.id !== tab.id && !t.pinned)} - {@const leftClosable = tabs.slice(0, i).filter((t) => !t.pinned)} - {@const rightClosable = tabs.slice(i + 1).filter((t) => !t.pinned)} +
+ {/each} +
+ {#if menuTab} + {@const tab = menuTab} + {@const i = tabs.findIndex((t) => t.id === tab.id)} + {@const hasOtherClosable = tabs.some((t) => t.id !== tab.id && !t.pinned)} + {@const leftClosable = tabs.slice(0, i).filter((t) => !t.pinned)} + {@const rightClosable = tabs.slice(i + 1).filter((t) => !t.pinned)} onpintoggle(tab.id)}> {#if tab.pinned} @@ -319,10 +378,34 @@ Close All Tabs + {/if} -
- {/each} +
+ + {#if fadeLeft || fadeRight} + + + + + + {#each tabs as tab (tab.id)} + onselect(tab.id)}> + + {tabDisplayTitle(tab)} + {#if tab.connLabel}{tab.connLabel}{/if} + {#if tab.id === activeTabId}{/if} + + {/each} + + + {/if} diff --git a/src/lib/components/TabLoading.svelte b/src/lib/components/TabLoading.svelte index abfd7e64..ca8907c9 100644 --- a/src/lib/components/TabLoading.svelte +++ b/src/lib/components/TabLoading.svelte @@ -9,7 +9,9 @@ // With no label there is nothing to read while the chunk lands - show a // credit instead, same pool the table loader draws from. - const message = label || nextLoadingMessage(EASTER_EGGS); + // A credit is picked once; a label passed later still shows. + const credit = nextLoadingMessage(EASTER_EGGS); + const message = $derived(label || credit); // Held back like the grid's loader: a chunk that lands in a frame or two // (most of them) never flashes a spinner and a line of text on its way past. diff --git a/src/lib/components/TableJsonView.svelte b/src/lib/components/TableJsonView.svelte index 0e735a06..962a1f86 100644 --- a/src/lib/components/TableJsonView.svelte +++ b/src/lib/components/TableJsonView.svelte @@ -276,7 +276,7 @@ {/if} {#if mode === 'tree'} -
+
+ // A table that failed to load, stated where its grid would be: what broke, + // why, and the action that fixes it (reconnect for a dropped pool, retry for + // everything else). Split out of StudioShell. + import AlertTriangle from '@lucide/svelte/icons/triangle-alert' + import WifiOff from '@lucide/svelte/icons/wifi-off' + import Unplug from '@lucide/svelte/icons/unplug' + import RefreshCw from '@lucide/svelte/icons/refresh-cw' + import { connectionErrorKind } from '$lib/utils.js' + import { humanizeDbError } from '$lib/db-error-text.js' + + let { + error = '', + connectionLost = false, + retrying = false, + onretry = () => {}, + ondismiss = () => {}, + } = $props() + + const kind = $derived(connectionErrorKind(error)) + const humanized = $derived(humanizeDbError(error)) + /** Showing the raw driver text. A new failure starts collapsed. */ + let showRawError = $state(false) + $effect(() => { void error; showRawError = false }) + + + + diff --git a/src/lib/components/TableRecordView.svelte b/src/lib/components/TableRecordView.svelte index 5cdd8981..2b0146ba 100644 --- a/src/lib/components/TableRecordView.svelte +++ b/src/lib/components/TableRecordView.svelte @@ -2,7 +2,7 @@ import FieldSelect from './FieldSelect.svelte'; import { untrack } from 'svelte' import Icon from './Icon.svelte' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' import { formatCellValue, anyDisplayExtEnabled } from '$lib/plugins/registry.js' import { pluginState } from '$lib/stores/plugins.js' @@ -14,6 +14,7 @@ import { isEditableType, isBooleanType, + asBooleanValue, getColumnEnumValues, valueToEditString, parseCellInput, @@ -49,6 +50,10 @@ /** @type {((detail: { rowIdx: number, colIdx: number, value: unknown }) => Promise) | null} */ onsave = null, readonly = false, + /** Load a cell the grid fetched as a size (a wide column's preview). @type {((detail: { rowIdx: number, colIdx: number }) => Promise) | null} */ + onloadvalue = null, + /** Bumped when a row changes in place (a loaded value): rows is not reactive per cell. */ + dataVersion = 0, } = $props() // svelte-ignore state_referenced_locally - the initial index deliberately @@ -177,7 +182,21 @@ } const extOn = $derived.by(() => { void $pluginState; return anyDisplayExtEnabled() }) + /** Past this, a value is shown cut (the field shows three lines anyway). */ + const DISPLAY_MAX = 4000 + /** + * Past this, a value is not edited in a field: a textarea handed megabytes + * does not paint. The table's cell panel (Space) edits values of any size. + */ + const INLINE_EDIT_MAX = 64 * 1024 + + /** @param {number} n */ + function sizeText(n) { + return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB` + } + const fields = $derived.by(() => { + void dataVersion if (columns.length === 0 || rows.length === 0) return [] const row = rows[idx] ?? [] const canEdit = !!onsave && primaryKey.length > 0 && !readonly @@ -185,16 +204,19 @@ const out = [] columns.forEach((col, i) => { if (hiddenColumns.has(col.name)) return - const raw = normalizeCellValue(row[i]) const dataType = col.dataType ?? col.data_type ?? '' + const raw = isBooleanType(dataType) ? asBooleanValue(normalizeCellValue(row[i])) : normalizeCellValue(row[i]) const normalType = normalizeColumnType(dataType) const enumValues = getColumnEnumValues(col) const isPk = pkSet.has(col.name) // Same rules as the row inspector: PKs, non-editable types and truncated // oversize cells stay read-only. - const editable = canEdit && !isPk && isEditableType(dataType) && !oversizeCellInfo(raw) + const over = oversizeCellInfo(raw) const isNull = raw === null const isEmpty = typeof raw === 'string' && raw === '' + const full = isNull ? 'NULL' : isEmpty ? 'EMPTY' : formatNormalValue(raw) + const tooBig = full.length > INLINE_EDIT_MAX + const editable = canEdit && !isPk && isEditableType(dataType) && !over && !tooBig out.push({ colIdx: i, name: col.name, @@ -202,8 +224,11 @@ raw, isNull, isEmpty, - displayValue: isNull ? 'NULL' : isEmpty ? 'EMPTY' : formatNormalValue(raw), - initialEditStr: valueToEditString(raw), + displayValue: full.length > DISPLAY_MAX ? `${full.slice(0, DISPLAY_MAX)}…` : full, + tooltip: full.length > 600 ? `${full.slice(0, 600)}…` : full, + oversize: !!over, + bigNote: tooBig ? `${sizeText(full.length)} · too large to edit here, Space in the table opens it in full` : '', + initialEditStr: editable ? valueToEditString(raw) : '', editable, isPk, isBoolean: isBooleanType(dataType), @@ -212,7 +237,7 @@ isJsonType: normalType.startsWith('json'), // Precomputed: this used to run a /\n/g match per field on every // render, allocating an array each time just to count lines. - textRows: Math.min(8, Math.max(2, (valueToEditString(raw).match(/\n/g)?.length ?? 0) + 1)), + textRows: editable ? Math.min(8, Math.max(2, (valueToEditString(raw).match(/\n/g)?.length ?? 0) + 1)) : 2, nullable: col.nullable !== false, hint: hintFor(raw, dataType, col.name, i, row), }) @@ -230,6 +255,21 @@ : fields, ) + /** @type {Record} */ + let loadingFields = $state({}) + /** Fetch a previewed value whole; the shell swaps it into the row. @param {number} colIdx */ + async function loadField(colIdx) { + if (!onloadvalue || loadingFields[colIdx]) return + loadingFields = { ...loadingFields, [colIdx]: true } + try { + await onloadvalue({ rowIdx: idx, colIdx }) + } catch (e) { + toast.error('Could not load the value', { description: errorText(e) }) + } finally { + loadingFields = { ...loadingFields, [colIdx]: false } + } + } + // ── Field editing (mirrors RowDetailPanel) ──────────────────────────────── /** @type {Record} */ let savingFields = $state({}) @@ -298,7 +338,7 @@ try { await onsave({ rowIdx: idx, colIdx, value }) } catch (e) { - toast.error(`Failed to save ${col.name}`, { description: String(e) }) + toast.error(`Failed to save ${col.name}`, { description: errorText(e) }) } finally { savingFields = { ...savingFields, [colIdx]: false } } @@ -429,7 +469,7 @@ aria-label="Search fields" bind:value={fieldSearch} onkeydown={(e) => { if (e.key === 'Escape' && fieldSearch) { e.preventDefault(); e.stopPropagation(); fieldSearch = '' } }} - class="field-surface h-8 w-full min-w-0 pl-8 pr-7 text-ui-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground" + class="search-box no-field-frame h-8 w-full min-w-0 pl-8 pr-7 text-ui-sm" /> {#if fieldSearch} {/if} {#if hiddenCount > 0} @@ -1204,7 +1226,7 @@ class="text-ui-2xs text-muted-foreground transition-colors hover:text-foreground" onclick={showAllColumns} > - Show all + {$tx('tb.showAll', 'Show all')} {/if}
@@ -1230,7 +1252,7 @@ onfocuscolumn(it.value)} > @@ -1238,7 +1260,7 @@ {/if} @@ -1324,9 +1346,9 @@ {#if total > 0 || counting || loading} - {total > 0 || counting ? to.toLocaleString("en-US") : "–"} + {total > 0 || counting ? loadedTo.toLocaleString("en-US") : "–"} of {#if counting || (loading && total === 0)}{:else}{total.toLocaleString("en-US")}{/if} loaded {/if} @@ -1340,7 +1362,7 @@ class={cn("mr-1 flex min-w-[18ch] shrink-0 items-center justify-end gap-1 font-mono text-ui-2xs tabular-nums @max-[37.5rem]/tb:hidden", hideAt(2))} title="{from.toLocaleString('en-US')}-{to.toLocaleString('en-US')} of {counting ? 'counting…' : total.toLocaleString('en-US') + ' rows'}{queryMs > 0 ? ` · ${queryMs}ms` : ''}" > - {total > 0 || counting ? `${from.toLocaleString("en-US")}-${to.toLocaleString("en-US")}` : "–"} + {(total > 0 || counting) && !(counting && loading && loaded === 0) ? `${from.toLocaleString("en-US")}-${to.toLocaleString("en-US")}` : "–"} {#if loading && total === 0 && !counting} of {:else if live && !counting} @@ -1355,19 +1377,21 @@
+ number in the toolbar is not a bare "1000". It and the pager stay + usable while rows load: picking another size starts a new load, + which cancels the one in flight on the server. Disabled, a slow + table left no way out but waiting. --> - {sizeShort(pageSize)}rows + {sizeShort(pageSize)}{$tx('table.rows', 'rows')} -

Rows per page

+

{$tx('tb.rowsPerPage', 'Rows per page')}

{#each PAGE_SIZE_OPTIONS as size (size)} - Enter to go - + + {$tx('tb.enterToGo', 'Enter to go')} +
{/if}
@@ -1509,7 +1533,7 @@ + >{$tx('common.cancel', 'Cancel')} +>{$tx('common.apply', 'Apply')}
@@ -1671,8 +1695,8 @@ {/if} {/snippet} @@ -1923,7 +1947,7 @@ {:else} pickFilterColumn(filter, it.value)} > diff --git a/src/lib/components/TerminalPage.svelte b/src/lib/components/TerminalPage.svelte index 88dd48ce..f3c93344 100644 --- a/src/lib/components/TerminalPage.svelte +++ b/src/lib/components/TerminalPage.svelte @@ -1,4 +1,5 @@ + +{#snippet option(/** @type {string} */ label, /** @type {string} */ hint, /** @type {boolean} */ checked, /** @type {(v: boolean) => void} */ set, /** @type {boolean} */ disabled = false)} + +{/snippet} + + { if (!v) close() }}> + + + {mode === 'export' ? 'Export connections and settings' : 'Import connections and settings'} + + {mode === 'export' + ? 'One file to set up Stroke on another computer. No account needed.' + : fileName ? fileName : 'Pick a file exported from Stroke.'} + + + +
+ {#if mode === 'export'} + {@render option('Connections', `${counts.connections} saved, with their workspaces`, parts.connections, (v) => (parts.connections = v), counts.connections === 0)} + {@render option('Saved queries', `${counts.queries} in the editor's Saved list`, parts.queries, (v) => (parts.queries = v), counts.queries === 0)} + {@render option('Settings', `Appearance, editor and grid, shortcuts, ${counts.aiProfiles} AI ${counts.aiProfiles === 1 ? 'model' : 'models'}, language`, parts.settings, (v) => (parts.settings = v))} + {@render option('SQL snippets', `${counts.snippets} of your own`, parts.snippets, (v) => (parts.snippets = v), counts.snippets === 0)} + +
+ + {#if parts.secrets} +
+ + +

{passError || 'Not stored anywhere: without it the passwords in the file cannot be read.'}

+
+ {/if} +
+ {:else if plan} + {@render option('Connections', plan.connections.length ? `${newCount} new${existingCount ? `, ${existingCount} already here` : ''}` : 'None in this file', take.connections, (v) => (take.connections = v), !plan.connections.length)} + {#if existingCount && take.connections} + + {/if} + {@render option('Saved queries', plan.queries ? `${plan.queries} in the file` : 'None in this file', take.queries, (v) => (take.queries = v), !plan.queries)} + {@render option('Settings', plan.settings ? 'Replaces appearance, editor, shortcuts, AI models and language here' : 'None in this file', take.settings, (v) => (take.settings = v), !plan.settings)} + {@render option('SQL snippets', plan.snippets ? `${plan.snippets} in the file; the same name and trigger updates yours` : 'None in this file', take.snippets, (v) => (take.snippets = v), !plan.snippets)} + {#if plan.encrypted} +
+

Passwords and keys are encrypted

+ { if (e.key === 'Enter') void doImport() }} /> +

Leave it empty to import everything else without them.

+
+ {/if} + {:else} +
+ +

{importError || 'Choose a file to see what it holds before anything changes.'}

+ +
+ {/if} + {#if mode === 'import' && plan && importError} +

{importError}

+ {/if} +
+ + + {#if mode === 'import' && plan} + + {/if} + + {#if mode === 'export'} + + {:else} + + {/if} + +
+
diff --git a/src/lib/components/TrialExpiredScreen.svelte b/src/lib/components/TrialExpiredScreen.svelte index e477acc1..f23617e9 100644 --- a/src/lib/components/TrialExpiredScreen.svelte +++ b/src/lib/components/TrialExpiredScreen.svelte @@ -114,7 +114,7 @@ >
-
+
@@ -181,7 +181,7 @@ Connections and settings stay on this device.

- {/if} @@ -189,7 +189,7 @@
-
+
diff --git a/src/lib/components/UpdateDialog.svelte b/src/lib/components/UpdateDialog.svelte index 0690caab..78894133 100644 --- a/src/lib/components/UpdateDialog.svelte +++ b/src/lib/components/UpdateDialog.svelte @@ -138,7 +138,7 @@ * The update's notes as releases: Nightly's feed carries CHANGELOG.md * sections for several versions (## [x.y.z]); a stable release carries one * version's sections without the heading. - * @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number }} + * @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number, versions?: number }} */ const notes = $derived.by(() => { const many = parseReleases(releaseNotes) @@ -146,7 +146,7 @@ // The feed carries the whole recent changelog. Only what this install // has not got yet: the versions after the running one, up to the update. if (appVersion) { - const between = releasesInRange(many, appVersion, updateVersion, 8) + const between = releasesInRange(many, appVersion, updateVersion, 8, { merge: true }) if (between.releases.length) return between } const own = many.filter((r) => r.version === updateVersion.replace(/-.*$/, '')) @@ -215,6 +215,8 @@ /** @type {import('$lib/changelog.js').ChangelogRelease[]} */ releases: [], omitted: 0, + /** Versions the notes cover (several merged into one release on a long jump). */ + versions: 0, /** @type {import('$lib/whats-new.js').Highlight[]} */ highlights: [], }) @@ -247,7 +249,7 @@ const base = current.replace(/-.*$/, '') const [maj, min] = base.split('.').map(Number) const previous = min > 0 ? `${maj}.${min - 1}.99` : `${Math.max(0, maj - 1)}.99.99` - /** @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number }} */ + /** @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number, versions?: number }} */ let notes = { releases: [], omitted: 0 } try { const { default: markdown } = await import('../../../CHANGELOG.md?raw') @@ -277,11 +279,12 @@ } if (!previous || previous === current) return - /** @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number }} */ + /** @type {{ releases: import('$lib/changelog.js').ChangelogRelease[], omitted: number, versions?: number }} */ let notes = { releases: [], omitted: 0 } try { const { default: markdown } = await import('../../../CHANGELOG.md?raw') - notes = releasesBetween(markdown, previous, current, 8) + // A long jump (stable to stable) as one merged list: see releasesInRange. + notes = releasesBetween(markdown, previous, current, 8, { merge: true }) } catch (e) { console.error('[updater] changelog unavailable:', e) } @@ -522,6 +525,7 @@ previous={whatsNew.previous} releases={whatsNew.releases} omitted={whatsNew.omitted} + versions={whatsNew.versions} highlights={whatsNew.highlights} onaction={onwhatsnewaction} onfullchangelog={() => void openChangelog('whats-new')} diff --git a/src/lib/components/UrlPreviewTooltip.svelte b/src/lib/components/UrlPreviewTooltip.svelte index d7938901..87961541 100644 --- a/src/lib/components/UrlPreviewTooltip.svelte +++ b/src/lib/components/UrlPreviewTooltip.svelte @@ -54,7 +54,7 @@
{#if !imgLoaded && !imgError} -
+
@@ -72,7 +72,7 @@
{/if} {#if imgError} -
+
Could not load image
@@ -80,7 +80,7 @@ { imgLoaded = true }} diff --git a/src/lib/components/VacuumGame.svelte b/src/lib/components/VacuumGame.svelte index 429f3f70..56cedff5 100644 --- a/src/lib/components/VacuumGame.svelte +++ b/src/lib/components/VacuumGame.svelte @@ -343,7 +343,7 @@

{game.over.reason}

{game.over.detail}

- {game.score} reclaimed{#if game.score >= best && game.score > 0} · new best{/if} + {game.score} reclaimed{#if game.score >= best && game.score > 0}{' '}· new best{/if}

space to run again diff --git a/src/lib/components/VectorCellViewer.svelte b/src/lib/components/VectorCellViewer.svelte index 230831f4..f0f30c54 100644 --- a/src/lib/components/VectorCellViewer.svelte +++ b/src/lib/components/VectorCellViewer.svelte @@ -13,7 +13,7 @@ import { Button } from '$lib/components/ui/button/index.js' import { toast } from '$lib/components/ui/sonner/toast.svelte.js' import { parseVector, vectorBars, vectorHistogram, short } from '$lib/vector-cell.js' - import { cn } from '$lib/utils.js' + import { cn, errorText } from '$lib/utils.js' let { open = $bindable(false), @@ -79,7 +79,7 @@ await navigator.clipboard.writeText(String(value ?? '')) toast.success(`Copied ${info ? `${info.dim} values` : 'value'}`) } catch (e) { - toast.error('Could not copy', { description: String(e) }) + toast.error('Could not copy', { description: errorText(e) }) } } diff --git a/src/lib/components/VirtualColumnsPanel.svelte b/src/lib/components/VirtualColumnsPanel.svelte index 326b2452..896b97b0 100644 --- a/src/lib/components/VirtualColumnsPanel.svelte +++ b/src/lib/components/VirtualColumnsPanel.svelte @@ -135,7 +135,7 @@ title={tableName} class="ml-auto min-w-0 truncate rounded bg-muted/60 px-1.5 py-0.5 font-mono text-ui-2xs text-muted-foreground" >{tableName} -

- -
{/if} {/if} - {#if rest.length} + {#snippet featureList(/** @type {import('$lib/whats-new.js').Highlight[]} */ items)} -
    - {#each rest as h (h.id)} -
  • +
      + {#each items as h (h.id)} +
    • -

      {h.title}

      +

      + {h.title} + {#if h.beta}Labs{/if} +

      {h.body}

      {#if h.action} - {/if}
    • {/each}
    + {/snippet} + + {#if leadWithHighlights && rest.length} +
    {@render featureList(rest)}
    {/if} {#if releases.length} - {#if highlights.length} - - - {/if} - {#if notesOpen} -
    + {#if leadWithHighlights} +

    All changes

    {/if} + + {/if} + + {#if !leadWithHighlights && rest.length} +

    Worth trying

    + {@render featureList(rest)} {/if}

- {#if changeCount}{`${changeCount} ${changeCount === 1 ? 'change' : 'changes'}${releases.length > 1 ? ` across ${releases.length} versions` : ''}`}{/if} + {#if changeCount}{`${changeCount} ${changeCount === 1 ? 'change' : 'changes'}${spanned > 1 ? ` across ${spanned} versions` : ''}`}{/if}

- +
diff --git a/src/lib/components/WorkspaceSwitcher.svelte b/src/lib/components/WorkspaceSwitcher.svelte index db0d5f98..26806006 100644 --- a/src/lib/components/WorkspaceSwitcher.svelte +++ b/src/lib/components/WorkspaceSwitcher.svelte @@ -30,6 +30,9 @@ let managerOpen = $state(false) let editing = $state(/** @type {import('$lib/stores/workspaces.js').Workspace | null} */ (null)) + /** "1 connection", "40 connections". @param {number} n */ + const countLabel = (n) => `${n} connection${n === 1 ? '' : 's'}` + /** @param {import('$lib/stores/workspaces.js').Workspace | null} w */ function openDialog(w) { editing = w @@ -41,11 +44,18 @@ @@ -57,8 +67,8 @@ class={compact ? 'transition-[scale,filter] duration-150 ease-out group-hover:brightness-110 group-hover:ring-2 group-hover:ring-foreground/15 group-active:scale-90 group-data-[state=open]:ring-2 group-data-[state=open]:ring-ring/50' : ''} /> {#if !compact}{active?.name}{/if} - {#if !compact}{count}{/if} - {#if !compact}{/if} + {#if !compact}{/if} + {#if !compact}{/if} {#each $workspaces as w (w.id)} @@ -67,7 +77,7 @@ {w.name} - {inWorkspace(connections, w.id, $workspaces).length} + {inWorkspace(connections, w.id, $workspaces).length} diff --git a/src/lib/components/WorkspacesManager.svelte b/src/lib/components/WorkspacesManager.svelte index 9d779405..49333d10 100644 --- a/src/lib/components/WorkspacesManager.svelte +++ b/src/lib/components/WorkspacesManager.svelte @@ -71,7 +71,7 @@ aria-label="Search workspaces" spellcheck="false" autocomplete="off" - class="peer field-surface h-8 w-full rounded-lg bg-input/30 pl-8 pr-2 text-ui-sm text-foreground placeholder:text-muted-foreground" + class="peer search-box no-field-frame w-full pl-8 pr-8 text-ui-sm" />
diff --git a/src/lib/components/ZoomIndicator.svelte b/src/lib/components/ZoomIndicator.svelte new file mode 100644 index 00000000..705a5b18 --- /dev/null +++ b/src/lib/components/ZoomIndicator.svelte @@ -0,0 +1,62 @@ + + +{#if shown} +
{ hovered = true; clearTimeout(timer) }} + onpointerleave={() => { hovered = false; hideLater() }} + > + {Math.round(level * 100)}% + {#if level !== 1} + + {/if} +
+{/if} diff --git a/src/lib/components/component-imports.test.js b/src/lib/components/component-imports.test.js index 7251c189..53493cd7 100644 --- a/src/lib/components/component-imports.test.js +++ b/src/lib/components/component-imports.test.js @@ -96,9 +96,12 @@ describe('rendered components are in scope', () => { expect(undeclared(parse(src, { modern: true }))).toEqual(['Icon']) }) + // Parsing and walking a file takes time in proportion to its size, and + // StudioShell (12k lines) took ~4.9s of vitest's 5s default on its own: + // any edit to it timed the check out while it still passed. for (const f of files) { it(f.slice(process.cwd().length + 1), () => { expect(undeclared(parse(readFileSync(f, 'utf8'), { modern: true }))).toEqual([]) - }) + }, 20_000) } }) diff --git a/src/lib/components/notebook/MarkdownCell.svelte b/src/lib/components/notebook/MarkdownCell.svelte index 14abcaaa..18f4b40a 100644 --- a/src/lib/components/notebook/MarkdownCell.svelte +++ b/src/lib/components/notebook/MarkdownCell.svelte @@ -1,4 +1,5 @@