Skip to content
krishnadobhalPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

DbShell

DbShell demo

A terminal SQL database client — inspired by DataGrip and lazydocker.

Deep-dive: for the full system design (query execution, connectors, TUI architecture, memory, packaging), see docs/ARCHITECTURE.md.

The TUI connects directly to a real database (SQLite, PostgreSQL, or MySQL) and runs your SQL straight against its own engine — no intermediate query planner, no server process, no ports.

┌─────────┐    ┌──────────────────┐    ┌──────────────────────────┐
│  User   │───▶│    TUI (Ink)     │───▶│  SQLite · PostgreSQL ·   │
└─────────┘    │  Backend → Query │    │  MySQL (your database)  │
               │  Service → conn  │    └──────────────────────────┘
               └──────────────────┘

Features

  • Multi-database — query SQLite, PostgreSQL, and MySQL through one interface; register any number of connections at runtime
  • Full SQL — queries run directly against the database's own engine, so anything that database supports works (not a restricted subset)
  • Paginated results — SELECTs load 200 rows at a time as you scroll, instead of pulling an entire result set into memory
  • Terminal dashboard — a DataGrip-style database client: connection picker, table sidebar, and a SQL editor with history

Prerequisites

  • Node.js >= 22 (Ink 7 requires it)
  • npm

Quick start

Global install (npm)

npm install -g dbshell

# Then run it anywhere:
dbshell

From source

# 1. Install dependencies
npm install

# 2. Run DbShell
npm run lazy

That's it — one process, no HTTP server, no ports. Press q to quit.

Build & run compiled (no tsx)

npm run lazy runs the TypeScript source directly via tsx — no build step. If you want a plain-JS build:

npm run build      # compiles TypeScript → dist/ (tsc -p tsconfig.build.json)
npm start          # runs node dist/index.js

The npm bin (dbshell) automatically uses dist/index.js when the build exists, and falls back to tsx otherwise.

Global memory

DbShell persists your state in the platform config directory:

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

memory.json stores:

  • Connections — every database you've connected to, with lastConnected timestamps. The picker offers them sorted by recency and reconnects them automatically at boot. Disconnected-but-saved DBs appear with a (reconnect) tag.
  • Query history — the last 200 queries (SQL, connection, status), shown under "Recent queries" in the editor.

Override the location with DBSHELL_CONFIG=/path/to/dir. Connection passwords are encrypted at rest (AES-256-GCM) — the key lives in a separate key file next to memory.json in the same config dir, so memory.json itself never holds a plaintext secret. That protects against the realistic risk for a personal tool (the file ending up in a backup, a cloud-synced config folder, a screen share, or a pasted-in bug report) — it isn't a hard boundary against another process running as the same OS user, since that user can read the key file too.

TUI flow

The terminal app is a DataGrip-style database client:

  1. Database picker — on launch you see the databases you've connected to before (from global memory), plus a Connect New Database option at the bottom.
  2. Connect wizard — pick a type (SQLite / PostgreSQL / MySQL) or paste a connection URL, then fill in the connection fields. The connection is saved to global memory for next time.
  3. Workspace — a left sidebar lists your databases and their tables; a shortcut-driven menu opens stats, DDL, schema info, samples, and row counts; a query editor runs SQL against the selected connection and records history.

Shortcuts

Key Action
↑ / ↓ Navigate connections / tables
← / → Switch database (workspace)
Enter Select (picker / wizard) / run SQL (editor)
Tab Enter the SQL editor
Ctrl+Enter Run the query
v Table view — list tables
s Stats — row count + columns
c Table DDL
i Schema info — column types
p Sample — preview 20 rows
n Row count
Esc Back (wizard → picker, workspace → picker, editor → menu)
q Quit

npm run lazy auto-registers datasets/demo.sqlite as sqlite_demo when it exists, and reconnects every saved connection from global memory.

Slash commands

In the SQL editor, type a command starting with / and press Enter:

Command Action
/help List all commands
/clear Clear the terminal screen
/history [n] Show the last n queries from global memory (default 15)
/kill <queryId> Cancel a running/queued query
/kill List running queries to choose from
/connect List saved connections
/connect <connId> Reconnect a saved connection
/connect <id> <type> [host] [port] [db] [user] [password] Connect to a new database (type: sqlite/postgres/mysql)

Example — cancel a stuck query:

/kill             → shows running queries:  a1b2c3d4  RUNNING  SELECT COUNT(*) FROM sqlite_demo.users
/kill a1b2c3d4    → Cancelled query a1b2c3d4

Multi-database support

DbShell can query any number of registered databases through a single interface. Connections are registered from the TUI — via the Connect wizard (picker → "+ Connect new database") or the /connect slash command — and persisted to global memory.

Query any registered database

Use the connection id as a table qualifier: FROM <connection_id>.<table>.

-- SQLite
SELECT COUNT(*) FROM sqlite_demo.users;
SELECT SUM(salary) AS total FROM sqlite_demo.users WHERE age > 20;

