DoltLite Documentation

repository·master·Indexed 41 days ago

https://github.com/dolthub/doltlite

A SQLite fork that replaces the standard B-tree storage engine with a content-addressed prolly tree, providing Git-like version control (branching, merging, commits) directly within a SQL database. Designed for local-first applications, it includes a C API, language bindings, and specialized extensions for WebAssembly and vector search.

Tokens
92.8K
Snippets
253
Records
403
Agent score
53%

What's inside DoltLite

  1. Overview of Miscellaneous Extensions

    master

    The ext/misc directory contains several specialized extensions for DoltLite. These include virtual tables for interacting with external file formats and custom SQL functions for data processing:

    • csv.c: A virtual table for reading Comma-Separated-Value (CSV) files.
    • dbdump.c: A library providing functionality similar to the .dump command in the SQLite command-line shell.
    • json1.c: SQL functions and table-valued functions for JSON processing (note: this is often already built into the SQLite amalgamation).
    • rot13.c: A simple rot13() substitution function; useful as a template for creating custom SQL functions.
    • series.c: An implementation of the generate_series virtual table; useful as a template for custom virtual table implementations.
    • shathree.c: Implements sha3() and sha3_query() SQL functions.
    • unionvtab.c: Implements unionvtab and swarmvtab virtual tables, allowing a single large table to be spread across multiple database files (with swarmvtab attaching files on demand).
    • zipfile.c: A virtual table for reading and writing ZIP archives.
  2. Compare DoltLite performance with SQLite

    master

    DoltLite's performance is benchmarked against SQLite across different storage modes (In-memory and File-backed) and operation classes (Reads, Writes, and Autocommit writes).

    In-memory Performance

    In-memory operations show DoltLite performing closely to SQLite:

    • Reads: ~1.1× ratio
    • Writes: ~1.6× ratio

    File-backed Performance

    File-backed operations also maintain high parity:

    • Reads: ~1.1× ratio
    • Writes: ~1.1× ratio
    • Autocommit writes: ~3.3× ratio

    Overall, the absolute performance ceiling for ordinary workloads is 2.3× slower than SQLite, while durable autocommit writes reach a ceiling of 6.0×.

  3. Understand how ROLLBACK affects Dolt version control operations

    master

    In DoltLite, version-control functions run inside SQLite transactions. However, certain operations are durable the moment they return and cannot be undone by a ROLLBACK command.

    What is undone by ROLLBACK:

    • Row writes and dolt_add operations.

    What is NOT undone by ROLLBACK (these are durable):

    • dolt_reset (--soft, --hard, or no args).
    • dolt_branch, dolt_tag, and dolt_branch('-d').
    • dolt_checkout -b (creates a new branch).
    • dolt_checkout of an existing branch.
    • dolt_commit, and any merge, cherry-pick, revert, or pull that completes.

    Important Note: A successful dolt_commit (or any operation that creates a commit/fast-forwards a branch) automatically commits the underlying SQL transaction. If you attempt a ROLLBACK after a successful dolt_commit, you will receive the error: cannot rollback - no transaction is active.

  4. Manage per-session branching in DoltLite

    master

    In DoltLite, each connection selects a branch independently. This means each connection maintains its own active branch and session view of HEAD and staging.

    Key behaviors:

    • Working set recovery: The uncommitted working set belongs to the branch. If one connection selects a branch, another connection selecting that same branch will recover that working set.
    • No dolt_stash: Checkout does not shelve uncommitted work between branches. If you switch branches, your uncommitted work is tied to the branch you are leaving/joining.
    • Peer-deleted branches: If a connection is parked on a branch that another connection (a peer) deletes, the parked connection can continue reading its current snapshot. However, any write attempts will fail and report the missing branch. To recover, the connection must check out an existing branch.
  5. How to use the Binder Factory

    master

    The Binder Factory is the entry point for creating bindings between WASM-side C structs and the JavaScript environment.

    1. Generate/Retrieve Descriptions: Obtain the JSON struct descriptions (ideally via the wasm__ctype_json pattern).
    2. Parse JSON: Use JSON.parse() on the string returned from WASM.
    3. Initialize Factory: Pass these descriptions into the Binder Factory to create the necessary binding logic for your specific struct types.
  6. Understand DoltLite revision syntax and refs

    master

    DoltLite uses various identifiers to reference specific states (snapshots) of the database. Commit refs are case-sensitive.

    Common Revision Types

    • Branches: main, feature/x (refers to the branch tip).
    • Tags: v1.0.
    • Commit Hashes: 40 lowercase hex characters (prefixes are not accepted).
    • HEAD: The tip of the connection's current branch. Note that head (lowercase) is an error.
    • Remote Tracking Branches: origin/main, remotes/origin/main, or refs/remotes/origin/main (available after dolt_clone or dolt_fetch).
    • Ancestors:
      • <rev>~N: The Nth first-parent ancestor. ~ is shorthand for ~1.
      • <rev>^N: The Nth parent of a merge commit. ^ is shorthand for ^1. Note that ^0 is an error.
    • Catalogs (Case-Insensitive):
      • WORKING: The working set (committed data plus staged and unstaged edits).
      • STAGED: The staged catalog, or HEAD if nothing is staged.

    Lookup Order and Suffixes

    When resolving a name, DoltLite follows this order: HEAD $\rightarrow$ hash $\rightarrow$ branch $\rightarrow$ tracking branch $\rightarrow$ tag. If a name is both a branch and a tag, the branch takes precedence. Suffixes like ~ and ^ chain from left to right (e.g., HEAD~2^2).

    Catalog vs. Commit

    WORKING and STAGED refer to a catalog, not a specific commit.

    • Use them with: dolt_diff_*, dolt_diff_stat, dolt_diff_summary, dolt_schema_diff, dolt_patch, dolt_at_<table>, dolt_hashof_table, and dolt_hashof_db.
    • Do NOT use them with: dolt_hashof, dolt_log, dolt_history_<table>, dolt_merge_base, or dolt_checkout (these require a specific commit).
    # Examples of revision syntax
    main              # Branch tip
    v1.0               # Tag
    40hexchars...      # Commit hash
    HEAD               # Tip of current branch
    WORKING            # The working set (case-insensitive)
    STAGED             # The staged catalog (case-insensitive)
  7. Understand memory allocation behavior when SQLITE_CONFIG_SMALL_MALLOC=1

    master

    When SQLITE_CONFIG_SMALL_MALLOC is set to 1, the sorter module changes its allocation strategy to use a linked list instead of a large contiguous buffer.

    • Allocation Pattern: sqlite3VdbeSorterWrite() stores keys in a regular heap-memory linked list, performing one allocation per element.
    • Memory Pressure Management: Every time a key is added, the sorter calls sqlite3HeapNearlyFull(). If this returns true, the current list of keys is flushed to a temporary file immediately, even if the size threshold has not been reached.
    • Cleanup: List elements are freed as they are flushed to disk by either the main thread or a worker thread.
  8. Understand the JSONB binary format

    master

    JSONB is a binary encoding of JSON supported by SQLite (starting from version 3.45.0). It is stored as a BLOB.

    Key Characteristics:

    • Performance: JSONB is typically 5% to 10% smaller than text-based RFC 8259 JSON and can be processed in less than half the CPU cycles.
    • Structure: Unlike text JSON which uses punctuation (quotes, braces, brackets, commas, colons) as delimiters, JSONB uses a header for each element that includes its size and type. This allows for faster reading without scanning for closing delimiters.
    • Compatibility: While named after PostgreSQL's JSONB, the formats are not binary compatible. They have different internal representations.
    • Payload: The actual payload bytes in JSONB are identical to the corresponding text JSON and appear in the same order.
  9. Understand the SQLite Test Script Interpreter specification

    master

    The Test Script Interpreter is designed to read and execute ASCII text files with a .test extension. These files contain SQL commands and expected results, which the interpreter uses to verify correctness and report discrepancies.

    Key Behaviors:

    • Isolation: Each script is evaluated independently. Context (like settings or state) does not carry forward between scripts.
    • Cleanup: All open database connections are closed at the end of a script, and all database files created during the script's execution are deleted upon completion.
    • Format: Scripts are processed line-by-line.

    Compatibility and Parsing Rules:

    To be compatible with this specification, a script must follow these rules:

    • Module Names: Must not contain MODULE_NAME: or MIXED_MODULE_NAME:. If SCRIPT_MODULE_NAME: is present, the script is considered compatible.
    • Properties: Must not contain REQUIRED_PROPERTIES: followed by non-whitespace text.
    • Format Restrictions: Lines starting with | (indicating a dbtotxt format) are incompatible.
    • No Preprocessor: Lines starting with # (C-preprocessor lines) are not supported; processing will be abandoned if they are encountered.
    • Commands: Commands are identified by lines starting with exactly two minus signs followed by a lowercase letter (e.g., --command).
    • Input Buffer: All lines that are not commands are accumulated into an "input buffer" which commands can access or reset.
  10. Understand DoltLite concurrency and the graph lock

    master

    DoltLite supports multiple connections and processes on a single database file, but it is not a multi-writer server. Coordination is managed via a graph lock sidecar that serializes durable writers.

    Key concurrency behaviors include:

    • One durable writer at a time: A connection holding an explicit write transaction owns the graph lock. Other processes attempting to write will receive SQLITE_BUSY (or a retryable busy class). This applies to both standard SQL (e.g., INSERT) and version-control commands (e.g., dolt_branch, dolt_tag, dolt_commit).
    • Read-only connections never block writers: Reads (including dolt_status) do not take an exclusive lock. A second process polling status will not cause a writer's INSERT or dolt_commit to fail.
    • Snapshot-safe write upgrades: If a transaction has established a read snapshot, it cannot upgrade to a writer if a peer has advanced the store in the meantime. This upgrade attempt will return SQLITE_BUSY_SNAPSHOT to prevent mixing catalogs.
    • GC and VACUUM cooperation: dolt_gc or VACUUM may be deferred or report busy while a writer holds the graph lock. Once the writer finishes, GC completes safely.
    • Conflicts are transient: Conflicted merges exist only within the transaction that produced them. A dolt_commit will be refused if conflicts remain, and no conflicted state is persisted to disk for other connections to inherit.
  11. How the SQLite Expert Extension works

    master

    The SQLite Expert Extension is a system designed to propose useful indexes for a database based on a provided set of SQL queries. It follows a multi-step process:

    1. Schema Copying: The user database schema is copied to a temporary database.
    2. Query Profiling: SQL queries are prepared against the temporary database to record information about WHERE and ORDER BY clauses and other features affecting index selection.
    3. Candidate Generation: The gathered information is used to create candidate indexes that the query planner might have used if they were available.
    4. Statistics Generation: A subset of the user database data is used to generate statistics for both existing indexes and the newly created candidate indexes.
    5. Validation: The SQL queries are prepared a second time. If the planner utilizes any of the candidate indexes, they are recommended to the user.
  12. The sqlite3_qrf_spec object

    master

    The sqlite3_qrf_spec object is the primary configuration structure for the Query Result Formatter. It defines the desired output format and specifies where the generated output should be deposited.

    Key fields mentioned in the documentation include:

    • iVersion: The structure version number (currently 2).
    • pzOutput: A pointer to a char * where the formatted output will be written.
    • bTitles: Controls whether column names are shown.
    • eEsc: Controls control character escapes.
    • eText / eTitle: Controls the display of TEXT values.
    • eBlob / bTextJsonb: Controls how BLOB values are displayed.