Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rust_sqlite

> 数据库
Open source

SQLRite - Simple embedded database modeled off SQLite in Rust

1.1K stars0 likes1 views
WebsiteGitHub

About

SQLRite - Simple embedded database modeled off SQLite in Rust

Rust-SQLite (SQLRite)

Rust-SQLite, aka SQLRite , is a simple embedded database modeled off SQLite, but developed with Rust. The goal is get a better understanding of database internals by building one.

What I cannot create, I do not understand. — Richard Feynman

Project website + docs: the marketing + getting-started site is in web/ (Next.js 15 + Tailwind v4). Run cd web && npm install && npm run dev to preview locally; deploys to Vercel out of the box.

     key 
     value 
  

  

    Design and discussions about direction

of the project going on over here.

    Show us your support by buying us a coffee, 

so we can keep building cool stuff. (coming soon)

    Rust API docs on docs.rs
    
  

  

    Come and Chat about databases with us

Read the series of posts about it:

What would SQLite look like if written in Rust?
  • Part 0 - Overview
  • Part 1 - Understanding SQLite and Setting up CLI Application and REPL
  • Part 2 - SQL Statement and Meta Commands Parser + Error Handling
  • Part 3 - Understanding the B-Tree and its role on database design

CREATE TABLE and INSERT Statements

Desktop app

A cross-platform Tauri 2.0 + Svelte 5 desktop GUI ships alongside the REPL (see desktop/ and docs/desktop.md for details).

Prebuilt installers — download from the latest desktop release:

Platform Files
Linux x86_64 .AppImage, .deb (Debian/Ubuntu), .rpm (Fedora/RHEL)
macOS Apple Silicon .dmg, raw .app.tar.gz (Intel Macs not supported yet — universal dmg is a follow-up)
Windows x86_64 .msi, .exe (NSIS)

⚠️ Installers are unsigned until Phase 6.1 wires up Apple Developer ID + Windows code-signing certs. First-launch friction to expect:

  • macOS: "SQLRite is damaged" or "unidentified developer" → run xattr -cr /Applications/SQLRite.app once to strip the quarantine attribute, then it opens normally. The app is fine; Tauri ad-hoc signs every macOS binary (Apple Silicon requires a signature), but quarantined ad-hoc signatures trip a stricter Gatekeeper path with the scary "damaged" wording.
  • Windows: SmartScreen → click "More info" → "Run anyway".
  • Linux AppImage: chmod +x SQLRite_*.AppImage before launching.

From source — cd desktop && npm install && npm run tauri dev. The header's New… / Open… / Save As… buttons cover the file lifecycle; the query editor has a live line-number gutter, ⌘/ (Ctrl+/) SQL comment toggle, and selection-aware Run (highlight a statement to run just that one).

MCP server (drive SQLRite from an LLM agent)

sqlrite-mcp exposes a SQLRite database as a Model Context Protocol stdio server. Spawn it from any MCP client (Claude Code, Cursor, mcp-inspector, …) and the agent gets seven tools — list_tables, describe_table, query, execute, schema_dump, vector_search, plus ask for natural-language → SQL — without any custom integration code.

bash
cargo install sqlrite-mcp

Or grab a per-platform pre-built binary from the latest release (Linux x86_64/aarch64, macOS aarch64, Windows x86_64).

Wire it into Claude Code (~/.claude.json):

json
{
  "mcpServers": {
    "sqlrite": {
      "command": "sqlrite-mcp",
      "args": ["/absolute/path/to/your.sqlrite"],
      "env": { "SQLRITE_LLM_API_KEY": "sk-ant-…" }
    }
  }
}

--read-only opens the DB with a shared lock and hides the execute tool. Full docs + the other six tools' references in docs/mcp.md.

End-to-end example apps

Beyond the per-language quickstarts in examples/, the SQLR-38 umbrella tracks longer, opinionated example apps that exercise SQLRite in real-world shapes:

App SDK What it shows
Python LLM agent with persistent memory Python Vector + lexical recall, fact extraction, summaries — all in one .sqlrite file
Chat-with-your-notes via Claude Desktop MCP Node.js Markdown → hybrid HNSW + BM25 index → sqlrite-mcp --read-only → Claude Desktop
Local-first journaling desktop app Tauri 2 + Svelte 5 Markdown daily-notes, BM25 full-text search with hit highlighting, "ask my journal" panel — entire data layer is one .sqlrite file

Developer guide

In-depth documentation lives under docs/. Start at docs/_index.md — it navigates to:

  • Getting started, Using SQLRite, Architecture
  • Design decisions, Roadmap
  • Internals: File format, Pager, Storage model, SQL engine

Benchmarks

SQLRite ships with a curated benchmark suite that pits the engine against SQLite (and optionally DuckDB) on twelve OLTP, SQL-feature-scaling, and AI-era workloads (vector top-10, BM25, hybrid retrieval). Run locally with make bench (lean, ~5 min) or make bench-duckdb (with the analytical comparator on Group B, ~30 min). Pinned-host JSON envelopes get committed under benchmarks/results/ so trends can be diffed mechanically; benchmarks/scripts/compare.py renders any two runs as a Markdown diff.

The canonical reference carries headline numbers, methodology notes (Q3 SQLite tuning, parser-tax framing), and the engineering debts (SQLR-18 / 19 / 20 / 21) the suite surfaced honestly.

Requirements

