Metadata-Version: 2.4
Name: db33studio
Version: 1.0.1
Summary: A local, single-user database client for PostgreSQL, MySQL, SQLite and Redis.
Author: hussein
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/hussein/db33studio
Project-URL: Repository, https://github.com/hussein/db33studio
Project-URL: Issues, https://github.com/hussein/db33studio/issues
Keywords: database,database-client,sqlite,postgresql,mysql,redis
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Web Environment
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi==0.163.2
Requires-Dist: uvicorn[standard]==0.54.0
Requires-Dist: python-dotenv==1.2.4
Requires-Dist: pydantic==2.14.3
Requires-Dist: structlog==26.1.0
Requires-Dist: aiosqlite==0.21.0
Requires-Dist: psycopg[binary]==3.3.4
Requires-Dist: aiomysql==0.3.2
Requires-Dist: redis==8.2.0
Provides-Extra: dev
Requires-Dist: pytest==9.2.0; extra == "dev"
Requires-Dist: httpx==0.28.1; extra == "dev"
Requires-Dist: pytest-asyncio==1.5.0; extra == "dev"
Requires-Dist: fakeredis==2.41.0; extra == "dev"
Dynamic: license-file

# DB33 Studio

A local, single-user database client for **PostgreSQL**, **MySQL**, **SQLite**
and **Redis**. One FastAPI backend, one Svelte 5 single-page app. It gives you
the everyday parts of a desktop DB tool in the browser: a schema tree, a paged
data grid with raw `WHERE` / `ORDER BY`, a structure view with constraints,
indexes, foreign keys and DDL, a SQL editor with multi-statement results, and a
Redis key browser with a command bar.

![Table data, dark theme](docs/screenshots/table-data-dark.png)

## Features

| | PostgreSQL | MySQL / MariaDB | SQLite | Redis |
| --- | --- | --- | --- | --- |
| Save / test / edit connections | yes | yes | yes | yes |
| Schema tree (tables, views, enums) | yes | yes (databases as schemas) | tables + views | logical DB |
| Paged table data, filter, sort, inspect | yes | yes | yes | not applicable |
| Row inspector with FK navigation | yes | yes | yes | not applicable |
| Structure: columns, keys, constraints, indexes | yes | yes | yes | not applicable |
| Table DDL | reconstructed | `SHOW CREATE TABLE` | from `sqlite_master` | not applicable |
| SQL editor, multi-statement | yes | yes | yes | command bar instead |
| Read-only SQLite file mode | - | - | yes | - |
| Key browser with SCAN and type filter | - | - | - | yes |
| Key detail for string/hash/list/set/zset/stream | - | - | - | yes |
| Command bar with admin-command blocklist | - | - | - | yes |
| TTL / rename / delete keys | - | - | - | yes |

Every SQL engine supports connection testing with the server version and
latency, CSV export of the loaded rows, and both themes. Redis connections test
the same way and open the key browser instead of the table and query tabs.

## Project layout

```
src/db33studio/    Python package: FastAPI app, engines, handlers, SQL migrations
web/               Svelte 5 + TypeScript + Tailwind source for the UI
scripts/           build_ui.py (stage the compiled UI), seed_demo.py
tests/             pytest suite
docs/              API contract, engine notes, screenshots
```

## Architecture

```
src/db33studio/              FastAPI package and all target-database access
  main.py server.py          entrypoint, app factory, lifespan (migrations)
  db.py                      aiosqlite wrapper for the local metadata store
  engines/
    base.py                  Engine ABC, dataclasses, identifier/value/SQL helpers
    registry.py              open_engine(record), test_engine(record)
    sqlite.py postgres.py mysql.py redis.py
    redis_commands.py        Redis command tokenizer + blocklist (pure functions)
  model/connections/         Pydantic DTOs and the connections service
  model/tabs/                workspace tab DTOs and the tabs service
  handlers/                  thin routers: connections, tables, query, redis, tabs, UI
  lib/                       response envelope, errors, migrations
  migrations/                the app's own SQLite schema
  webui/                     compiled UI, written by scripts/build_ui.py (gitignored)

web/                         Svelte 5 + TypeScript + Tailwind v4 SPA
  src/App.svelte             shell, routing between screens
  src/lib/api/               typed client: connections, schema, query, redis, tabs
  src/lib/stores/            theme, layout panels, connections, workspace tabs, catalog, toasts
  src/lib/tabs.ts            tab reordering and id helpers, pure functions
  src/lib/lines.ts           line counts and gutter widths, pure functions
  src/lib/components/
    layout/                  title bar, connection rail, jump search, theme toggle
    connections/             new/edit connection screen
    schema/                  object tree
    data/ data grid           shared by the table and query tabs
    workspace/               tab strip with drag reorder, empty state
    table/                   table tab: data, filters, inspector, structure
    query/                   SQL editor and per-statement results
    highlight/               per-dialect highlighting for the query editor and Redis command bar
    redis/                   key list, key detail, command bar
    ui/                      buttons, inputs, badges, modal, toasts, icons
  tests/                     vitest for pure helpers

scripts/
  build_ui.py                builds web/, copies web/dist into src/db33studio/webui
  seed_demo.py               reproducible SQLite demo database
tests/                       pytest suite
docs/                        CONTRACT.md, db.md, engines.md, screenshots/
```