-- PostgreSQL / MySQL
SELECT COUNT(*) FROM postgres_prod.orders;
SELECT AVG(amount) FROM mysql_dev.orders WHERE quantity > 2;

Connection id rules: use letters, digits and underscores (e.g. sqlite_demo). A dash is not a valid SQL identifier — it needs backtick quoting: FROM `sqlite-demo`.users.

Supported SQL

Queries run directly against the connected database's own engine (connector.query(sql) — see How it works), so anything that database's SQL dialect supports works: JOINs, GROUP BY, subqueries, INSERT/UPDATE/DDL, and so on — not a restricted subset.

SELECT-shaped queries (SELECT/WITH) are paginated automatically: the first 200 rows load immediately, more load as you scroll near the end of the result. Mutating statements (INSERT/UPDATE/DDL/...) run once, unpaginated.

How it works

  1. Submit — the TUI (or a slash command) calls QueryService.submit(sql, connectionId).
  2. Execute — SELECT-shaped SQL is wrapped in a paging subquery (LIMIT 200 OFFSET 0); everything else runs as-is. Either way, it's handed straight to the connector's query(sql) method, which runs it on the real database (SQLite/pg/mysql2 driver).
  3. Paginate — as the TUI scrolls near the end of a SELECT result, loadMoreRows fetches the next 200-row page (same paging wrapper, next offset) and appends it.

There's no query planner, chunking, or worker pool — the database does its own work, the same way any SQL client uses it.

Connector architecture

Every data source implements the same interface (shared/connectors.ts), so adding a new database type is a self-contained change:

interface Connector {
  id: string;
  type: 'sqlite' | 'postgres' | 'mysql';
  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[]>; // sample rows
  query(sql: string): Promise<{ columns: string[]; rows: Array<string | number | null>[] }>; // direct SQL execution
}

To add a new database type (e.g. MongoDB, ClickHouse, DuckDB):

  1. Implement Connector in shared/connectors/<type>.ts
  2. Register it in shared/connector-factory.ts
  3. Add the new type to the ConnectionConfig['type'] union in shared/connectors.ts
  4. Done — the TUI, query service, and slash commands all pick it up automatically

Walkthrough: adding a DuckDB connector

Step 1 — install the driver

npm install @duckdb/node-api

Step 2 — implement the interface in shared/connectors/duckdb.ts:

import type { Connector, ConnectionConfig, TableMetadata } from '../connectors.js';
import type { ColumnType } from '../types.js';

function mapType(t: string): ColumnType {
  return /INT|REAL|DOUBLE|NUMERIC|DECIMAL|FLOAT/.test(t.toUpperCase()) ? 'number' : 'string';
}

export class DuckDbConnector implements Connector {
  readonly id: string;
  readonly type = 'duckdb' as const;
  readonly config: ConnectionConfig;
  private db: any; // your driver instance

  constructor(config: ConnectionConfig) {
    this.id = config.id;
    this.config = config;
  }

  async connect(): Promise<void> {
    // open the database from config.file / config.host
  }

  async listTables(): Promise<string[]> {
    // query information_schema.tables → names[]
  }

  async getTableMetadata(table: string): Promise<TableMetadata> {
    // query information_schema.columns → { columns, columnTypes }
  }

  async countRows(table: string): Promise<number> {
    // SELECT COUNT(*) FROM "table"
  }

  async readRange(table, startRow, endRow, limit?): Promise<Array<Record<string, unknown>>> {
    // SELECT * FROM "table" LIMIT size OFFSET startRow
    // normalize values: number stays number, null stays null, everything else String(v)
  }

  async query(sql: string): Promise<{ columns: string[]; rows: Array<string | number | null>[] }> {
    // run sql directly, normalize the result set the same way
  }
}

Step 3 — register the factory case in shared/connector-factory.ts:

case 'duckdb': {
  const { DuckDbConnector } = await import('./connectors/duckdb.js');
  return new DuckDbConnector(config);
}

Step 4 — extend the type union in shared/connectors.ts:

export interface ConnectionConfig {
  id: string;
  type: 'sqlite' | 'postgres' | 'mysql' | 'duckdb';
  // ...
}

Step 5 — connect and query it from the TUI's Connect wizard, or via /connect:

/connect duckdb_analytics duckdb data/analytics.duckdb
SELECT COUNT(*) FROM duckdb_analytics.events;

That's the whole integration — direct execution, pagination, error handling, and the TUI all work automatically once the interface is implemented.

Configuration

Environment variables (see .env.example):

Variable Default Description
DBSHELL_CONFIG platform dir Override the global memory directory

Project layout

bin/                 npm bin entry (dbshell)
index.ts             Entry point (npm run lazy): cluster + TUI
commands/            Slash commands (/help, /history, /kill, /connect)
core/                Cluster wiring, global memory (connections + history)
coordinator/         Connector registry, query store, query service (direct SQL execution)
shared/              Types, connector interface + implementations, connector factory
tui/                 Ink TUI (picker / connect wizard / workspace); Backend interface + DirectBackend
scripts/             Demo DB generator
datasets/            demo.sqlite (gitignored)

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages