Repository navigation
feat(editor): open SQLite databases in a read-only table viewer - #11809
AboveColin wants to merge 6 commits into
Conversation
`.db`, `.sqlite` and `.sqlite3` files fell back to "Binary file — cannot display". They now open in a virtualized table viewer with a table list. Reads go through the existing `node:sqlite` adapter (src/main/sqlite/ sync-database.ts), the same one the orchestration store uses, so SQLite's own parser handles WAL snapshots, WITHOUT ROWID tables, generated columns and column defaults. No third-party native addon, so no exposure to the glibc floor. The viewer never reaches the text-content pipeline, whose 10 MB previewable-binary cap would reject an ordinary database. Opening reads only the schema; count(*) runs for the displayed table alone. Rows are paged in chunks of 200 with an explicit ORDER BY, without which SQLite can serve one chunk from an index and the next from the table and interleave rows. Remote files are refused rather than silently read from a same-named local path: SSH, runtime environments and unresolved owners each report why.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdded a read-only SQLite reader with metadata discovery, typed cell conversion, pagination, row counting, and size limits. Added authorized IPC handlers and typed preload APIs. Added SQLite file detection, ownership resolution, editor routing, and a virtualized renderer with chunked row loading. Added fixtures, localization, and Vitest coverage. Priority: ➖ Normal Merge Risk: 🔵 Low · up to The rowid-shadowing behavior is implemented, but its regression test cannot distinguish the intended ordering from the broken ordering. Strengthen the fixture before merge to prevent this pagination bug from escaping future changes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the implementation, scope, limitations, testing, and manual validation, but it omits most required template sections, including ELI5, Linked Issue, Visual Proof or an explicit N/A, Review, Agent skill upstream boundary, Notes, and Checklist confirmations. Resolution Update the description to include all required template sections. Add an ELI5 summary, a linked issue using Full details: Docstring CoverageExplanation Docstring coverage is 12.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 24 files. (2 skipped: 2 unsupported.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/renderer/src/components/editor/SqliteTableList.tsx (1)
25-41: 📐 Maintainability & Code Quality | 🔵 TrivialConsider using a shadcn primitive for the table-row button.
This renders a raw
<button>with custom Tailwind classes for each table row. Check whether the codebase has an existing shadcn-based pattern (for example, aButtonvariant or list-item primitive fromsrc/renderer/src/components/ui/) for this kind of selectable-row UI, and align this component with it if one exists.As per coding guidelines, "All UI work—including layout, color, typography, spacing, component selection, and UX behavior—must follow
docs/STYLEGUIDE.md... and use shadcn primitives fromsrc/renderer/src/components/ui/."#!/bin/bash # Description: Check for existing shadcn-based list/button primitives used for similar sidebar row selection. fd . src/renderer/src/components/ui --iglob '*button*' rg -n "components/ui/button" --type=tsx --type=ts -g '!**/*.test.*'
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cb9759fa-8dca-4eb5-aec9-cd92e4c59a96
⛔ Files ignored due to path filters (1)
src/main/sqlite/__fixtures__/sample-database.dbis excluded by!**/*.db
📒 Files selected for processing (23)
src/main/ipc/register-core-handlers.test.tssrc/main/ipc/register-core-handlers.tssrc/main/ipc/sqlite-database.test.tssrc/main/ipc/sqlite-database.tssrc/main/sqlite/__fixtures__/sample-database.sqlsrc/main/sqlite/sqlite-reader.test.tssrc/main/sqlite/sqlite-reader.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsxsrc/renderer/src/components/editor/EditorContent.test.tsxsrc/renderer/src/components/editor/EditorContent.tsxsrc/renderer/src/components/editor/EditorPanelShell.tsxsrc/renderer/src/components/editor/SqliteTableList.tsxsrc/renderer/src/components/editor/SqliteViewer.tsxsrc/renderer/src/components/editor/editor-panel-render-model.tssrc/renderer/src/components/editor/sqlite-file-owner.test.tssrc/renderer/src/components/editor/sqlite-file-owner.tssrc/renderer/src/components/editor/use-sqlite-table-rows.test.tssrc/renderer/src/components/editor/use-sqlite-table-rows.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/lib/language-detect.tssrc/shared/sqlite-database.ts
Greptile SummaryThis PR adds a read-only, virtualized table viewer for
Confidence Score: 5/5Safe to merge. The new code paths are well-isolated behind a new isSqlite flag, the IPC boundary is protected by path authorization and table-name allowlisting, and the chunk cache has been hardened against the duplicate-fetch, stale-response, and eviction-blank-row issues surfaced in earlier review rounds. All three concerns from the previous review round were addressed in 1f1a64c: hidden FTS5 columns are filtered, withReader awaits its callback before closing, and the resident ref is now the source of truth so a scroll event between a response landing and React committing can no longer re-request the same chunk. The new code introduces no unsafe SQL interpolation, no third-party native addons, and no new async-lifetime issues. Test coverage is thorough — quoted identifiers, WITHOUT ROWID, generated columns, FTS5 shadow tables, and eviction regression are all exercised against a checked-in fixture. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/sqlite/sqlite-reader.ts | New SqliteDatabaseReader: opens read-only, filters shadow/sqlite_ tables from sqlite_master, lazy-resolves columns via table_xinfo (hidden≠1), probes rowid vs primary key for stable ORDER BY, and bounds text per cell based on column×row budget. |
| src/main/ipc/sqlite-database.ts | IPC handlers: rejects remote connectionIds before path resolution, routes all paths through resolveAuthorizedPath, validates offset/limit ranges at the IPC boundary, and uses async-aware withReader with a finally close. |
| src/renderer/src/components/editor/use-sqlite-table-rows.ts | Virtualized chunk cache: ref as source of truth prevents the duplicate-fetch window, generation counter drops stale cross-table responses, eviction sorts by distance from lastRequested, and ensureRange guards against zero rowCount. |
| src/renderer/src/components/editor/SqliteViewer.tsx | Viewer component: three sequential effects (open → count → rows), virtualizer drives ensureRange, headerColumns falls back to schema columns before first page arrives; countError branches replace the grid but leave the status bar showing "counting rows…" simultaneously. |
| src/renderer/src/components/editor/sqlite-file-owner.ts | Correctly classifies file ownership (local/remote/runtime-environment/unresolved) before any IPC call, preventing a same-named local file from being opened as a fallback for an SSH or unresolved path. |
| src/shared/sqlite-database.ts | Shared types are minimal and well-scoped; the optional truncated flag correctly distinguishes clipped text from full text. |
| src/renderer/src/lib/language-detect.ts | Adds .db, .sqlite, .sqlite3 → sqlite extension mappings; the sqlite language key routes before the binary size gate in EditorContent. |
| src/main/sqlite/sqlite-reader.test.ts | Comprehensive fixture-based tests covering every value type, WITHOUT ROWID ordering, generated columns, ALTER TABLE defaults, quoted identifiers, FTS5 hidden-column filtering, shadow-table exclusion, SQL-injection rejection, and out-of-bounds paging. |
| src/renderer/src/components/editor/use-sqlite-table-rows.test.ts | Hook tests cover deduplication, cross-chunk index mapping, stale-response after table switch, eviction-and-refetch regression, and error surfacing. |
Sequence Diagram
sequenceDiagram
participant R as Renderer (SqliteViewer)
participant P as Preload (IPC bridge)
participant M as Main (sqlite-database.ts)
participant DB as SqliteDatabaseReader
R->>P: "sqlite.openDatabase({ filePath })"
P->>M: ipcMain: sqlite:openDatabase
M->>DB: SqliteDatabaseReader.open(filePath)
DB-->>M: reader (tableNames from sqlite_master)
M->>DB: reader.overview() → listTables() → N×columnsOf()
DB-->>M: SqliteDatabaseOverview
M-->>P: overview
P-->>R: overview (tables + columns)
R->>P: "sqlite.countTableRows({ filePath, table })"
P->>M: ipcMain: sqlite:countTableRows
M->>DB: reader.countRows(table)
DB-->>M: "number (COUNT(*))"
M-->>P: rowCount
P-->>R: rowCount
loop On scroll (ensureRange)
R->>P: "sqlite.readTablePage({ filePath, table, offset, limit })"
P->>M: ipcMain: sqlite:readTablePage
M->>DB: reader.readTablePage(table, offset, limit)
Note over DB: requireTable() validates name<br/>orderBy() probes rowid vs PK<br/>SELECT * ORDER BY LIMIT OFFSET
DB-->>M: SqliteTablePage
M-->>P: page
P-->>R: page stored in resident ref → setChunks
end
Reviews (3): Last reviewed commit: "fix(editor): hide virtual-table shadow t..." | Re-trigger Greptile
- Hide SQLite's reserved sqlite_% tables; sqlite_sequence showed up as user data for any table with AUTOINCREMENT. - Drop table_xinfo columns that SELECT * omits. FTS5 adds hidden `docs` and `rank` columns, which rendered as phantom NULL cells. - Resolve a table's columns lazily instead of running one pragma per table on every reader open, so a chunk read no longer costs N+1 round-trips. - Await the callback in withReader so a future async caller cannot outlive the connection close. - Make the chunk cache ref the source of truth so residency is visible before React commits; a scroll could previously re-request an in-flight chunk. Fixture now covers an AUTOINCREMENT table and an FTS5 virtual table. count(*) stays synchronous on the main thread: measured 31ms over 5M rows and 36ms over a 280MB/500k-row table, with a deep OFFSET page at 46ms, so a worker thread is not warranted at these sizes.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 03ee1b74-522c-4e7e-b28b-3e1c0320b916
⛔ Files ignored due to path filters (1)
src/main/sqlite/__fixtures__/sample-database.dbis excluded by!**/*.db
📒 Files selected for processing (5)
src/main/ipc/sqlite-database.tssrc/main/sqlite/__fixtures__/sample-database.sqlsrc/main/sqlite/sqlite-reader.test.tssrc/main/sqlite/sqlite-reader.tssrc/renderer/src/components/editor/use-sqlite-table-rows.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/sqlite/sqlite-reader.test.ts
- src/main/ipc/sqlite-database.ts
- src/renderer/src/components/editor/use-sqlite-table-rows.ts
- src/main/sqlite/sqlite-reader.ts
|
Thanks both for the reviews — pushed 1f1a64c addressing them. Changed
The fixture gained an Not changed, with reasoning in the threads
Still no e2e spec; glad to add one under |
FTS5 stores its index and content in shadow tables (docs_data, docs_idx, ...). Listing them let a user open index internals as if they were data. A table is treated as shadow only when the name before its last underscore is a virtual table AND the suffix is one its module declares, mirroring SQLite's own xShadowName check. Matching the prefix alone would have hidden a user table named docs_archive next to an fts5 docs; an unknown module is left visible, since showing an extra table beats hiding a real one.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/sqlite/sqlite-reader.ts (1)
197-211: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUse an unshadowed internal rowid alias.
Line 200 only confirms that
rowidresolves. A rowid table can define a user column namedrowid, which shadows SQLite's internal alias. If that column has duplicate values,ORDER BY rowidis not a total order, so page boundaries can repeat or omit rows.Select an unshadowed alias from
rowid,_rowid_, andoidusing table metadata. If all aliases are shadowed, use a proven unique key or reject paging for that table. Add a regression test with a non-unique user-definedrowidcolumn.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3093a764-a7b5-42eb-a8b0-5116843238a7
⛔ Files ignored due to path filters (1)
src/main/sqlite/__fixtures__/sample-database.dbis excluded by!**/*.db
📒 Files selected for processing (3)
src/main/sqlite/__fixtures__/sample-database.sqlsrc/main/sqlite/sqlite-reader.test.tssrc/main/sqlite/sqlite-reader.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/sqlite/sqlite-reader.test.ts
- src/main/sqlite/fixtures/sample-database.sql
# Conflicts: # src/main/ipc/register-core-handlers/register-core-handlers.test.ts # src/main/ipc/register-core-handlers/register-core-handlers.ts # src/preload/api-types.ts # src/preload/index.ts # src/renderer/src/components/editor/EditorContent.tsx # src/renderer/src/i18n/locales/en.json
A user table can declare its own non-unique column literally named rowid, which shadows the internal rowid alias for that table only and breaks the total order pagination depends on. orderBy now checks declared columns and prefers the first of rowid, _rowid_, oid that the table hasn't declared, falling back to the primary key (or erroring) exactly as before when none resolve. Adds a shadow_rowid fixture table and a regression test.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 9ea5e25b-e553-435c-b0fa-4c30d429a5cd
⛔ Files ignored due to path filters (1)
src/main/sqlite/__fixtures__/sample-database.dbis excluded by!**/*.db
📒 Files selected for processing (18)
src/main/ipc/register-core-handlers/register-core-handlers.test.tssrc/main/ipc/register-core-handlers/register-core-handlers.tssrc/main/sqlite/__fixtures__/sample-database.sqlsrc/main/sqlite/sqlite-reader.test.tssrc/main/sqlite/sqlite-reader.tssrc/preload/api-types.tssrc/preload/api/sqlite-database-api.tssrc/preload/api/sqlite-database-bridge.tssrc/preload/index.tssrc/renderer/src/components/editor/EditorContent.markdown-classification.test.tsxsrc/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsxsrc/renderer/src/components/editor/EditorContent.test.tsxsrc/renderer/src/components/editor/EditorContent.tsxsrc/renderer/src/components/editor/EditorPanelShell.tsxsrc/renderer/src/components/editor/editor-lazy-views.tssrc/renderer/src/components/editor/editor-panel-render-model.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/lib/language-detect.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/i18n/locales/en.json
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| const page = reader.readTablePage('shadow_rowid', 0, 10) | ||
| expect(page.columns).toEqual(['rowid', 'label']) | ||
| expect(page.rows.map((row) => row[1]?.text)).toEqual(['first', 'second', 'third']) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Make the rowid-shadowing test discriminate between both order clauses.
All user-defined rowid values are equal. An incorrect ORDER BY rowid can still return first, second, third, so this regression test can pass without using _rowid_ or oid.
Use non-unique values whose sorted order differs from insertion order. For example, use z, a, and z, while retaining the expected label order.
|
Closing this. It has fallen behind main and I'm not able to keep it current. Thanks for the reviews. |
What
.db,.sqliteand.sqlite3files currently fall back to "Binary file — cannot display". This opens them in a read-only, virtualized table viewer with a table list beside it.Why this approach
Reads go through
SyncDatabase(src/main/sqlite/sync-database.ts) — the existingnode:sqliteadapter thatruntime/orchestration/db.tsalready uses. Letting SQLite's own parser do the work means WAL snapshots,WITHOUT ROWIDtables, generated columns andALTER TABLEcolumn defaults are all correct without this code knowing anything about the on-disk format. It also adds no third-party native addon, so there is no exposure to the glibc floor indocs/reference/linux-glibc-compatibility.md.Two details worth a reviewer's attention:
MAX_PREVIEWABLE_BINARY_SIZEis 10 MB, which rejects an ordinary database outright, so the branch sits before the content lookup inEditorContent.ORDER BY. Without one, SQLite may satisfy one chunk from a covering index and the next from the table, which interleaves rows across chunk boundaries and shows duplicates and gaps while scrolling. Rowid tables order byrowid;WITHOUT ROWIDtables order by their primary key.Opening a tab reads only the schema. Row counts are deliberately not part of that —
count(*)scans a table, so counting every table up front would read the whole file just to render a sidebar. Only the displayed table is counted.Bounds
sqlite_masterand are rejected if unknown before being quoted into a query, so a name from the renderer never reaches SQL unchecked.Not supported
SSH hosts and runtime environments — the reader runs against the local filesystem. An unresolved owner is reported as such rather than falling back to a same-named local file. Views, indexes and triggers are not listed, and there is no editing.
Because each IPC call opens its own read-only connection, two chunks can come from different points in time if the database is being written concurrently. A viewer does not hold a transaction open across scrolling.
Testing
35 tests: reader against a checked-in fixture (regenerable from
sample-database.sql) covering quoted identifiers,WITHOUT ROWID, generated columns,ALTER TABLEdefaults and an overflowing value; IPC handlers including the path-authorization and remote-refusal paths; and the renderer chunk cache, including regressions for a stale response after a table switch and for an evicted chunk never reloading.Also exercised manually against a real 15 MB / 15,968-row database, cross-checked against the
sqlite3CLI: identical row counts, identical rows at offset 15000, and an identical SHA-256 for a 29,883-character overflowing value.pnpm lintandpnpm typecheckare clean. No e2e spec yet — happy to add one undertests/e2e/if you'd like that before merge.