moonsqlite-inspect

    Reconstruct and compare offline SQLite WAL commits in pure MoonBit

    Download zip
    Author
    Version
    0.3.2
    License
    Apache-2.0
    Last updated
    5 days ago
    Downloads
    29

    #MoonSQLite Inspect

    Open and compare committed versions of an offline SQLite database. Given a checkpointed baseline and the WAL written after it, MoonSQLite Inspect can read an earlier revision, compare two revisions by rowid and trace each reported cell to its page in the baseline or to a specific WAL frame. The history index and row comparisons are implemented in MoonBit and use MoonSQLiteFile for WAL verification and record decoding. The CLI uses Node.js for file input and hashing. MoonSQLiteFile

    #Install the library

    Add the module to an existing MoonBit project.

    moon add sssssurf/moonsqlite-inspect@0.3.2

    Import the package in that project's moon.pkg.

    import {
    "sssssurf/moonsqlite-inspect" @inspect,
    }

    Use the checkpointed baseline and WAL bytes from the capture workflow below.

    fn first_commit_changes(
    base : Bytes,
    wal : Bytes,
    ) -> Array[@inspect.VersionedChange] raise @inspect.InspectError {
    let history = @inspect.open_wal_timeline(base, wal)
    @inspect.diff_revisions(history.snapshot(0), history.snapshot(1), "status")
    }

    The library builds on JS, native, Wasm and Wasm GC. JS shares read-only frame slices with the upstream validator. The other targets copy the requested frame bytes. The CLI entry point is supported on JS with Node.js 24. Mooncakes package

    #Reproduce a WAL history

    Run the following commands from the repository root with MoonBit, Node.js and Python 3.10 or later. Python's SQLite extension generates the demonstration capture. Use a fresh output directory to regenerate it.

    moon update moon build --target js python scripts/wal_demo.py _build/wal-demo node _build/js/debug/build/cmd/main/main.js wal-verify _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal _build/wal-demo/capture.json node _build/js/debug/build/cmd/main/main.js wal-history _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal node _build/js/debug/build/cmd/main/main.js wal-rows _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 1 status node _build/js/debug/build/cmd/main/main.js wal-changes _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 0 1 status node _build/js/debug/build/cmd/main/main.js wal-changes _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 1 2 status node _build/js/debug/build/cmd/main/main.js wal-changes _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 0 2 status node _build/js/debug/build/cmd/main/main.js wal-series _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 0 3 status --limit 2 --manifest _build/wal-demo/capture.json

    The demo creates four SQLite commits. Revision 0 is the baseline. Row 41 changes from ready to waiting in revision 1 and returns to ready in revision 2. The two adjacent comparisons each report one change. The comparison from 0 to 2 returns an empty entries array. Reported rows identify the cell's page payload offset and, for WAL pages, the frame and revision that supplied that page.

    wal-series compares every adjacent pair in the requested interval, including pairs with zero changes. Each invocation indexes the WAL once and returns up to 32 comparisons by default. Use --limit to request 1–1024 comparisons. The demo returns next_from: 2, so the next call uses 2 3 status. A null continuation marks completion. Each response is limited to 8 MiB. If it exceeds the limit, retry with fewer comparisons or use the library's row visitor for a large individual comparison. Revision 4 in the demo changes the table definition, so the series stops at revision 3.

    wal-verify checks file sizes, SHA-256 digests and the WAL epoch against capture.json, then reports the validated timeline. Provide --manifest FILE to apply the same check before any history read or comparison. To make your own bundle, use the capture helper with a SQLite writer you control. It keeps a read transaction open from the checkpointed baseline through export. The CLI accepts up to 64 MiB per database or WAL file. Use the latest-snapshot commands below for a consistent same-time database/WAL pair. Capture and snapshot details

    From MoonBit, open the capture once with open_wal_timeline(base, wal). Use commits() to list revisions, snapshot(revision) to read stored rows and diff_revisions(before, after, name) for a pair with matching table definitions. visit_adjacent_changes emits ordered changes and completion events one comparison at a time. page_origin(page) gives the underlying byte location of a logical page.

    #Inspect a backup or the latest snapshot

    Use a stable offline database copy. For latest-snapshot commands, the database and WAL must belong to the same static capture. Omitting the WAL shows the main image alone.

    node _build/js/debug/build/cmd/main/main.js catalog backup.sqlite node _build/js/debug/build/cmd/main/main.js table backup.sqlite samples node _build/js/debug/build/cmd/main/main.js index backup.sqlite samples_n node _build/js/debug/build/cmd/main/main.js row backup.sqlite samples 4000 node _build/js/debug/build/cmd/main/main.js range backup.sqlite samples 100 900 25 node _build/js/debug/build/cmd/main/main.js table capture.sqlite samples --wal capture.wal node _build/js/debug/build/cmd/main/main.js diff before.sqlite after.sqlite samples node _build/js/debug/build/cmd/main/main.js wal-diff capture.sqlite samples --wal capture.wal

    index also reads WITHOUT ROWID tables in their physical key order. diff compares signed rowids in tables with identical stored SQL definitions and reports added, removed and changed records. It walks the two tables row by row and retains the changes. wal-diff compares the main image with the committed snapshot reconstructed from its WAL. Each record includes the physical source location. JSON uses decimal strings for 64-bit integers and rowids and hexadecimal strings for blobs.

    row and range work with ordinary rowid tables, and both accept an optional --wal WAL. They follow B-tree branches that intersect the requested keys. row returns an empty entries array if the key is absent. range takes inclusive signed 64-bit bounds and a positive row limit. When next_rowid is a decimal string, use it as the next request's first bound with the same snapshot and upper bound. A null value marks the last page.

    The corresponding library methods are Snapshot::find_row and Snapshot::scan_rowid_range. They work on the in-memory snapshot returned by open_snapshot, including its committed WAL pages.

    The reader supports UTF-8, UTF-16LE and UTF-16BE databases with SQLite page sizes from 512 through 65,536 bytes. It validates cell boundaries, freeblock chains and rowid ranges in the B-trees it visits. It returns the SQLite storage classes and field order from each physical record. For an INTEGER PRIMARY KEY alias, the key appears in rowid and its stored column remains NULL. SQL projections and schema-derived defaults belong to the query layer. The library caps each decoded record at 16 MiB and the CLI caps each input file at 64 MiB.

    #Reproduce verification

    moon test --target js --frozen moon build --target js --frozen python -B scripts/sqlite_oracle.py python -B scripts/verify_distribution.py

    The oracle checks 6,012 legacy table, index and WITHOUT ROWID records across three page sizes and three encodings. It compares signed rowid lookups, pagination and differences with SQLite queries and checks page provenance against raw cell bytes. WAL coverage includes historical reads and adjacent changes for all nine encoding/page-size combinations, truncation and regrowth, partially written tails, uncommitted frames, batch continuation, overflow-only updates, output limits and rejection of mismatched capture files. SQLite file format

    verify_distribution.py unpacks the current distribution and uses it in a separate consumer project. Three public API tests run on each of the four backends. They check snapshot reads, changes that are later reversed, signed 64-bit rowids, event order, cancellation, budgets and schema mismatch errors. To verify the published release using a new registry installation, update the index and run the registry mode.

    moon update python -B scripts/verify_distribution.py --registry --version 0.3.2

    After building the CLI, python -B scripts/benchmark.py measures latest WAL loading, backup comparison and point lookup. Add --history to measure indexing 12,000 commits and --compare-export to compare full exports of an 8,000-row BLOB table. Pass --baseline /path/to/main.js to run the paired cases against an earlier build. The benchmark checks matching results before reporting times.

    #Source and license

    MoonSQLite Inspect and the MoonSQLiteFile 0.8.1 dependency use Apache-2.0. The project builds on the upstream public APIs. Its own timeline indexes page lifetimes across all available revisions, compares stored rows and reports version-specific cell provenance. The SQLite engine is used by the demo and verification scripts. Upstream release · Hackathon review and acceptance notes

    InspectError

    pub suberror InspectError {
    Invalid(String)
    Unsupported(String)
    NotFound(String)
    }

    CatalogEntry

    pub struct CatalogEntry {
    kind : String
    name : String
    table : String
    root_page : Int
    sql : String?
    }

    IndexRecord

    pub struct IndexRecord {
    page : Int
    cell_offset : Int
    values : Array[Value]
    }

    PageOrigin

    pub(all) enum PageOrigin {
    MainPage(Int64)
    WalFrame(WalPageOrigin)
    }

    Offsets point to page payloads. WAL offsets exclude the 24-byte frame header.

    Row

    pub struct Row {
    rowid : Int64
    page : Int
    cell_offset : Int
    values : Array[Value]
    }

    RowChange

    pub(all) enum RowChange {
    Added(Row)
    Removed(Row)
    Changed(Row, Row)
    }

    RowidPage

    pub struct RowidPage {
    rows : Array[Row]
    next_rowid : Int64?
    }

    Snapshot

    pub struct Snapshot {
    page_size : Int
    page_count : Int
    usable_size : Int
    wal_frames_applied : Int
    wal_tail_bytes : Int
    // private fields
    }

    Snapshot::catalog

    fn Snapshot::catalog(self : Snapshot) -> Array[CatalogEntry] raise InspectError

    Read the five stored fields of each sqlite_schema record.

    Snapshot::find_row

    fn Snapshot::find_row(self : Snapshot, name : String, rowid : Int64) -> Row? raise InspectError

    Find a stored record by its signed rowid. A missing row returns None.

    Snapshot::scan_index

    fn Snapshot::scan_index(self : Snapshot, name : String) -> Array[IndexRecord] raise InspectError

    Read an index or WITHOUT ROWID table named in sqlite_schema.

    Snapshot::scan_index_root

    fn Snapshot::scan_index_root(self : Snapshot, root : Int) -> Array[IndexRecord] raise InspectError

    Read stored index entries or WITHOUT ROWID records in physical key order.

    Snapshot::scan_root

    fn Snapshot::scan_root(self : Snapshot, root : Int) -> Array[Row] raise InspectError

    Read stored records from a rowid-table root page in signed rowid order.

    Snapshot::scan_rowid_range

    fn Snapshot::scan_rowid_range(self : Snapshot, name : String, first : Int64, last : Int64, limit~ : Int) -> RowidPage raise InspectError

    Read up to limit records from an inclusive rowid range in ascending order. Pass next_rowid as the next call's first bound to continue, when present.

    Snapshot::scan_table

    fn Snapshot::scan_table(self : Snapshot, name : String) -> Array[Row] raise InspectError

    Read stored values for a table with the exact name used in sqlite_schema.

    Snapshot::text_encoding

    fn Snapshot::text_encoding(self : Snapshot) -> String

    Return the text encoding used to decode records from this snapshot.

    Value

    pub(all) enum Value {
    Null
    Integer(Int64)
    Real(Double)
    Text(String)
    Blob(Bytes)
    }

    impl Eq for Value

    Value::equal

    fn Value::equal(self : Value, other : Value) -> Bool

    Value::not_equal

    fn Value::not_equal(x : Value, y : Value) -> Bool

    Value::to_repr

    VersionedChange

    pub(all) enum VersionedChange {
    Added(VersionedRow)
    Removed(VersionedRow)
    Changed(VersionedRow, VersionedRow)
    }

    VersionedRow

    pub(all) struct VersionedRow {
    row : Row
    origin : PageOrigin
    }

    The origin refers to the B-tree cell page, which may point to overflow pages.

    WalChangeEvent

    pub(all) enum WalChangeEvent {
    CommitStarted(WalCommit, WalCommit)
    CommitChange(VersionedChange)
    CommitFinished(WalCommit)
    }

    Ordered events within a history export. Each successful pair ends with CommitFinished, including pairs with zero changed rows.

    WalCommit

    pub(all) struct WalCommit {
    revision : Int
    first_frame : Int
    last_frame : Int
    page_count : Int
    }

    A captured commit, or revision 0 for the baseline. WAL frames are one-based.

    WalPageOrigin

    pub(all) struct WalPageOrigin {
    frame : Int
    revision : Int
    offset : Int64
    }

    WalRevision

    pub struct WalRevision {
    info : WalCommit
    // private fields
    }

    One committed database view. Open multiple revisions from the same index.

    WalRevision::page_origin

    fn WalRevision::page_origin(self : WalRevision, page : Int) -> PageOrigin raise InspectError

    Return the source of one logical page in this revision.

    WalRevision::scan_table

    fn WalRevision::scan_table(self : WalRevision, name : String) -> Array[VersionedRow] raise InspectError

    Read the stored records of a rowid table in this revision, with cell origins.

    WalTimeline

    pub struct WalTimeline {
    page_size : Int
    valid_frames : Int
    committed_frames : Int
    ignored_wal_bytes : Int
    stop_offset : Int64
    stop_reason : String
    // private fields
    }

    Indexed committed snapshots in a single offline WAL capture.

    WalTimeline::commit

    fn WalTimeline::commit(self : WalTimeline, revision : Int) -> WalCommit raise InspectError

    Return a revision's boundary and page count without opening its view.

    WalTimeline::commits

    fn WalTimeline::commits(self : WalTimeline) -> Array[WalCommit]

    Returns revision 0 followed by the complete commits in the validated WAL prefix.

    WalTimeline::snapshot

    fn WalTimeline::snapshot(self : WalTimeline, revision : Int) -> WalRevision raise InspectError

    WalTimeline::visit_adjacent_changes

    fn WalTimeline::visit_adjacent_changes(self : WalTimeline, name : String, from~ : Int, to~ : Int, emit : (WalChangeEvent) -> Bool) -> Bool raise InspectError

    Compare FROM→FROM+1 through TO-1→TO using the same WAL index. Records stream in rowid order. Treat each pair as complete only after its CommitFinished event; a later error may stop the visitor partway through a pair. Returns false if the visitor stopped the export by returning false.

    diff_revisions

    fn diff_revisions(before : WalRevision, after : WalRevision, name : String) -> Array[VersionedChange] raise InspectError

    Compare two historical views by signed rowid and stored values. Both endpoints must have the same stored table definition.

    diff_table

    fn diff_table(before : Snapshot, after : Snapshot, name : String) -> Array[RowChange] raise InspectError

    Compare stored rowid-table records. The two catalog definitions must match.

    open_snapshot

    fn open_snapshot(main : Bytes, wal? : Bytes) -> Snapshot raise InspectError

    Open an offline main database image with an optional WAL from the same capture.

    open_wal_timeline

    fn open_wal_timeline(base : Bytes, wal : Bytes, max_frames? : Int) -> WalTimeline raise InspectError

    Open a checkpointed baseline taken before the first write in this WAL epoch. The inputs must stay immutable. The caller is responsible for capture order and preventing other checkpoints or WAL resets through the final capture. Only complete commits before the first invalid frame are indexed.