Handlers never talk to a driver. They resolve the saved connection, open one
engine from `engines/registry.py` for the request, and close it again. Engines
are the only place with dialect SQL. The full API and data-shape contract lives
in [docs/CONTRACT.md](docs/CONTRACT.md).

## Requirements

- Python 3.11+ (tested on 3.14)
- Node 20.19+ and npm (tested on Node 24, npm 12)
- A reachable PostgreSQL / MySQL / Redis server only if you want to use those
  engines. SQLite needs nothing extra.

## Setup and run

From the repo root:

```bash
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -e ".[dev]"

python scripts/build_ui.py          # builds web/ and copies the compiled UI into src/db33studio/webui
python -m db33studio --debug        # or: db33studio --debug -> http://127.0.0.1:2100
```

The editable install pulls the runtime and dev dependencies from
`pyproject.toml`; there is no `requirements.txt`. `scripts/build_ui.py` installs
the npm packages if `web/node_modules` is missing, runs `npm run build`, and
stages `web/dist` into `src/db33studio/webui` where the server serves it from.
Run the suite with `python -m pytest` from the repo root.

Copy `.env.example` to `.env` if you want to change the defaults; the built-in
defaults work as-is.

For UI work with hot reload, run Vite in a second terminal:

```bash
cd web
npm install
npm run dev                 # http://localhost:5173
```

Vite proxies `/api` to `127.0.0.1:2100`. For a production build,
`npm run build` writes `web/dist`; serve it from any static server that proxies
`/api` to the backend, or set `VITE_API_BASE` to an absolute API URL at build
time.

Environment variables (see `.env.example`):

| variable | default | meaning |
| --- | --- | --- |
| `HOST` | `127.0.0.1` | bind address when not running `--debug` |
| `PORT` | `2100` | backend port |
| `DATABASE_PATH` | per-user data dir | optional path to the app's own SQLite file with saved connections |
| `QUERY_TIMEOUT_SECONDS` | `30` | per-request budget for tables, queries and Redis |

The server binds loopback only, because the app has no authentication and its
metadata file holds saved passwords. Set `HOST=0.0.0.0` deliberately if you want
to reach it from another machine, and treat that as exposing your databases.
`--debug` also binds `127.0.0.1`, and additionally enables auto-reload.

## Demo database

The SQLite demo is reproducible and safe to re-run (it rewrites
`data/demo.db` only):

```bash
python scripts/seed_demo.py
# Seeded .../data/demo.db with 10 customers and 40 orders.
```

Then create a connection in the UI with engine SQLite and the absolute path to
`data/demo.db`. The database has `customers`, `orders` (FK, check
constraints, NULLs, two indexes) and a `daily_revenue` view.

For Redis, any reachable server works. The browser uses `SCAN`, never `KEYS`,
so an empty database simply shows the empty state.

## How to use it

1. **Connect.** First run opens the connection screen. Pick an engine, fill in
   the form, press **Test** (server version and latency appear), then **Save &
   connect**. Saved connections stay available in the rail on the left; the
   chip in the title bar reopens the editor.
2. **Browse.** The object tree groups tables, views and enums. The filter box is
   local and instant. `Ctrl/Cmd+K` jumps to any table or view. The panel button
   beside the logo, or `Ctrl/Cmd+B`, hides the sidebar; the Redis key list uses
   the same toggle, and the choice is remembered per browser. With the sidebar
   hidden the main pane takes the full width.
3. **Table data.** Column headers show type, `PK` and `FK` badges. Use the
   `WHERE` and `ORDER BY` inputs for raw SQL fragments, choose a page size and
   press Apply. Click a row number to open the inspector; foreign keys get an
   "Open ... row" button that opens the target table filtered to that value. The
   inspector is a right sidebar with its own panel toggle in the table toolbar,
   also remembered per browser.
4. **Structure.** Switch the toolbar to Structure for columns, constraints,
   indexes, the foreign-key graph and the DDL. The DDL block has a line-number
   gutter that stays in place while the code scrolls sideways; the numbers are
   decorative, so they never end up in a copy. Constraint definitions, index
   definitions and the DDL block are highlighted with the connection's dialect,
   and long definitions wrap instead of clipping. Copy or export the DDL.
