Skip to main content

PyDB

An educational database engine built from scratch in Python.

PyDB is a fully functional relational database that stores data in tables, supports SQL queries, and manages transactions -- all written from the ground up as a learning project. Built incrementally using TDD, every concept is explained with real-world analogies a 12-year-old can follow.

Features

These are wired into the database engine -- run them through SQL and the executor uses them automatically:

  • Full SQL support -- SELECT, INSERT, UPDATE, DELETE, CREATE/DROP TABLE
  • JOINs -- cross-reference rows from two tables (aggregates supported)
  • Aggregations -- COUNT, SUM, AVG, MIN, MAX with GROUP BY and HAVING
  • Subqueries -- scalar and IN subqueries in WHERE clauses
  • Views -- saved queries as virtual tables (in-memory; not persisted)
  • B-Tree indexes -- CREATE/DROP INDEX; equality lookups use the index automatically; index definitions are saved and rebuilt on load
  • Query planner -- EXPLAIN shows scan vs. index lookup decisions
  • Constraints -- PRIMARY KEY, NOT NULL, UNIQUE (duplicates are found with one look-up in a register of values, not by reading every row)
  • Dates and times -- DATE and TIMESTAMP columns (stored in UTC), with DATE '…' / TIMESTAMP '…' literals in SQL
  • NULL -- nullable columns, IS NULL / IS NOT NULL, and three-valued logic (TRUE / FALSE / UNKNOWN) in WHERE, ON and HAVING
  • Transactions -- commit/rollback via an undo log (each change notes how to undo itself, so no table is ever copied), also as with Transaction(db):
  • Durable databases -- Database(path, journal=True) writes every commit to a checksummed journal before it counts, recovers after a crash, and checkpoints to keep the journal short
  • Locks -- threads take turns on one database lock; a LOCK file stops a second program opening the same journalled folder
  • Storage engine -- JSON persistence for table schemas and rows
  • Interactive REPL -- type SQL and see pretty-printed results

Standalone teaching modules

These live in their own modules and work with a Database, but they are not yet wired into the Database/executor pipeline -- import and drive them directly to see how each idea works:

  • Write-Ahead Log (pydb.wal) -- crash recovery via operation logging (the real database uses its own journal: see "Durable databases" below)
  • MVCC (pydb.mvcc) -- multi-version concurrency for snapshot isolation
  • CSV import/export (pydb.csv_io) -- load and save spreadsheet files
  • Outbox pattern (pydb.outbox) -- atomic DB writes + message queue delivery

Note on persistence: save()/load() persist table schemas, rows and index definitions. Views live in memory only, so they are recreated rather than restored on restart. Without journal=True, nothing is safe on disk until you call save().

Note on updates: Table.update() is copy-on-write: it returns a new Record, and a Record you fetched earlier keeps its old values, so rows you are reading never change under you. Fetch the row again (get() or select()) to see the new values. See docs/concepts/journal.md for the other ways every database now differs from before.

Example

pydb> CREATE TABLE cards (name TEXT NOT NULL, type TEXT, power INTEGER)
Table 'cards' created

pydb> INSERT INTO cards VALUES ('Pikachu', 'Electric', 55)
1 row inserted

pydb> SELECT type, COUNT(*), AVG(power) FROM cards GROUP BY type
┌──────────┬──────────┬────────────┐
│ type     │ COUNT(*) │ AVG(power) │
├──────────┼──────────┼────────────┤
│ Electric │        1 │       55.0 │
└──────────┴──────────┴────────────┘

pydb> EXPLAIN SELECT * FROM cards WHERE name = 'Pikachu'
Full table scan on cards

Durable databases

Open a database with journal=True and every commit is written to journal.log -- and forced onto the disk -- before it returns. Reopening the folder (even after a crash) replays the journal, so committed work is never lost and unfinished transactions leave no trace:

import tempfile
from datetime import UTC, date, datetime
from pathlib import Path

from pydb.database import Database
from pydb.schema import Column, Schema
from pydb.transaction import Transaction
from pydb.types import DataType

with tempfile.TemporaryDirectory() as tmp:
    folder = Path(tmp) / "jobs"
    schema = Schema(columns=[
        Column("job", DataType.TEXT),
        Column("run_date", DataType.DATE),
        Column("started", DataType.TIMESTAMP),
    ])
    with Database(folder, journal=True) as db:      # every commit is fsynced
        runs = db.create_table("runs", schema)
        runs.insert({"job": "backup", "run_date": date(2026, 10, 17),
                     "started": datetime(2026, 10, 17, 2, 0, tzinfo=UTC)})
        with Transaction(db) as txn:                 # all-or-nothing, one commit
            txn.get_table("runs").insert({"job": "report", "run_date": date(2026, 10, 17),
                                          "started": datetime(2026, 10, 17, 7, 30, tzinfo=UTC)})

    with Database(folder, journal=True) as db:      # reopen: recovered from disk
        print([row["job"] for row in db.get_table("runs").select()])

Output:

['backup', 'report']

