From ffce4a97a339853a4b9be760aca6388c67374dd5 Mon Sep 17 00:00:00 2001 From: broisnischal Date: Tue, 23 Jun 2026 17:18:03 +0545 Subject: [PATCH 1/6] chore::a lot of things is going good and i like that --- package-lock.json | 347 ++++++++++++++++++++- package.json | 3 +- src/App.svelte | 9 +- src/lib/components/AppErrorBoundary.svelte | 45 +++ src/lib/table-query.test.js | 114 +++++++ vitest.config.js | 10 + 6 files changed, 523 insertions(+), 5 deletions(-) create mode 100644 src/lib/components/AppErrorBoundary.svelte create mode 100644 src/lib/table-query.test.js create mode 100644 vitest.config.js diff --git a/package-lock.json b/package-lock.json index 56a26bd5..20c41b5b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,8 @@ "cross-env": "^10.1.0", "mode-watcher": "^1.1.0", "svelte": "^5.55.5", - "vite": "^8.0.12" + "vite": "^8.0.12", + "vitest": "^4.1.9" } }, "node_modules/@antfu/install-pkg": { @@ -657,6 +658,13 @@ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", "license": "MIT" }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, "node_modules/@svelte-put/shortcut": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/@svelte-put/shortcut/-/shortcut-4.1.0.tgz", @@ -1317,6 +1325,17 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/d3": { "version": "7.4.3", "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", @@ -1570,6 +1589,13 @@ "@types/d3-selection": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -1628,6 +1654,119 @@ "d3-transition": "^3.0.1" } }, + "node_modules/@vitest/expect": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz", + "integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.9.tgz", + "integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.9", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.9.tgz", + "integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.9.tgz", + "integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.9", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.9.tgz", + "integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.9", + "@vitest/utils": "4.1.9", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.9.tgz", + "integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.9.tgz", + "integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.9", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xyflow/svelte": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@xyflow/svelte/-/svelte-1.5.2.tgz", @@ -1686,6 +1825,16 @@ "node": ">= 0.4" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/axobject-query": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", @@ -1749,6 +1898,16 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/character-entities-html4": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", @@ -1806,6 +1965,13 @@ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "license": "MIT" }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, "node_modules/cose-base": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz", @@ -2491,6 +2657,13 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-module-lexer": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", + "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "dev": true, + "license": "MIT" + }, "node_modules/es-toolkit": { "version": "1.47.0", "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.47.0.tgz", @@ -2524,6 +2697,26 @@ } } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -3353,6 +3546,13 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -3607,6 +3807,13 @@ "node": ">=20" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/slot-text": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/slot-text/-/slot-text-0.2.2.tgz", @@ -3657,6 +3864,20 @@ "sql-formatter": "bin/sql-formatter-cli.cjs" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", + "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -3796,6 +4017,13 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, "node_modules/tinyexec": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz", @@ -3821,6 +4049,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -4062,6 +4300,96 @@ } } }, + "node_modules/vitest": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.9.tgz", + "integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.9", + "@vitest/mocker": "4.1.9", + "@vitest/pretty-format": "4.1.9", + "@vitest/runner": "4.1.9", + "@vitest/snapshot": "4.1.9", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.9", + "@vitest/browser-preview": "4.1.9", + "@vitest/browser-webdriverio": "4.1.9", + "@vitest/coverage-istanbul": "4.1.9", + "@vitest/coverage-v8": "4.1.9", + "@vitest/ui": "4.1.9", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -4078,6 +4406,23 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "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 1e8c91ce..fcf647d3 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,8 @@ "cross-env": "^10.1.0", "mode-watcher": "^1.1.0", "svelte": "^5.55.5", - "vite": "^8.0.12" + "vite": "^8.0.12", + "vitest": "^4.1.9" }, "dependencies": { "@dagrejs/dagre": "^3.0.0", diff --git a/src/App.svelte b/src/App.svelte index 92de490b..6b8f2d93 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -3,6 +3,7 @@ import { Toaster } from '$lib/components/ui/sonner/index.js' import StudioShell from './lib/components/StudioShell.svelte' import LicenseGate from './lib/components/LicenseGate.svelte' + import AppErrorBoundary from './lib/components/AppErrorBoundary.svelte' import { loadSettings, applySettings, installZoomShortcuts } from '$lib/stores/settings.js' import { installPlatformClass } from '$lib/platform.js' @@ -41,6 +42,8 @@ - - - + + + + + diff --git a/src/lib/components/AppErrorBoundary.svelte b/src/lib/components/AppErrorBoundary.svelte new file mode 100644 index 00000000..181f3274 --- /dev/null +++ b/src/lib/components/AppErrorBoundary.svelte @@ -0,0 +1,45 @@ + + + { try { console.error('[app-boundary]', e) } catch { /* noop */ } }}> + {@render children()} + + {#snippet failed(error, reset)} +
+
+ +
+ +
+

Something went wrong

+

+ The interface hit an unexpected error. Try to recover, or reload — your + connections and data are safe. +