5. **Queries.** The `+` in the tab bar or the empty state opens a query tab.
   Tabs survive a reload or an app restart: the open queries with their text,
   the table tabs with their filter, ordering and Data/Structure view, plus the
   active tab and the tab order, are stored per connection in the app's own
   metadata database (not the target database) and restored when you open that
   connection again. Closing a tab deletes it for good. Drag a tab to reorder
   the strip, or focus it and press `Alt+Left` / `Alt+Right`. The editor has a
   line-number gutter that scrolls with the code.
   The editor is a resizable pane: drag the splitter under it, use
   `ArrowUp`/`ArrowDown` on the splitter, or double-click it to reset. The height
   is remembered per browser. Highlighting follows the active engine
   (PostgreSQL, MySQL, SQLite or Redis) and needs no editor dependency.
   The editor completes as you type: keywords and functions ranked by what the
   caret expects, table and view names after `FROM` / `JOIN` / `INTO` /
   `UPDATE`, schema (MySQL: database) names once the connection has more than
   one, and column names bare, `alias.` or `table.` for the tables the statement
   mentions. `Tab` accepts the highlighted row, `Enter` accepts it only while a
   word is half typed, `Ctrl/Cmd+Space` opens the list and `Escape` closes it
   without leaving the editor. Columns are fetched per table on demand and
   dropped after a run, so `CREATE` / `ALTER` is reflected immediately.
   `Ctrl/Cmd+Enter` runs the selection when there is one, otherwise the whole
   buffer. Multiple `;`-separated statements each get a result
   tab, with rows, affected counts and durations. Every run reports its outcome:
   "Running query" while it is in flight, then a green "Query succeeded" strip
   with statement, row and duration counts, or a red "Query failed" strip with
   the server message and Retry. A matching status chip sits in the tab toolbar
   and stays put after the strip is dismissed.
6. **Redis.** Pick a Redis connection and browser mode opens: MATCH pattern,
   type chips, keys grouped by prefix with TTLs, Load more for the next SCAN
   page, per-type detail with paging, Rename / Set TTL / Delete, and a command
   bar that prints readable results for nested replies.
7. **Theme.** The title-bar toggle switches dark and light. The choice is kept in
   `localStorage`.

## Keyboard shortcuts

Every toolbar button advertises its chord in the hover title. `Ctrl/Cmd` is used
for app-wide actions so typing in a field never loses a character; `Alt` is used
for the actions of the panel that is on screen, and the panel owns them: while a
table tab is open `Alt+R` refreshes the table, otherwise it refreshes the tree.

| Action | Keys |
| --- | --- |
| Run query (selection, else everything) | `Ctrl/Cmd+Enter` |
| Complete the word under the caret | `Ctrl/Cmd+Space` |
| Jump to a table or view | `Ctrl/Cmd+K` |
| Show / hide the sidebar | `Ctrl/Cmd+B` |
| Switch dark / light | `Ctrl/Cmd+Shift+L` |
| Connections screen | `Alt+C` |
| New query / new connection | `Alt+N` / `Alt+Shift+N` |
| Close tab | `Alt+W` |
| Previous / next tab | `Alt+Shift+Left` / `Alt+Shift+Right` |
| Move the open tab | `Alt+Left` / `Alt+Right` |
| Data / Structure view | `Alt+1` / `Alt+2` |
| Row inspector | `Alt+I` |
| Refresh the current panel, or retry | `Alt+R` |
| Export the current grid (CSV) or the DDL | `Alt+S` |
| Copy DDL / copy the inspected row as JSON | `Alt+Shift+C` |
| Dismiss the query outcome strip | `Alt+Shift+D` |
| Previous / next page (table rows, Redis keys and entries) | `Alt+[` / `Alt+]` |
| Run command (Redis), apply filters, save and connect | `Alt+Enter` |
| Rename / Set TTL / Delete a Redis key | `Alt+M` / `Alt+T` / `Alt+Delete` |
| Test / save a connection | `Alt+T` / `Alt+S` |
| Close a dialog, cancel the connection form | `Esc` |

## Tests

Backend (from the repo root):

```bash
python -m pytest
```

The suite covers the SQLite engine end to end, connection CRUD and validation,
table/query endpoints, workspace tab persistence, the Redis tokenizer and a
fakeredis-backed Redis engine. It runs against temporary databases and never
touches a real server.

Optional live engine checks create and drop one probe table in the configured
database, then disconnect:

