SQLite: how one SQL statement runs
From sqlite3_prepare_v2 to bytes on disk: the compiler, the virtual machine and the storage engine underneath.
- Source
- sqlite/sqlite @ 77c6cc6
- Drawn
- , by an AI agent
What it shows
SQLite does not interpret SQL. It compiles each statement into a small program and then runs that program on a virtual machine. The diagram follows one statement through both halves, and then down to the file.
Compiling. sqlite3_prepare_v2 hands the SQL text to the tokenizer, which feeds tokens one at a time to a parser generated from parse.y. When the grammar rule for a whole statement completes, its action hands the finished parse tree straight to the code generator: sqlite3Select for a SELECT. The code generator appends instructions to a program, one sqlite3VdbeAddOp call at a time.
Running. sqlite3_step runs that program in sqlite3VdbeExec, a single loop over instructions. The instructions that touch data open cursors on B-trees.
Storing. The B-tree layer never touches a file. It asks the pager for pages by number. The pager owns the cache and the transaction, and reads or writes through an OS layer with one implementation per platform; on Unix a read ends in pread. In write-ahead-log mode, changed pages are appended to the log as frames instead of being written in place, and the log is itself a file written through the same OS layer.
Where every box and arrow comes from
Before this drawing was accepted, a script looked up each box and each arrow in sqlite/sqlite at commit 77c6cc6 (20 November 2026) and failed if one was missing. These are the lines it found.
| From, to | Proof in the source |
|---|---|
| Your application → SQL interfaceSQL |
|
| SQL interface → Tokenizerprepare |
|
| Tokenizer → Parsertokens |
|
| Parser → Code generatorparse tree |
|
| Code generator → Virtual machinebytecode |
|
| SQL interface → Virtual machinestep |
|
| Virtual machine → B-treecursors |
|
| B-tree → Pagerpages |
|
| Pager → OS interfaceread / write |
|
| OS interface → Database file |
|
| Pager → Write-ahead logframes |
|
| Write-ahead log → OS interface |
|
| Box | Proof in the source |
|---|---|
| Your application | Your own program: it is not part of SQLite's source. |
| SQL interface |
|
| Tokenizer |
|
| Parser |
|
| Code generator |
|
| Virtual machine |
|
| B-tree |
|
| Pager |
|
| OS interface |
|
| Database file | The database file on disk. |
| Write-ahead log |
|
How it was made
An AI agent read the project's source at the commit above and drew this page on a WireMagic canvas through Agent Bridge, the same tools any agent gets when you connect it to the app. The result is an ordinary WireMagic file: download it, open it, and move things around.
You can have your own agent do this for a codebase you know. Connect it, then ask it to draw the architecture of the repository.