Skip to content

Latest commit

 

History

History
251 lines (177 loc) · 10.6 KB

ARCHITECTURE.md

File metadata and controls

251 lines (177 loc) · 10.6 KB

DbShell — System Design & How It Works

This is the deep-dive design document for DbShell: a terminal SQL database client, inspired by DataGrip and lazydocker.

It covers, end to end:

  1. Big picture
  2. Query lifecycle
  3. Connectors (multi-database)
  4. TUI architecture & flow
  5. Slash commands
  6. Global memory
  7. The Backend abstraction
  8. Packaging & npm publishing
  9. Adding a new database type
  10. Project layout

1. Big picture

┌─────────┐    ┌──────────────────┐    ┌──────────────────────────┐
│  User   │───▶│    TUI (Ink)     │───▶│  SQLite · PostgreSQL ·   │
└─────────┘    │  Backend → Query │    │  MySQL (your database)  │
               │  Service → conn  │    └──────────────────────────┘
               └──────────────────┘
  • A query arrives as a SQL string from the TUI editor (or a slash command).
  • QueryService.submit() hands it straight to the target connector's query(sql) method — the real database engine parses, plans, and executes it.
  • The TUI drives all of this through a thin Backend interface, and persists connections + history to a global memory store.

One process, no HTTP server, no ports. The TUI is the app (npm run lazy).


2. Query lifecycle

A query goes through these states:

QUEUED → RUNNING → COMPLETED | FAILED

Step 1 — Submit

SELECT COUNT(*) FROM sqlite_demo.users WHERE age > 20

The TUI calls QueryService.submit(sql, defaultConnector) (coordinator/query-service.ts), where defaultConnector is the active connection id.

Step 2 — Execute

SELECT/WITH-shaped SQL is wrapped as a paged subquery:

SELECT * FROM (SELECT COUNT(*) FROM sqlite_demo.users WHERE age > 20) AS __dbshell_page LIMIT 200 OFFSET 0

Everything else (INSERT/UPDATE/DDL/...) runs as-is, once, unpaginated. Either way it's passed to connector.query(sql), which each connector implements against its real driver:

Connector query() implementation /kill cancels it?
SQLite db.prepare(sql) (node:sqlite, read-only) No — synchronous driver, can't interrupt an in-flight call
PostgreSQL dedicated pool.connect(), cancel via pg_cancel_backend(pid) from a second connection Yes
MySQL dedicated pool.getConnection(), cancel via KILL QUERY <threadId> from a second connection Yes

The database does its own parsing, planning, and execution — DbShell doesn't touch the SQL itself beyond the paging wrapper. QueryService.submit() hands each connector an AbortSignal; kill() aborts it, which the postgres/mysql connectors turn into a real server-side cancel. SQLite's query() only checks the signal before starting, since node:sqlite blocks the event loop for the duration of the call — there's no point to interrupt.

Step 3 — Paginate

The result is stored on the QueryRecord. If the query was a SELECT, a QueryPageState is recorded (connectorId, the original SQL, next offset, pageSize). As the TUI scrolls near the end of the loaded rows, loadMoreRows → QueryService.fetchMore() re-wraps the same SQL with the next offset and appends the result — until a page comes back shorter than pageSize, which marks it exhausted.


3. Connectors

Every data source implements the same interface (shared/connectors.ts):

interface Connector {
  id: string;
  type: 'sqlite' | 'postgres' | 'mysql';
  config: ConnectionConfig;
  connect(): Promise<void>;
  listTables(): Promise<string[]>;
  getTableMetadata(table: string): Promise<TableMetadata>;   // columns + types
  countRows(table: string): Promise<number>;
  readRange(table, startRow, endRow, limit?): Promise<Row[]>; // used for the TUI's row sample preview
  query(sql: string): Promise<{ columns: string[]; rows: Array<string | number | null>[] }>; // direct SQL execution
}