```bash
TEST_POSTGRES_DSN=postgresql://user:pass@127.0.0.1:5432/testdb python -m pytest -q
TEST_MYSQL_DSN=mysql://user:pass@127.0.0.1:3306/testdb python -m pytest -q
```

Frontend (from `web/`):

```bash
npm run check     # svelte-check, zero warnings expected
npm test          # vitest, pure helpers only
npm run build
```

## Package / PyPI

The wheel bundles the compiled UI and the SQL migrations, so one install serves
both the SPA and the API. `pip` puts a `db33studio` command on your `PATH`:

```bash
python scripts/build_ui.py && python -m build --wheel   # dist/db33studio-<version>-py3-none-any.whl

pip install db33studio
db33studio                  # then open http://127.0.0.1:2100
db33studio --help           # --port 8080, or --debug for auto-reload
```

It runs from any directory: the UI and the migrations are read from the
installed package, and the connection list lives in your per-user data
directory. `python -m db33studio` is the same entry point if you prefer it.

The Svelte source in `web/` is never part of the wheel: build the UI first, then
build the wheel. Distribution metadata (version, dependencies, console script)
lives in `pyproject.toml`, and the version comes from `db33studio.__version__`.

## Supported operations and limitations

- **Raw SQL is intentional.** The `WHERE` and `ORDER BY` fields and the query
  editor send SQL to the server verbatim. The app does not parse or sanitise
  them. `UPDATE`, `DELETE`, `DROP` and friends will run, and there is no
  transaction history or undo. Use a read-only connection where it matters.
- **Local single-user storage.** Saved connections and the open tabs of each
  connection live in the app's own SQLite file in the per-user data directory
  (`~/.local/share/db33studio/app.db` on Linux,
  `%LOCALAPPDATA%\db33studio\app.db` on Windows,
  `~/Library/Application Support/db33studio/app.db` on macOS), overridable with
  `DATABASE_PATH`. There is no login, no sharing and no encryption. The backend
  has no authentication; run it on localhost (`python -m db33studio --debug`)
  unless you have put your own access control in front of it.
- **Passwords are stored in plaintext.** The password column in that database
  file is not encrypted. The API never returns it (responses
  expose `has_password` only) and the UI never renders it, but anyone who can
  read that file can read the credentials. Prefer dedicated read-only database
  users, and delete connections you no longer need.
- **Limits.** Query results are capped at 5000 rows; table pages at 1000 rows
  (default 100); Redis scans and key detail pages at 1000 entries. Every
  request has a 30 s budget by default (`QUERY_TIMEOUT_SECONDS`).
- **Identifiers versus values.** Schema and table names are validated against a
  conservative pattern and quoted per dialect. Filter values must be written as
  SQL literals by you, because the whole clause is raw.
- **Redis.** `SCAN` is used for key listing, so a pattern is not a `KEYS` scan
  and type filtering happens after `TYPE` per key. Server administration is
  blocked in the command bar: `CONFIG`, `SHUTDOWN`, `DEBUG`, `MONITOR`,
  `SAVE`, `BGSAVE`, `FLUSHALL`, `FLUSHDB`, `MIGRATE`, `REPLICAOF`, `SLAVEOF`,
  `ACL`, `MODULE`, `SCRIPT`, `EVAL`, `EVALSHA`, `FUNCTION`.
- **No schema editing.** This client reads and queries data; it does not create
  or alter tables. Use a migration tool for that.
- **DDL fidelity.** PostgreSQL DDL is reconstructed from catalogs and is
  readable but not byte-identical; if the catalogs are not readable by the
  connected role, `ddl` is `null`. MySQL DDL comes from `SHOW CREATE TABLE`;
  index sizes are not exposed and are `null`. SQLite DDL is the stored
  `CREATE` statement.
- **Row counts.** Tree estimates are server statistics (PostgreSQL `reltuples`,
  MySQL `TABLE_ROWS`), not exact. The grid footer comes from a real `COUNT(*)`
  with the current filter.
- **Not included.** SSH tunnels, cloud IAM auth, schema diffs, import files,
  saved query library, TLS client certificates, and multi-user access.

## Screenshots

| | |
| --- | --- |
| ![New connection](docs/screenshots/new-connection-dark.png) | ![Table structure](docs/screenshots/table-structure-dark.png) |
| ![Query tab](docs/screenshots/query-dark.png) | ![Redis browser](docs/screenshots/redis-dark.png) |

| | |
| --- | --- |
| ![Table data, light theme](docs/screenshots/table-data-light.png) | ![Query tab, light theme](docs/screenshots/query-light.png) |

All screenshots are 1440x900 PNGs in [docs/screenshots](docs/screenshots).

## License

Apache License 2.0. See [LICENSE](LICENSE).

Copyright 2026 hussein.