Options: sync=False skips the fsync (fast, but a power cut can lose the last commits), checkpoint_bytes sets when the journal is checkpointed automatically (4 MiB by default), and repair=True opens a journal damaged in the middle by keeping the commits before the damage. save() and close() take a checkpoint. See it survive a real crash with uv run python examples/crash_and_recover.py, and read the "Durable Databases" learning path in docs/index.md.

Quick Start

# Install dependencies
uv sync --all-extras

# Launch the interactive REPL
uv run pydb

# Run tests
uv run pytest

# Lint and type check
uv run ruff check .
uv run pyright src tests

Documentation

Full docs (with kid-friendly explanations of every idea): https://robcox2910.github.io/pydb/

Install

PyPI

pip install fromscratch-pydb

Or get the whole series at once: pip install fromscratch-pystack.

Developing alongside a sibling

PyDB has no sibling dependencies of its own, but PyStack depends on a PyDB release from PyPI (fromscratch-pydb), and its uv.lock records the exact version. A change merged here can't affect PyStack until PyDB publishes a release and PyStack chooses to upgrade.

To try an unreleased PyDB change from a PyStack checkout next to this one, install it over the released version:

cd ../pystack
uv pip install -e ../pydb
uv run --no-sync pytest

Use uv run --no-sync while you do this: a plain uv run (like uv sync) puts the released version back, which is how you undo the override.

Releasing

Other projects in the series (PyStack) use a released version of this one from PyPI, not whatever is on main. To publish a change for them:

  1. Merge the change to main.
  2. Release it: gh release create vX.Y.Z --target main --generate-notes (or push a vX.Y.Z tag); the release workflow publishes it to PyPI. A change to the public API bumps the minor version (v0.1.0 → v0.2.0); anything else bumps the patch (v0.1.0 → v0.1.1).
  3. In each project that uses it, raise the fromscratch-pydb>=X.Y.Z floor in pyproject.toml, run uv lock --upgrade-package fromscratch-pydb, and open a pull request so CI checks the pair together.

This project is one of a series that builds real systems "from scratch in Python" to teach how they work. See the series home for the full story.

Project What it teaches Repository Docs PyPI
PyOS Operating systems py-os Docs fromscratch-pyos
Pebble Compilers and programming languages pebble-lang Docs fromscratch-pebble
PyDB Relational databases pydb Docs fromscratch-pydb
PyKV Key-value stores pykv Docs fromscratch-pykv
PyDocDB Document databases pydoc-db Docs fromscratch-pydocdb
PyGraphDB Graph databases pygraphdb Docs fromscratch-pygraphdb
PyTSDB Time-series databases pytsdb Docs fromscratch-pytsdb
PyVecDB Vector databases pyvecdb Docs fromscratch-pyvecdb
PyColDB Column-family databases pycoldb Docs fromscratch-pycoldb
PyCrypt Cryptography pycrypt Docs fromscratch-pycrypt
PyNet Computer networking pynet Docs fromscratch-pynet
PyWeb HTTP web servers pyweb Docs fromscratch-pyweb
PyGit Version control pygit Docs fromscratch-pygit
PySearch Search engines pysearch Docs fromscratch-pysearch
PyMQ Message queues pymq Docs fromscratch-pymq
PyLLM Language models (the brain) pyllm Docs fromscratch-pyllm
PyScheduler Job scheduling pyscheduler Docs fromscratch-pyscheduler
PyStack Full-stack integration pystack Docs fromscratch-pystack

License

MIT

Metadata

Release files for fromscratch-pydb 0.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fromscratch-pydb 0.5.1
File Size Uploaded Provenance Actions
fromscratch_pydb-0.5.1.tar.gz 298.9 kB With provenance Details for fromscratch_pydb-0.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fromscratch-pydb 0.5.1
File Interpreter ABI Platform Actions
fromscratch_pydb-0.5.1-py3-none-any.whl Python 3 none any Details for fromscratch_pydb-0.5.1-py3-none-any.whl

Total release size: 399.7 kB

Release files / fromscratch_pydb-0.5.1.tar.gz

Download URL fromscratch_pydb-0.5.1.tar.gz
Size 298.9 kB
Tags Source
SHA-256 checksum
How to use checksums
5fa48ea6e508159732204293211317737f616ba31ac6d1ca9dd864e490ff3adf
BLAKE2b-256 checksum
How to use checksums
6ebfd1e45643dcc05cebb19da62a4c238ed928dc42c22e5ad52e4e9eb8161556
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / fromscratch_pydb-0.5.1-py3-none-any.whl

Download URL fromscratch_pydb-0.5.1-py3-none-any.whl
Size 100.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
76aa468c0661f255b2f10d224af8959fead6c6d553d769962f380868e657f00b
BLAKE2b-256 checksum
How to use checksums
49f4e108006a54ba0dc4fd7f7e9b546d8301421e0d7d224e20026a0cc5752929
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for fromscratch-pydb 0.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fromscratch_pydb-0.5.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.5.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page