moonsqlite-inspect

    Reconstruct and compare offline SQLite WAL commits in pure MoonBit

    Download zip
    Author
    Version
    0.5.0
    License
    Apache-2.0
    Last updated
    24 minutes ago
    Downloads
    36

    #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.5.0

    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 node _build/js/debug/build/cmd/main/main.js --help 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-row _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 1 status 41 --manifest _build/wal-demo/capture.json node _build/js/debug/build/cmd/main/main.js wal-range _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 3 status -9223372036854775808 9223372036854775807 2 node _build/js/debug/build/cmd/main/main.js wal-range _build/wal-demo/baseline.sqlite _build/wal-demo/capture.wal 3 status 9223372036854775807 9223372036854775807 2 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-row seeks a signed rowid at the selected revision and returns zero or one record. wal-range reads an inclusive rowid interval in ascending order, up to the requested row limit and the JSON byte budget. The first example page ends with next_rowid: "9223372036854775807". For the next call, use that value as the first bound and keep the same capture, revision, table and last bound. null marks exhaustion. The lookup reads the relevant B-tree branches and any overflow pages needed by the selected records.

    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. Revision 4 in the demo changes the table definition, so the series stops at revision 3.

    wal-rows, wal-row, wal-range, wal-changes and wal-series each return at most 8 MiB of UTF-8 JSON, including the final newline. wal-range reserves space for its continuation and returns early when another row would exceed the budget. When the first row cannot fit, the command reports an error with empty standard output. Use wal-range for large tables, a smaller series --limit for multiple comparisons or a library visitor for larger individual values. A decoding error while reading a page of results discards that response. Record decoding and the shared history index also use memory.

    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. WalRevision::visit_table visits rows without collecting the table, and visit_revision_changes visits changes between any two supported views, including reverse comparisons. Return false to stop before reading another record. A true result means the scan completed; an error can follow earlier callbacks. The array-returning APIs remain available. 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. Visitor examples

    WalRevision::find_row and WalRevision::visit_rowid_range seek directly in a revision. The range visitor returns the first unaccepted key when its row limit is reached or its callback declines the current row. Historical lookup API

    #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.

    Stored REAL values use numeric equality. NaNs compare equal to other NaNs, and positive and negative zero compare equal. NaN payload bits are outside this value comparison. A raw serial-7 NaN remains a Real value here, while SQLite SQL reads it as NULL. A stored REAL-to-NULL or INTEGER-to-REAL change still appears in a diff. JSON encodes REALs as strings, including NaN, Infinity and -Infinity. SQLite numeric representation

    #Reproduce verification

    moon test --target js --frozen moon build --target js --frozen python -B scripts/sqlite_oracle.py python -B scripts/history_stress.py python -B scripts/verify_distribution.py python -B scripts/verify_readme.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

    history_stress.py uses two fixed seeds and two page sizes to generate four captures with 24 commits each. It compares 100 historical snapshots and 120 adjacent, nonadjacent, reverse or identical-endpoint comparisons with SQLite queries, and checks cell origins against raw frame bytes. The workload includes multi-page tables, index updates, overflow payloads, growth, vacuum shrink and regrowth, savepoint and transaction rollback, and writes to an unrelated table.

    verify_distribution.py unpacks the current distribution and uses it in a separate consumer project. Seven public API tests run on each of the four backends, including a history seek and a resume at the first rejected key. The SQLite oracle checks multi-level seeks, historical insertion and deletion, raw cell origins and pagination where JSON escaping triggers the byte budget. verify_readme.py executes the README's history commands in a newly extracted package and checks all ten JSON reports. 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.5.0

    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.

    Use python -B scripts/benchmark.py --history-lookup --runs 7 to compare historical point lookup with scanning and filtering an 8,000-row capture. Supply --baseline with a 0.4.1 build to use that release for the scan. Optimization plan and verification results

    #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::find_row

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

    Seek one signed rowid in an ordinary table at this revision. None means the key is absent. Only the lookup path and its payload are read.

    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.

    WalRevision::visit_rowid_range

    fn WalRevision::visit_rowid_range(self : WalRevision, name : String, first : Int64, last : Int64, limit~ : Int, accept : (VersionedRow) -> Bool) -> Int64? raise InspectError

    Visit up to limit stored rows in an inclusive range in signed rowid order. If accept returns false, the current row remains the first unaccepted key. Use the returned key as the lower bound in the same revision and range. None means the range is exhausted. Errors may follow earlier callbacks.

    WalRevision::visit_table

    fn WalRevision::visit_table(self : WalRevision, name : String, emit : (VersionedRow) -> Bool) -> Bool raise InspectError

    Visit stored rows in signed rowid order, with their cell origins. Return false from emit to stop before reading another record. The result is true only when the scan reaches its end; errors may follow earlier callbacks.

    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.

    visit_revision_changes

    fn visit_revision_changes(before : WalRevision, after : WalRevision, name : String, emit : (VersionedChange) -> Bool) -> Bool raise InspectError

    Visit differences between any two historical views, in signed rowid order. Both endpoints must have the same stored table definition. Returning false stops the comparison immediately. A true result means both scans completed; errors may follow earlier callbacks, so consumers must handle partial work.