The registry (coordinator/connector-registry.ts) holds every connector the TUI has connected to this session; connections are added at runtime as the user connects (or reconnects a saved one). Connectors are built on demand (shared/connector-factory.ts — drivers are lazy-loaded via dynamic import() so boot doesn't block on mysql2/pg).

Connection URLs are parsed in tui/screens/connect.tsx — including sslmode=require → ssl: true for Neon-style managed Postgres.


4. TUI architecture & flow

The TUI is built on Ink (React for CLIs). It is a DataGrip-style database client:

Picker → (Connect wizard) → Workspace

Screen 1: Database picker

  • Lists live connections first, then saved-but-offline connections (tagged reconnect), then Connect New Database.
  • Sorted by recency from global memory.

Screen 2: Connect wizard

  • Choose a type: SQLite / PostgreSQL / MySQL / Connection URL.
  • URL mode: paste postgres://user:pass@host:5432/db, mysql://..., or sqlite:/path — parsed into a config automatically.
  • Field mode: name + host/port/database/user/password.
  • The name becomes the connection id used in SQL (FROM <name>.table).

Screen 3: Workspace

  • Status line: connection · table · query status
  • Hint line: the shortcuts
  • Sidebar: connections on one dim line (switch with ←/→), tables below (navigate with ↑/↓, select with ▸)
  • Main panel: table details (stats / DDL / schema / sample / count), or the SQL editor

Shortcuts:

Key Action
↑/↓ move through tables
←/→ switch database
s c i p n stats · ddl · schema · sample · count
v open editor pre-filled SELECT * FROM <table>
Tab open editor
Enter/Ctrl+Enter run query (editor)
Esc back / exit editor
q quit (picker)

Design principles applied (from the design skill's product-surface discipline): one status line, no colored section headers, no bordered boxes, one accent (green) for selection, dense but calm.


5. Slash commands

Typed in the editor. Dispatcher: commands/index.ts → runCommand(text, ctx).

Command Action
/help list commands
/clear clear the terminal (ANSI escape, TTY only)
/history [n] recent queries from memory
/kill <queryId> cancel a query
/kill list running queries
/connect <connId> reconnect a saved connection
/connect <id> <type> [host] [port] [db] [user] [password] connect to a new DB

Each command is a pure function (args, ctx) → CommandResult with ctx = { backend, memory, activeConn, commands, stdout }.


6. Global memory

DbShell persists your state in the platform config directory:

Platform Path
Windows %APPDATA%\dbshell\memory.json
macOS ~/Library/Application Support/dbshell/memory.json
Linux $XDG_CONFIG_HOME/dbshell/memory.json (or ~/.config/dbshell)

DBSHELL_CONFIG overrides the directory.

memory.json holds:

{
  "connections": [ { "id": "sqlite_demo", "type": "sqlite", "file": "...", "lastConnected": 1786... } ],
  "history":     [ { "sql": "SELECT ...", "connId": "sqlite_demo", "status": "COMPLETED", "runAt": 1786... } ]
}
  • Connections — saved with lastConnected, sorted by recency in the picker, reconnected at boot.
  • History — last 200 queries; shown in the editor and via /history.

Connection passwords are encrypted at rest (core/secret.ts, AES-256-GCM). The key is generated once and stored as a separate key file next to memory.json in the same config dir — memory.json itself never holds a plaintext secret. MemoryStore decrypts on load() and encrypts on save(), so everywhere else in the app (saved.password, /connect, etc.) still just sees plaintext at runtime; only the on-disk JSON is ciphertext. This defends against the file leaking on its own (backups, cloud-synced config dirs, screen shares) — not against another process running as the same OS user, which can read the key file too.


7. The Backend abstraction

The TUI never talks to the engine directly. It uses a Backend interface (tui/services/backend.ts):

interface Backend {
  listQueries(); listConnections();
  connectDb(config); listTables(connId); getTableMetadata(connId, table);
  countRows(connId, table); sampleRows(connId, table, limit);
  getQuery(id); getResult(id); submitQuery(sql); killQuery(queryId);
  loadMoreRows(queryId);
}

One implementation — DirectBackend (tui/services/direct-backend.ts) — wraps the in-process Cluster (core/cluster.ts: { store, connectors, queryService }). The screens call a thin api.* facade (tui/services/api.ts) over it, so screen code never touches the engine directly.


8. Packaging & npm publishing

package.json is publish-ready:

  • name: dbshell · type: module · engines: node >= 22
  • bin: dbshell → bin/dbshell.js
  • files: bin/, dist/, source dirs, tsconfigs
npm run build      # tsc -p tsconfig.build.json → dist/
npm start          # node dist/index.js
npm publish        # runs prepublishOnly: build + typecheck

bin/dbshell.js prefers compiled dist/index.js (plain node) and falls back to running the TS source via tsx.


9. Adding a new database type

  1. Implement Connector in shared/connectors/<type>.ts (6 methods, including query).
  2. Register it in shared/connector-factory.ts (one case, dynamically imported).
  3. Add the type to ConnectionConfig['type'] in shared/connectors.ts.
  4. Done — the query service, connector registry, and TUI all pick it up.

See the README's DuckDB walkthrough for a full example.


10. Project layout

bin/                 npm bin entry (dbshell)
index.ts             entry point (npm run lazy): cluster + TUI
commands/            slash commands (/help, /clear, /history, /kill, /connect)
core/                Cluster, config dir, memory store
coordinator/         connector registry, query store, query service (direct SQL execution)
shared/              types, connector interface + implementations, connector factory
tui/                 Ink screens (picker, connect, workspace), Backend + DirectBackend
scripts/             demo DB generator
datasets/            demo.sqlite (gitignored)