+
+ +
{String(/** @type {any} */ (error)?.message ?? error)}
+ +
+ + +
+
+ {/snippet} +
diff --git a/src/lib/table-query.test.js b/src/lib/table-query.test.js new file mode 100644 index 00000000..b6ab64bc --- /dev/null +++ b/src/lib/table-query.test.js @@ -0,0 +1,114 @@ +import { describe, it, expect } from 'vitest' +import { + activeFilters, + filtersForApi, + sortForApi, + hasTableQuery, + buildSelectSql, + createFilter, + ANY_COLUMN, +} from './table-query.js' + +/** @param {Partial} f */ +const mk = (f) => ({ ...createFilter('col', 'eq'), ...f }) + +describe('activeFilters', () => { + it('drops filters with no column', () => { + expect(activeFilters([mk({ column: '', value: 'x' })])).toHaveLength(0) + }) + + it('drops value-requiring filters with empty value', () => { + expect(activeFilters([mk({ op: 'eq', value: ' ' })])).toHaveLength(0) + }) + + it('keeps null-check ops without a value', () => { + expect(activeFilters([mk({ op: 'is_null', value: '' })])).toHaveLength(1) + }) + + it('requires a value for ANY_COLUMN search', () => { + expect(activeFilters([mk({ column: ANY_COLUMN, op: 'contains', value: '' })])).toHaveLength(0) + expect(activeFilters([mk({ column: ANY_COLUMN, op: 'contains', value: 'hi' })])).toHaveLength(1) + }) +}) + +describe('filtersForApi', () => { + it('omits the conjunct on the first filter and attaches dataType', () => { + const out = filtersForApi( + [mk({ column: 'a', op: 'eq', value: '1' }), mk({ column: 'b', op: 'eq', value: '2', conjunct: 'or' })], + [{ name: 'a', dataType: 'int4' }, { name: 'b', dataType: 'text' }], + ) + expect(out[0].conjunct).toBeUndefined() + expect(out[0].dataType).toBe('int4') + expect(out[1].conjunct).toBe('or') + }) +}) + +describe('sortForApi', () => { + it('returns undefined fields for null sort', () => { + expect(sortForApi(null)).toEqual({ sortColumn: undefined, sortDirection: undefined }) + }) + it('maps column + direction', () => { + expect(sortForApi({ column: 'created_at', direction: 'desc' })).toEqual({ + sortColumn: 'created_at', + sortDirection: 'desc', + }) + }) +}) + +describe('hasTableQuery', () => { + it('is false when nothing is set', () => { + expect(hasTableQuery('', [], null)).toBe(false) + }) + it('is true for a search term, a filter, or a sort', () => { + expect(hasTableQuery('foo', [], null)).toBe(true) + expect(hasTableQuery('', [mk({ value: '1' })], null)).toBe(true) + expect(hasTableQuery('', [], { column: 'a', direction: 'asc' })).toBe(true) + }) +}) + +describe('buildSelectSql', () => { + it('builds a minimal SELECT with quoting and limit', () => { + expect(buildSelectSql({ schema: 'public', table: 'users', engine: 'postgres', limit: 100 })) + .toBe('SELECT *\nFROM "public"."users"\nLIMIT 100;') + }) + + it('escapes single quotes in values', () => { + const sql = buildSelectSql({ + table: 't', + engine: 'postgres', + filters: [mk({ column: 'name', op: 'eq', value: "O'Brien" })], + }) + expect(sql).toContain(`"name" = 'O''Brien'`) + }) + + it('emits WHERE (search OR-group) AND filters, ORDER BY and engine quoting', () => { + const sql = buildSelectSql({ + schema: 'public', + table: 'users', + columns: [{ name: 'id' }, { name: 'email' }], + engine: 'postgres', + search: 'acme', + filters: [ + mk({ column: 'email', op: 'contains', value: '@x.com' }), + mk({ column: 'id', op: 'gt', value: '100', conjunct: 'and' }), + ], + sort: { column: 'id', direction: 'desc' }, + limit: 50, + }) + expect(sql).toContain('WHERE ("id"::text ILIKE \'%acme%\' OR "email"::text ILIKE \'%acme%\')') + expect(sql).toContain('"email"::text ILIKE \'%@x.com%\'') + expect(sql).toContain('"id" > \'100\'') + expect(sql).toContain('ORDER BY "id" DESC') + expect(sql.endsWith('LIMIT 50;')).toBe(true) + }) + + it('uses backtick quoting and LIKE for MySQL', () => { + const sql = buildSelectSql({ + table: 'orders', + engine: 'mysql', + filters: [mk({ column: 'status', op: 'is_null', value: '' })], + }) + expect(sql).toContain('FROM `orders`') + expect(sql).toContain('`status` IS NULL') + }) +}) diff --git a/vitest.config.js b/vitest.config.js new file mode 100644 index 00000000..4525f9a6 --- /dev/null +++ b/vitest.config.js @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config' + +// Pure-logic unit tests run in a Node environment — no Svelte compilation or DOM +// needed for the modules under test (table-query, table-list, studio-tabs, format-sql). +export default defineConfig({ + test: { + environment: 'node', + include: ['src/**/*.test.js'], + }, +}) From c67252d6a2eac846a20f44bd70c145d69d4f70c8 Mon Sep 17 00:00:00 2001 From: broisnischal Date: Tue, 23 Jun 2026 22:44:42 +0545 Subject: [PATCH 2/6] feat:: smooth fps scrolling --- package-lock.json | 13 +--- src-tauri/src/commands.rs | 12 +++ src-tauri/src/db/connection.rs | 7 +- src-tauri/src/db/query.rs | 92 ++++++++++++++--------- src-tauri/src/lib.rs | 6 +- src/app.css | 8 ++ src/lib/api.js | 5 ++ src/lib/components/AiSidebar.svelte | 2 +- src/lib/components/ConnectionModal.svelte | 18 +++++ src/lib/components/DataTable.svelte | 68 ++++++++++++----- src/lib/components/SqlConsole.svelte | 38 +++++++--- src/lib/components/StudioShell.svelte | 64 ++++++++++++---- src/lib/stores/connections.js | 1 + 13 files changed, 240 insertions(+), 94 deletions(-) diff --git a/package-lock.json b/package-lock.json index 20c41b5b..7353e0a0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -100,7 +100,6 @@ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" @@ -112,7 +111,6 @@ "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -208,7 +206,6 @@ "resolved": "https://registry.npmjs.org/@internationalized/date/-/date-3.12.1.tgz", "integrity": "sha512-6IedsVWXyq4P9Tj+TxuU8WGWM70hYLl12nbYU8jkikVpa6WXapFazPUcHUMDMoWftIDE2ILDkFFte6W2nFCkRQ==", "license": "Apache-2.0", - "peer": true, "dependencies": { "@swc/helpers": "^0.5.0" } @@ -1802,7 +1799,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -2019,7 +2015,6 @@ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.4.tgz", "integrity": "sha512-HIN5Pmd9MrX9BkV7tDwnOcEJCSFvCpc8X97h3f508J6I5FsqAY65wKOCvgH2CuP42CaahWaz4tuh32SOOIH7ww==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10" } @@ -2429,7 +2424,6 @@ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", "license": "ISC", - "peer": true, "engines": { "node": ">=12" } @@ -3564,7 +3558,6 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -3912,7 +3905,6 @@ "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.55.9.tgz", "integrity": "sha512-fTjjT8cHLDwigcu2j3pv7Jq04LklXevPB8uBgyHNiTXv+RMNvVnrjS4UEYrLMkhuq1vpCodHjiW+z/95SDs/fg==", "license": "MIT", - "peer": true, "dependencies": { "@jridgewell/remapping": "^2.3.4", "@jridgewell/sourcemap-codec": "^1.5.0", @@ -3972,7 +3964,6 @@ "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.6.0.tgz", "integrity": "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==", "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/dcastil" @@ -4001,8 +3992,7 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.0.tgz", "integrity": "sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.3.3", @@ -4207,7 +4197,6 @@ "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.14.tgz", "integrity": "sha512-s4BJJ+5y1pYL6Otw51FHhVJQhPnuRinKig64g/1+EUNaJsd3gCKdD31IPFvswUgW9/60QT9oFHbZHbQK5imcxw==", "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 84ef9db7..bfeab69a 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -523,6 +523,18 @@ pub async fn pg_insert_table_row( insert_table_row(state, schema, table, values).await } +// ── Cancel running query ────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn cancel_query(state: State<'_, DbState>) -> Result<(), String> { + if let Ok(mut guard) = state.cancel_tx.lock() { + if let Some(tx) = guard.take() { + let _ = tx.send(()); + } + } + Ok(()) +} + // ── License ─────────────────────────────────────────────────────────────────── #[tauri::command] diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index e81ecd84..3034fded 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -7,6 +7,7 @@ use sqlx::{ConnectOptions, MySqlPool, PgPool, SqlitePool}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tauri::State; +use tokio::sync::oneshot; use super::ssh_tunnel::{SshConfig, SshTunnel, TunnelState}; @@ -228,11 +229,15 @@ impl ActiveConnection { pub struct DbState { pub conn: Arc>>, + pub cancel_tx: Arc>>>, } impl Default for DbState { fn default() -> Self { - Self { conn: Arc::new(Mutex::new(None)) } + Self { + conn: Arc::new(Mutex::new(None)), + cancel_tx: Arc::new(Mutex::new(None)), + } } } diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index ab65ac8d..d46e2da7 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -1632,20 +1632,30 @@ pub async fn execute_ddl(state: State<'_, DbState>, sql: String) -> Result<(), S } pub async fn execute_sql(state: State<'_, DbState>, sql: String) -> Result { - let sql_str = sql.trim(); + let sql_str = sql.trim().to_string(); if sql_str.is_empty() { return Err("Query is empty".into()); } - match require_conn(&state)? { - ActiveConnection::Postgres(pool) => execute_sql_pg(&pool, sql_str).await, - 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::Mysql(pool) => super::mysql::execute_sql(&pool, sql_str).await, - ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(&cfg, 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, - } + let conn = require_conn(&state)?; + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + *state.cancel_tx.lock().map_err(|e| e.to_string())? = Some(cancel_tx); + let result = tokio::select! { + r = async move { + match conn { + ActiveConnection::Postgres(pool) => execute_sql_pg(&pool, &sql_str).await, + 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::Mysql(pool) => super::mysql::execute_sql(&pool, &sql_str).await, + ActiveConnection::Clickhouse(cfg) => super::clickhouse::query(&cfg, &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, + } + } => r, + _ = async { let _ = cancel_rx.await; } => Err("Query cancelled".to_string()), + }; + if let Ok(mut guard) = state.cancel_tx.lock() { *guard = None; } + result } /// Execute a SQL query against an arbitrary saved connection without changing @@ -1920,34 +1930,44 @@ async fn execute_sql_multi_pg(pool: &sqlx::PgPool, sql: &str) -> Result, sql: String) -> Result, String> { - let sql_str = sql.trim(); + let sql_str = sql.trim().to_string(); if sql_str.is_empty() { return Err("Query is empty".into()); } - match require_conn(&state)? { - ActiveConnection::Postgres(pool) => execute_sql_multi_pg(&pool, sql_str).await, - ActiveConnection::Sqlite(pool) => { - super::sqlite::execute_sql(&pool, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::D1(cfg) => { - super::d1::query(&cfg, sql_str, vec![]).await.map(|r| vec![r]) - } - ActiveConnection::LibSql(cfg) => { - super::libsql::query(&cfg, sql_str, vec![]).await.map(|r| vec![r]) - } - ActiveConnection::Mysql(pool) => { - super::mysql::execute_sql(&pool, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Clickhouse(cfg) => { - super::clickhouse::query(&cfg, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Duckdb(h) => { - super::duckdb::execute_sql(&h, sql_str).await.map(|r| vec![r]) - } - ActiveConnection::Mssql(h) => { - super::mssql::execute_sql(&h, sql_str).await.map(|r| vec![r]) - } - } + let conn = require_conn(&state)?; + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + *state.cancel_tx.lock().map_err(|e| e.to_string())? = Some(cancel_tx); + let result = tokio::select! { + r = async move { + match conn { + ActiveConnection::Postgres(pool) => execute_sql_multi_pg(&pool, &sql_str).await, + ActiveConnection::Sqlite(pool) => { + super::sqlite::execute_sql(&pool, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::D1(cfg) => { + super::d1::query(&cfg, &sql_str, vec![]).await.map(|r| vec![r]) + } + ActiveConnection::LibSql(cfg) => { + super::libsql::query(&cfg, &sql_str, vec![]).await.map(|r| vec![r]) + } + ActiveConnection::Mysql(pool) => { + super::mysql::execute_sql(&pool, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Clickhouse(cfg) => { + super::clickhouse::query(&cfg, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Duckdb(h) => { + super::duckdb::execute_sql(&h, &sql_str).await.map(|r| vec![r]) + } + ActiveConnection::Mssql(h) => { + super::mssql::execute_sql(&h, &sql_str).await.map(|r| vec![r]) + } + } + } => r, + _ = async { let _ = cancel_rx.await; } => Err("Query cancelled".to_string()), + }; + if let Ok(mut guard) = state.cancel_tx.lock() { *guard = None; } + result } // ── D1 helpers (thin wrappers that build SQLite-compatible SQL) ─────────────── diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc7655bc..482dd769 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -57,7 +57,10 @@ pub fn run() { let _ = metrics::set_process_title("stroke".into()); // Create the shared connection Arc — both DbState and McpState point to the same lock. let db_conn: Arc>> = Arc::new(Mutex::new(None)); - let db_state = DbState { conn: Arc::clone(&db_conn) }; + let db_state = DbState { + conn: Arc::clone(&db_conn), + cancel_tx: Arc::new(std::sync::Mutex::new(None)), + }; let mcp_state = McpState::new(db_conn); tauri::Builder::default() @@ -302,6 +305,7 @@ pub fn run() { commands::enable_autostart, commands::disable_autostart, commands::get_autostart_status, + commands::cancel_query, #[cfg(debug_assertions)] commands::debug_set_trial_days_ago, #[cfg(debug_assertions)] diff --git a/src/app.css b/src/app.css index 53cdce51..e6a82bfc 100644 --- a/src/app.css +++ b/src/app.css @@ -519,6 +519,14 @@ html[data-os="linux"] { --window-radius: 8px; } } } + /* Canvas table: promote scroll container to a compositing layer so WebKit's + CADisplayLink runs at the display's native rate (120Hz on ProMotion) instead + of the default 60Hz timer path. will-change:scroll-position does NOT create + a new stacking context, so position:sticky inside is unaffected. */ + [data-canvas-table] { + will-change: scroll-position; + } + /* Minimal thin scrollbars — all platforms */ :is(.app-scroll, .overflow-auto, .overflow-y-auto, .overflow-x-auto) { scrollbar-width: thin; diff --git a/src/lib/api.js b/src/lib/api.js index 70a15c36..e1b608a9 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -442,6 +442,11 @@ export async function getColumnStats(schema, table, column) { } } +/** Cancel the currently-running SQL query (no-op if none is running). */ +export async function cancelQuery() { + return inv('cancel_query') +} + /** @param {string} sql */ export async function executeSql(sql) { try { diff --git a/src/lib/components/AiSidebar.svelte b/src/lib/components/AiSidebar.svelte index c583e7e1..e8abb89e 100644 --- a/src/lib/components/AiSidebar.svelte +++ b/src/lib/components/AiSidebar.svelte @@ -624,7 +624,7 @@ -
+
Assistant diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 5720d667..ee101660 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -17,6 +17,7 @@ import Server from '@lucide/svelte/icons/server' import FolderOpen from '@lucide/svelte/icons/folder-open' import Terminal from '@lucide/svelte/icons/terminal' + import Lock from '@lucide/svelte/icons/lock' import ChevronDown from '@lucide/svelte/icons/chevron-down' import Check from '@lucide/svelte/icons/check' import CloudflareLogin from './CloudflareLogin.svelte' @@ -139,6 +140,9 @@ let connectionUri = $state('') let uriHint = $state('') + // ── Connection options ─────────────────────────────────────────────────────── + let readOnly = $state(false) + // ── SSH tunnel state ───────────────────────────────────────────────────────── let sshEnabled = $state(false) let sshHost = $state('') @@ -216,6 +220,7 @@ const s = conn.ssh sshEnabled = !!s?.host; sshHost = s?.host ?? ''; sshPort = String(s?.port ?? 22) sshUsername = s?.username ?? ''; sshKeyPath = s?.privateKeyPath ?? '' + readOnly = conn.readOnly ?? false } else { dbType = 'postgres'; name = ''; host = '127.0.0.1'; port = '5432' database = 'postgres'; user = 'postgres'; password = ''; ssl = false; secure = false @@ -223,6 +228,7 @@ filePath = ''; accountId = ''; databaseId = ''; apiToken = '' libsqlUrl = ''; libsqlToken = '' sshEnabled = false; sshHost = ''; sshPort = '22'; sshUsername = ''; sshKeyPath = '' + readOnly = false } error = ''; testOk = false; connectionUri = ''; uriHint = '' d1Reset() @@ -354,6 +360,7 @@ id, ...payload, port: hasHostPort ? (Number(payload.port) || defaultPort) : undefined, lastConnectedAt: Date.now(), + readOnly: readOnly || undefined, } saved = upsertConnection(saved_conn).sort((a, b) => (b.lastConnectedAt ?? 0) - (a.lastConnectedAt ?? 0)) setLastConnectionId(id) @@ -956,6 +963,17 @@
+ +
+ +
+
{#if error} diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index 6f85c117..30960056 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -23,6 +23,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; import ChevronDown from "@lucide/svelte/icons/chevron-down"; import ChevronsDownUp from "@lucide/svelte/icons/chevrons-down-up"; import Copy from "@lucide/svelte/icons/copy"; + import CopyPlus from "@lucide/svelte/icons/copy-plus"; import Pencil from "@lucide/svelte/icons/pencil"; import CircleSlash from "@lucide/svelte/icons/circle-slash"; import Trash2 from "@lucide/svelte/icons/trash-2"; @@ -945,9 +946,13 @@ import FilterX from "@lucide/svelte/icons/filter-x"; toast.error('Cannot insert row', { description: built.message }) return } - await oninsertrow(/** @type {Record} */ (built.values)) - newRowDrafts = null - newRowFocusCol = null + try { + await oninsertrow(/** @type {Record} */ (built.values)) + newRowDrafts = null + newRowFocusCol = null + } catch { + // error toast already shown by oninsertrow + } } /** @param {string} colName @param {string} value */ @@ -1192,6 +1197,20 @@ import FilterX from "@lucide/svelte/icons/filter-x"; } } + /** @param {number} rowIdx */ + async function duplicateRow(rowIdx) { + if (readonly) return; + const row = rows[rowIdx]; + if (!row) return; + const record = rowToRecord(columns, row); + for (const pk of primaryKey) delete record[pk]; + try { + await oninsertrow(record); + } catch { + // error toast already shown by oninsertrow + } + } + /** @param {number} rowIdx @param {number} colIdx @param {'down'|'right'|'left'} action @param {boolean} [autoEdit] */ function navigateAfterEdit(rowIdx, colIdx, action, autoEdit = false) { const visColIdx = actualToVisColIdx(colIdx); @@ -2946,6 +2965,25 @@ import FilterX from "@lucide/svelte/icons/filter-x"; if (_resizeRafId) cancelAnimationFrame(_resizeRafId) }) + // Shift+wheel → horizontal scroll. Non-passive so we can call preventDefault, + // but bails out immediately on non-Shift events so the compositor waits <0.05ms. + // Registered via $effect (not onwheel attribute) to keep the Svelte template + // free of any non-passive wheel binding, which would otherwise force the + // compositor to consult JS on every 120Hz trackpad tick. + $effect(() => { + const el = tableContainer + if (!el) return + const onShiftWheel = (/** @type {WheelEvent} */ e) => { + if (!e.shiftKey) return + if (e.deltaY || e.deltaX) { + e.preventDefault() + el.scrollLeft += e.deltaY || e.deltaX + } + } + el.addEventListener('wheel', onShiftWheel, { passive: false }) + return () => el.removeEventListener('wheel', onShiftWheel) + }) + // Layout / sizing effect — resize the backing store when geometry or viewport changes. $effect(() => { void rows; void columns; void columnWidths @@ -3427,19 +3465,6 @@ import FilterX from "@lucide/svelte/icons/filter-x"; oncontextmenu={(e) => onCanvasContextMenu(e, bitsContextMenu)} onscroll={onContainerScroll} onkeydown={handleTableKeydown} - onwheel={(e) => { - // Shift+wheel → horizontal scroll (maps a mouse wheel's vertical - // delta onto the X axis). Everything else — vertical, trackpad, - // diagonal — is left to the browser so macOS momentum/inertia and - // edge overscroll-chaining to the parent stay buttery smooth. - if (e.shiftKey) { - const tc = tableContainer - if (tc && (e.deltaY || e.deltaX)) { - e.preventDefault() - tc.scrollLeft += e.deltaY || e.deltaX - } - } - }} onfocusin={() => { isTableFocused = true; }} onfocusout={(e) => { if (!tableContainer?.contains(e.relatedTarget instanceof Element ? e.relatedTarget : null)) { @@ -3459,11 +3484,11 @@ import FilterX from "@lucide/svelte/icons/filter-x"; -
+
{selected.has(contextRowIdx) ? "Deselect row" : "Select row"} + runMenuAction(() => duplicateRow(contextRowIdx))} + > + + Duplicate row + - + {#if activeResult.loading} + + {:else} + + {/if} diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 69740f33..8fe0044d 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -2585,6 +2585,10 @@ let rowSearch = $state('') async function runSql() { if (!connection || !sqlText.trim()) return + if (tableReadonly && /^\s*(insert|update|delete|drop|truncate|alter|create|replace)\b/i.test(sqlText)) { + sqlError = 'Connection is read-only — write queries are blocked.' + return + } sqlLoading = true sqlError = '' sqlMessage = '' @@ -2623,6 +2627,7 @@ let rowSearch = $state('') recordActivity({ type: 'connect', title: `Connected to ${conn.name ?? conn.database ?? conn.filePath ?? 'database'}`, success: true }) connection = conn savedConnections = loadSavedConnections() + tableReadonly = savedConnections.find(c => c.id === savedId)?.readOnly ?? conn.readOnly ?? false // Persist last-used ID and bump timestamp if (savedId) { setLastConnectionId(savedId) @@ -3116,6 +3121,7 @@ let rowSearch = $state('') } } catch (err) { toast.error('Insert failed', { description: String(err) }) + throw err } finally { insertingRow = false } @@ -3412,6 +3418,18 @@ let rowSearch = $state('') style={sidebarOpen && !aiMode && connection ? '' : 'display:none'} inert={!sidebarOpen || aiMode || !connection || undefined} > + + {#snippet failed(err, reset)} +
+ +

Sidebar error

+ +
+ {/snippet} +
{/if} @@ -3531,6 +3550,7 @@ let rowSearch = $state('') inert={!aiMode} > {#await import('./AiChat.svelte')}{:then { default: AiChat }} + (showAiModelSettings = true)} onopendiagramspage={() => { exitAiMode(); openDiagramsTab() }} /> + {/await}
{/if} @@ -4269,19 +4290,36 @@ let rowSearch = $state('')
{:then { default: AiSidebar }} - void handleAiSidebarAccept(d)} - onopensettings={() => (showAiModelSettings = true)} - /> + + {#snippet failed(err, reset)} +
+ +
+

AI sidebar error

+

{err instanceof Error ? err.message : String(err)}

+
+ +
+ {/snippet} + void handleAiSidebarAccept(d)} + onopensettings={() => (showAiModelSettings = true)} + /> +
{/await}
{/if} diff --git a/src/lib/stores/connections.js b/src/lib/stores/connections.js index 6ebb0883..5cc60401 100644 --- a/src/lib/stores/connections.js +++ b/src/lib/stores/connections.js @@ -25,6 +25,7 @@ const LAST_ID_KEY = 'stroke:last-connection-id' * databaseId?: string * apiToken?: string * ssh?: SshConfig + * readOnly?: boolean * }} SavedConnection */ From 549dc6dec189a28ab0bf9a2e97dd38c700329a53 Mon Sep 17 00:00:00 2001 From: broisnischal Date: Tue, 23 Jun 2026 22:49:17 +0545 Subject: [PATCH 3/6] feat:: smooth fps scrolling --- src/lib/components/DataTable.svelte | 53 ++++++++++++++++++----------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index 30960056..42a01c8f 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -1900,28 +1900,42 @@ import FilterX from "@lucide/svelte/icons/filter-x"; }) /** @param {Event & { currentTarget: HTMLElement }} e */ + // Continuous rAF loop that drives canvas redraws during scroll. + // Reading scrollTop/scrollLeft inside rAF gives the compositor-synchronized + // position for the frame being painted, eliminating the 1-frame lag that + // a one-shot scheduleDraw() produces (queued from onscroll → fires next frame). + // The loop runs while the user is scrolling and for 200ms after the last + // scroll event to cover momentum/inertia, then stops to save GPU time. + let _scrollLoopId = 0 + let _scrollLoopDeadline = 0 + + function startScrollLoop() { + _scrollLoopDeadline = performance.now() + 200 + if (_scrollLoopId) return + function loop() { + const el = tableContainer + if (!el || !_ctx || performance.now() > _scrollLoopDeadline) { + _scrollLoopId = 0 + return + } + _scrollTop = el.scrollTop + _scrollLeft = el.scrollLeft + draw() + _scrollLoopId = requestAnimationFrame(loop) + } + _scrollLoopId = requestAnimationFrame(loop) + } + function onContainerScroll(e) { const el = e.currentTarget - // Page/layout scroll can shift the canvas on screen — drop the cached rect. invalidateCanvasRect() - const hScrolled = el.scrollLeft !== _scrollLeft - if (el.scrollTop !== _scrollTop) _scrollTop = el.scrollTop - if (hScrolled) _scrollLeft = el.scrollLeft - // For horizontal scroll, draw synchronously — the sticky canvas shows stale - // column positions for a full frame when deferred via rAF, which the eye - // reads as a column shift. Vertical scroll is imperceptible at 1-frame lag - // because adjacent rows look similar, so it stays on the rAF path. - // Re-arm a cleanup rAF so any concurrent reactive updates still get redrawn. - if (_ctx && (editingCell || hScrolled)) { - if (_drawRafId) cancelAnimationFrame(_drawRafId) - draw() - _drawRafId = requestAnimationFrame(() => { _drawRafId = 0 }) - } else { - // Repaint directly from the scroll handler. The big layout effect no longer - // tracks _scrollTop/_scrollLeft, so scrolling skips syncCanvasSurface() - // (style writes + getContext + setTransform) and only does the rAF draw. - scheduleDraw() - } + // Update state immediately so any synchronous consumers (hit-test etc.) are current. + _scrollTop = el.scrollTop + _scrollLeft = el.scrollLeft + // Cancel any pending one-shot draw — the loop handles all scroll redraws at + // the display's native frame rate (120Hz on ProMotion). + if (_drawRafId) { cancelAnimationFrame(_drawRafId); _drawRafId = 0 } + startScrollLoop() // Infinite scroll — trigger load when within 3 rows of the bottom if (infiniteScroll && !loadingMore) { const threshold = ROW_HEIGHT * 3 @@ -2963,6 +2977,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; onDestroy(() => { if (_drawRafId) cancelAnimationFrame(_drawRafId) if (_resizeRafId) cancelAnimationFrame(_resizeRafId) + if (_scrollLoopId) cancelAnimationFrame(_scrollLoopId) }) // Shift+wheel → horizontal scroll. Non-passive so we can call preventDefault, From ddfd8cfcd893f2a8ff68828873e8971c97bbc0bf Mon Sep 17 00:00:00 2001 From: broisnischal Date: Tue, 23 Jun 2026 23:19:44 +0545 Subject: [PATCH 4/6] feat:: internet connection fix --- src-tauri/src/commands.rs | 17 ++- src-tauri/src/db/mod.rs | 6 +- src-tauri/src/db/query.rs | 23 ++++ src-tauri/src/db/schema.rs | 64 ++++++++++ src-tauri/src/lib.rs | 2 + src/lib/ai.js | 9 ++ src/lib/api.js | 18 +++ src/lib/components/ConnectionModal.svelte | 28 +++++ src/lib/components/SecurityPage.svelte | 32 ++++- src/lib/components/SqlConsole.svelte | 43 ++++--- src/lib/components/StatusBar.svelte | 21 +++- src/lib/components/StudioShell.svelte | 120 ++++++++++++++++--- src/lib/components/ui/sonner/sonner.svelte | 11 +- src/lib/components/ui/sonner/toast.svelte.js | 13 +- src/lib/monaco-sql-complete.js | 36 ++++++ src/lib/stores/connections.js | 1 + src/lib/utils.js | 32 +++++ 17 files changed, 422 insertions(+), 54 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index bfeab69a..d7933cf0 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -122,10 +122,10 @@ pub fn toggle_devtools(window: tauri::WebviewWindow) { use crate::db::{ connect, connect_clickhouse, connect_d1, connect_duckdb, connect_libsql, connect_mssql, connect_mysql, connect_sqlite, disconnect, delete_table_row, delete_table_rows, execute_ddl, execute_sql, execute_sql_multi, get_table_rows, insert_table_row, - list_schemas, list_tables, list_indexes, list_enums, list_triggers, list_sequences, + list_schemas, list_tables, list_indexes, list_enums, list_functions, list_triggers, list_sequences, ping_connection, truncate_table, drop_table, get_table_column_structure, get_incoming_foreign_keys, get_table_ddl as db_get_table_ddl, test_clickhouse_connection, test_connection, test_d1_connection, test_duckdb_connection, test_libsql_connection, test_mssql_connection, test_mysql_connection, test_sqlite_connection, - update_table_cell, ConnectionConfig, D1Config, DbState, EnumInfo, ExplainResult, IndexInfo, LibSqlConfig, + update_table_cell, ConnectionConfig, D1Config, DbState, EnumInfo, FunctionInfo, ExplainResult, IndexInfo, LibSqlConfig, SqlResult, SqliteConfig, TableInfo, TableRows, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, InsertRowResult, TunnelState, explain_pg, explain_mysql, explain_sqlite, @@ -360,6 +360,19 @@ pub async fn pg_list_sequences( list_sequences(state, schema).await } +#[tauri::command] +pub async fn pg_list_functions( + state: State<'_, DbState>, + schema: String, +) -> Result, String> { + list_functions(state, schema).await +} + +#[tauri::command] +pub async fn ping_db_connection(state: State<'_, DbState>) -> Result<(), String> { + ping_connection(state).await +} + #[tauri::command] pub async fn pg_truncate_table( state: State<'_, DbState>, diff --git a/src-tauri/src/db/mod.rs b/src-tauri/src/db/mod.rs index 89e488d0..8b71f553 100644 --- a/src-tauri/src/db/mod.rs +++ b/src-tauri/src/db/mod.rs @@ -22,13 +22,13 @@ pub use explain::{explain_pg, explain_mysql, explain_sqlite, ExplainResult}; 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, - get_column_stats, get_table_rows, insert_table_row, update_table_cell, + get_column_stats, get_table_rows, insert_table_row, update_table_cell, ping_connection, ColumnStats, InsertRowResult, RowFilter, SqlResult, TableRows, }; pub use schema::{ list_schemas, list_tables, list_schemas_on_conn, list_tables_on_conn, - list_indexes, list_enums, list_triggers, list_sequences, + list_indexes, list_enums, list_functions, list_triggers, list_sequences, truncate_table, drop_table, get_table_column_structure, get_incoming_foreign_keys, get_table_ddl, get_table_ddl_on_conn, - TableInfo, IndexInfo, EnumInfo, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, + TableInfo, IndexInfo, EnumInfo, FunctionInfo, TriggerInfo, SequenceInfo, ColumnStructureRow, IncomingForeignKey, }; diff --git a/src-tauri/src/db/query.rs b/src-tauri/src/db/query.rs index d46e2da7..8b2f7392 100644 --- a/src-tauri/src/db/query.rs +++ b/src-tauri/src/db/query.rs @@ -2611,3 +2611,26 @@ pub async fn get_column_stats( Ok(ColumnStats { column, count, null_count, distinct_count, min, max, avg }) } + +/// Lightweight connection health check — runs `SELECT 1` against the active +/// connection. HTTP-based engines (D1, LibSQL, Clickhouse) are stateless so we +/// return Ok immediately; a real request would validate their tokens but also +/// incur network cost every 30 s. +pub async fn ping_connection(state: State<'_, DbState>) -> Result<(), String> { + let conn = require_conn(&state)?; + match conn { + ActiveConnection::Postgres(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + ActiveConnection::Sqlite(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + ActiveConnection::Mysql(pool) => { + sqlx::query("SELECT 1").execute(&pool).await.map(|_| ()).map_err(|e| e.to_string()) + } + // HTTP-based: stateless, no persistent TCP connection to validate + ActiveConnection::D1(_) | ActiveConnection::LibSql(_) | ActiveConnection::Clickhouse(_) => 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(|_| ()), + } +} diff --git a/src-tauri/src/db/schema.rs b/src-tauri/src/db/schema.rs index 42753bfb..3c4a7702 100644 --- a/src-tauri/src/db/schema.rs +++ b/src-tauri/src/db/schema.rs @@ -503,6 +503,19 @@ pub struct TriggerInfo { pub enabled: bool, } +// ── Functions / Procedures (PostgreSQL only) ───────────────────────────────── + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FunctionInfo { + pub name: String, + /// Full call signature e.g. "fn(arg1 text, arg2 int)" + pub signature: String, + pub return_type: String, + /// "function" | "procedure" | "aggregate" + pub kind: String, +} + // ── Sequences (PostgreSQL only) ─────────────────────────────────────────────── #[derive(Debug, Clone, Serialize)] @@ -701,6 +714,57 @@ pub async fn list_indexes(state: State<'_, DbState>, schema: String) -> Result Result, String> { + let rows = sqlx::query( + r#" + SELECT DISTINCT ON (p.proname) + p.proname::text AS name, + pg_get_function_arguments(p.oid) AS arg_types, + COALESCE(pg_get_function_result(p.oid), 'void') AS return_type, + CASE p.prokind + WHEN 'f' THEN 'function' + WHEN 'p' THEN 'procedure' + WHEN 'a' THEN 'aggregate' + ELSE 'function' + END AS kind + FROM pg_catalog.pg_proc p + JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = $1 + AND p.prokind IN ('f', 'p', 'a') + ORDER BY p.proname + "#, + ) + .bind(schema) + .fetch_all(pool) + .await + .map_err(|e| format!("Failed to list functions: {e}"))?; + + rows.iter() + .map(|row| { + let name: String = row.try_get("name").map_err(|e| e.to_string())?; + let arg_types: String = row.try_get("arg_types").map_err(|e| e.to_string())?; + let return_type: String = row.try_get("return_type").map_err(|e| e.to_string())?; + let kind: String = row.try_get("kind").map_err(|e| e.to_string())?; + Ok(FunctionInfo { + signature: format!("{}({})", name, arg_types), + name, + return_type, + kind, + }) + }) + .collect() +} + +pub async fn list_functions(state: State<'_, DbState>, schema: String) -> Result, String> { + match require_conn(&state)? { + ActiveConnection::Postgres(pool) => { + validate_ident(&schema)?; + list_functions_pg(&pool, &schema).await + } + _ => Ok(vec![]), + } +} + pub async fn list_enums(state: State<'_, DbState>, schema: String) -> Result, String> { match require_conn(&state)? { ActiveConnection::Postgres(pool) => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 482dd769..5380480a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -254,8 +254,10 @@ pub fn run() { commands::pg_get_table_column_structure, commands::pg_get_incoming_foreign_keys, commands::pg_list_enums, + commands::pg_list_functions, commands::pg_list_triggers, commands::pg_list_sequences, + commands::ping_db_connection, commands::pg_truncate_table, commands::pg_drop_table, commands::get_table_ddl, diff --git a/src/lib/ai.js b/src/lib/ai.js index cad7b26f..c25d538f 100644 --- a/src/lib/ai.js +++ b/src/lib/ai.js @@ -1352,11 +1352,20 @@ SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() ORDER B (ctx.userSkills ?? []).map((s) => `### ${s.name}\n${s.content}`).join('\n\n') : '' + const envLine = ctx.environment + ? ctx.environment === 'prod' + ? `Environment: PRODUCTION — treat all destructive queries (DELETE, DROP, TRUNCATE, UPDATE without WHERE) with extreme caution. Always confirm scope before executing.` + : ctx.environment === 'staging' + ? `Environment: STAGING` + : `Environment: DEV` + : '' + return `You are an expert ${DB_LABEL[dbType] ?? 'SQL'} database assistant embedded in Stroke — a database GUI. Your job: help users explore, query, analyse, and visualise their database through tool calls and clear explanations. === DATABASE === Engine: ${DB_LABEL[dbType] ?? dbType} +${envLine} ${DB_NOTES[dbType] ?? ''} Available schemas: ${ctx.schemas.length ? ctx.schemas.join(', ') : ctx.activeSchema} diff --git a/src/lib/api.js b/src/lib/api.js index e1b608a9..519a08c0 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -347,6 +347,24 @@ export async function listSequences(schema) { } } +/** @param {string} schema */ +export async function listFunctions(schema) { + try { + return await invoke('pg_list_functions', { schema }) + } catch (err) { + throw new Error(formatInvokeError(err)) + } +} + +/** @returns {Promise} */ +export async function pingConnection() { + try { + await invoke('ping_db_connection') + } catch (err) { + throw new Error(formatInvokeError(err)) + } +} + /** * @param {string} schema * @param {string} table diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index ee101660..1979d805 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -141,6 +141,8 @@ let uriHint = $state('') // ── Connection options ─────────────────────────────────────────────────────── + /** @type {'prod' | 'staging' | 'dev' | null} */ + let environment = $state(null) let readOnly = $state(false) // ── SSH tunnel state ───────────────────────────────────────────────────────── @@ -221,6 +223,7 @@ sshEnabled = !!s?.host; sshHost = s?.host ?? ''; sshPort = String(s?.port ?? 22) sshUsername = s?.username ?? ''; sshKeyPath = s?.privateKeyPath ?? '' readOnly = conn.readOnly ?? false + environment = conn.environment ?? null } else { dbType = 'postgres'; name = ''; host = '127.0.0.1'; port = '5432' database = 'postgres'; user = 'postgres'; password = ''; ssl = false; secure = false @@ -229,6 +232,7 @@ libsqlUrl = ''; libsqlToken = '' sshEnabled = false; sshHost = ''; sshPort = '22'; sshUsername = ''; sshKeyPath = '' readOnly = false + environment = null } error = ''; testOk = false; connectionUri = ''; uriHint = '' d1Reset() @@ -361,6 +365,7 @@ port: hasHostPort ? (Number(payload.port) || defaultPort) : undefined, lastConnectedAt: Date.now(), readOnly: readOnly || undefined, + environment: environment || undefined, } saved = upsertConnection(saved_conn).sort((a, b) => (b.lastConnectedAt ?? 0) - (a.lastConnectedAt ?? 0)) setLastConnectionId(id) @@ -963,6 +968,29 @@
+ +
+

Environment

+
+ {#each /** @type {Array<{id: 'prod'|'staging'|'dev', label: string, cls: string}>} */ ([ + { id: 'prod', label: 'Production', cls: 'border-red-500/40 bg-red-500/10 text-red-500' }, + { id: 'staging', label: 'Staging', cls: 'border-amber-500/40 bg-amber-500/10 text-amber-500' }, + { id: 'dev', label: 'Dev', cls: 'border-emerald-500/40 bg-emerald-500/10 text-emerald-500' }, + ]) as env (env.id)} + + {/each} +
+
+