Before you begin, ensure you have met the following requirements:

  • Rust (latest stable) – How to install Rust

Usage

Build and launch the REPL:

bash
cargo run

You'll drop into a REPL connected to a transient in-memory database. Use .open to switch to a file-backed database (auto-saves on every statement; see Meta commands).

…

toml [dependencies] sqlrite-engine = "0.14" sqlrite-ask = "0.14"


```rust
use sqlrite::{Connection, ConnectionAskExt};
use sqlrite_ask::AskConfig;

let conn = Connection::open("foo.sqlrite")?;
let cfg  = AskConfig::from_env()?;          // SQLRITE_LLM_API_KEY etc.
let resp = conn.ask("How many users are over 30?", &cfg)?;
println!("Generated SQL: {}", resp.sql);
println!("Why: {}",          resp.explanation);
// Caller decides whether to run resp.sql — the library deliberately doesn't.

Defaults: claude-sonnet-4-6, max_tokens: 1024, schema dump cached for 5 minutes via Anthropic prompt caching (configurable to 1h or off via AskConfig::cache_ttl). Bring your own API key — set SQLRITE_LLM_API_KEY or pass it on AskConfig.

In the REPL: .ask . From an open Connection (this section). Per-product wrappers shipped across 7g.3 – 7g.8: the desktop "Ask…" composer, conn.ask() / db.ask() in the Python / Node / Go SDKs, the WASM SDK's split db.askPrompt() / db.askParse() shape (so the API key never enters the browser), and the MCP ask tool exposed by sqlrite-mcp (so any LLM agent over MCP can call ask against your database directly). See docs/phase-7-plan.md §7g for the full surface plan.

For the canonical Ask reference covering every surface (REPL, desktop, Rust library, Python / Node / Go / WASM), env vars, defaults, prompt caching, and the security model — read docs/ask.md. For copy-paste backend proxy templates the WASM SDK needs (Cloudflare Workers, Vercel Edge, Deno Deploy, Firebase, AWS Lambda, Express), see docs/ask-backend-examples.md.

Roadmap

The project is staged in phases, each independently shippable. A finished phase is committed to main before the next one starts.

Phase 0 — Modernization (done)

  • Rust edition 2024, resolver 3, stable toolchain pinned via rust-toolchain.toml
  • Upgrade every dependency to current majors: rustyline 18, clap 4, sqlparser 0.61, thiserror 2, env_logger 0.11, prettytable-rs 0.10, serde / log latest

Phase 1 — SQL execution surface (done)

  • CLI + rustyline REPL with history, syntax highlighting, bracket matching, line validation
  • Parsing via sqlparser (SQLite dialect); typed SQLRiteError via thiserror
  • CREATE TABLE with PRIMARY KEY, UNIQUE, NOT NULL; duplicate-column detection; in-memory BTreeMap indexes on PK/UNIQUE columns
  • INSERT with auto-ROWID for INTEGER PRIMARY KEY, UNIQUE enforcement, NULL padding for missing columns
  • SELECT — projection, WHERE, ORDER BY, LIMIT
  • JOIN — INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER, CROSS with ON / USING (...) / NATURAL (SQLR-5)
  • UPDATE ... SET ... WHERE ... with type + UNIQUE enforcement at write time
  • DELETE ... WHERE ...
  • Expression evaluator: =/<>/``/>=, AND/OR/NOT, arithmetic +/-/*///%, string concat ||, NULL-as-false in WHERE
  • Replaced every .unwrap() panic on malformed input with typed errors

Phase 2 — On-disk persistence (done)

  • Single-file database format — one .sqlrite file per database
  • Fixed 4 KiB pages; page 0 carries a header (magic SQLRiteFormat\0\0\0, format version, page size, page count, schema-root page)
  • Typed payload pages (schema-root / table-data / overflow) chained via next-page pointers; payloads up to 4089 bytes before spilling into overflow
  • Schema catalog + per-table state serialized via bincode 2.0
  • .open FILENAME — create-or-load a database file
  • .save FILENAME — explicit flush of the in-memory DB to disk (auto-save arrives with Phase 3's pager)
  • .tables — list tables in the current database
  • Header written last during save, so a mid-save crash leaves the file recognizably unopenable

Phase 3 — On-disk B-Tree + auto-save pager (done)

  • 3a — Auto-save: every committing SQL statement (CREATE / INSERT / UPDATE / DELETE) against a file-backed DB auto-flushes; .save is now a rare manual flush
  • 3b — Pager abstraction: long-lived Pager holding a byte snapshot of every page on disk plus a staging area for the next commit; commit diffs staged vs. snapshot and writes only pages whose bytes actually changed; file truncates when the page count shrinks
  • 3c — Cell-based pages (format v2): rows stored as length-prefixed cells (tag-then-value encoding with null bitmap) in TableLeaf pages carrying a SQLite-style slot directory; oversized cells spill into an overflow page chain; the schema catalog itself is now a real table named sqlrite_master stored in the same cell format
  • 3d — B-Tree: InteriorNode pages above the existing leaves; save rebuilds the tree bottom-up from the in-memory sorted rows; open descends to the leftmost leaf and scans forward via the sibling next_page chain. Interior cells share the cell_length | kind_tag | body prefix with local/overflow cells so binary search over slot directories works uniformly. Cursor / lazy-load reads deferred to Phase 5.
  • **3e — Secondary index

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustcomputer-sciencedatabase-designdatabasesrust-lang

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库