|
Lightweight 0.20261105.1
|
This page explains how the backup engine (Lightweight::SqlBackup::Backup / Restore) works: its pipeline, parallelism model, memory and disk profile, fault tolerance, and the consistency guarantees you can (and cannot) expect. For the on-disk archive layout, see sql-backup-format.md; for the CLI, see dbtool.md (dbtool backup / dbtool restore).
A backup is a single zip archive containing:
metadata.json — schema description (tables, columns, types, row counts),checksums.json — SHA-256 per data chunk and attachment,data/<table>/NNNN_SS.msgpack — the table data, split into self-contained msgpack chunks (NNNN = window index, SS = sub-chunk within the window),attachments/<name> — optional files the caller supplied through BackupSettings::attachments, which restore ignores.SqlBackup::ListArchiveAttachments(file) lists an archive's attachments, refusing a name a backup would refuse, and SqlBackup::ReadArchiveAttachment(file, name) reads one, refusing it unless checksums.json lists it with a matching SHA-256 (see sql-backup-format.md).
SqlBackup::BackupSchemas backs up several schemas into one archive. It then stores the data under data/<schema>/<table>/ and records each table's schema and each foreign key's referenced schema, so that a restore recreates every table in its own schema (see sql-backup-format.md).
Backup and restore work against SQLite3, Microsoft SQL Server, and PostgreSQL through ODBC; all per-DBMS SQL differences are handled internally.
[lo, hi]: the planner runs SELECT MIN(pk), MAX(pk) (an index seek) and divides the span into windows of about rowsPerChunk keys, capped at 1024 windows per table — sparse key spaces (e.g. snowflake-style IDs) get proportionally wider windows instead of millions of empty ones. Each window is an independent chunk, so one big table is read by many workers concurrently.Parallel data export. concurrency worker threads, each with its own pooled database connection, drain a shared chunk queue. Workers fetch rows (bulk array-fetch where possible, row-by-row otherwise), encode them to msgpack, hash, and add the chunk files to the archive. Chunk filenames are assigned at plan time, so workers never coordinate on naming, and chunks may complete in any order.
Array-fetch coverage (one driver round-trip per block of rows instead of one SQLGetData per cell — the dominant cost on remote servers): integer family, Real, Bool, Varchar/Char, Decimal, NVarchar/NChar (UTF-16 bound), Date/DateTime/Timestamp (native structs) on all databases; Time and Guid additionally on SQL Server and PostgreSQL. Tables containing LOBs (varchar(max), text, binary) fall back to the row-by-row path. The per-cursor fetch-buffer memory is capped (~4 MB per worker); wide tables automatically read fewer rows per round-trip instead of exhausting RAM.
metadata.json and checksums.json are written, and the archive is closed. The close only streams already-compressed bytes, so it takes seconds even for very large backups.Restore is chunk-order-independent: it enumerates data/<table>/*.msgpack entries and tracks completion by per-table chunk count, so parallel, out-of-order backups restore exactly like sequential ones.
RAM usage is bounded and independent of database size. Each worker buffers at most chunkSizeBytes (default 10 MB) of encoded rows; flushed chunks go into the worker's private temp archive under <output>.zip.tmp/, which is sealed (compressed in the worker thread) every workerArchiveBytes (default 256 MB) of input. The memory ceiling is therefore about concurrency × workerArchiveBytes plus fetch buffers — and because the temp archives hold compressed data, the extra disk needed during the run is only about the size of the final archive itself. The temp directory is removed automatically when the backup finishes (also on failure).
RetrySettings). A PK-window chunk re-reads just its own window; rows already counted are not double-reported, and chunk files are rewritten in place (ZIP_FL_OVERWRITE), so retries are idempotent.checksums.json and verified on restore. SqlBackup::VerifyArchive(file) checks a finished archive the same way without a database: it needs metadata.json, every data/ entry and every attachment listed in checksums.json with a matching SHA-256, and returns the SHA-256 of the whole file. A schema-only archive without attachments has no such entries and needs no checksums.json. A failure names the entry at fault.schema_backups and the tables the advisory-lock handlers keep (_lightweight_locks on SQLite, which holds a row while the migration lock is taken) are never backed up, and a restore skips them in archives that still hold them. The live tables stay as they are: a restore never brings back old backup records or a held lock.metadata.json's complete is false for a filtered or schema-only backup and for one in which a table failed; VerifyArchive reports it. Archives without the key count as complete.SqlBackup::Restore() does not abort on a bad value or row; it restores everything it can and returns a bounded RestoreReport of the rest (it is not [[nodiscard]], so existing callers that ignore it compile unchanged):
RetrySettings stops the worker that hit it; the report lists the tables it left incomplete (incompleteTables; WorkerStopped()).A table that failed as a whole, that a stopped worker left incomplete, or that could not be created leaves the restore incomplete: the run reports an error, does not claim success, and does not apply foreign key constraints and indexes, because constraining a database that is missing a table's data only produces misleading AddForeignKey failed errors naming the referencing tables. Rerun the restore once the cause is fixed. Rows left out one by one and unreadable chunks do not count: the constraints and indexes are applied, and a constraint that the missing rows break is reported as an error.
Each table gets at most one terminal update through the ProgressManager (Error if anything failed for it, with a message such as 2 rows failed, 3 cells set to NULL; Finished otherwise). A table that failed as a whole or had an unreadable chunk may report additional Error updates before it, so a consumer that tallies failed tables must count a table once.
RestoreReport holds only tables with failures (tables, sorted by name; TotalFailedRows() and NulledCellCount() sum them up), and the run-level problems. Its memory and the progress traffic do not grow with the number of failed rows: per table, at most MaxReportedRowRanges (100) row ranges (FailedRowRange: chunk, first and last row) and MaxReportedReasons (20) distinct FailureReasons with MaxSampleKeysPerReason (3) sample keys each are kept; the rest is counted in rowsBeyondRangeCap and occurrencesBeyondReasonCap. ColumnValueFailures counts the NULLed cells per column. report.HasFailures() is the verdict.
A restore that is refused before it moves any data (an unsupported archive, a refused target schema) returns an empty report and reports the error through the ProgressManager; check both (progress.ErrorCount() and report.HasFailures()), as dbtool restore does for its exit code. See dbtool for the command-line output.
SQL Server and PostgreSQL pad a CHAR(n)/NCHAR(n) value to n characters and ignore the pad when comparing; SQLite does not pad and compares exactly. A CHAR(5) holding q therefore comes out of a SQL Server backup as q, and restored verbatim into SQLite, ‘WHERE Code = 'q’would find nothing. When a restore crosses from a padding database into a non-padding one, the trailing spaces (U+0020 only) ofCHAR/NCHARvalues are stripped (an all-space value becomes empty;NULLstaysNULL;VARCHAR andNVARCHARare never touched). The source is theserver.namein the archive'smetadata.json; if it is missing or names no known database, nothing is stripped. A restore into the same kind of database as the backup, or into a padding one, keeps every value as archived. Whether a database pads is the SqlQueryFormatter::ComparesFixedCharWithPadSemantics()` knob.
The backup runs online, without a global snapshot or table locks. If the database is being written to during the run:
MAX(pk) after a table was planned are not included;For a strictly consistent backup, run against a quiesced database, a snapshot, or a restored replica.
| Knob | Default | Effect |
|---|---|---|
concurrency (jobs) | caller-defined | Worker threads and database connections. The export phase is mostly network/IO-bound, so more jobs ≈ more concurrent result streams. |
BackupSettings::rowsPerChunk | 100 000 | Target keys per PK window. Smaller = finer load balancing, more files; larger = fewer round-trips per table. |
BackupSettings::chunkSizeBytes | 10 MB | Byte threshold per chunk file flush; sets data-file granularity. |
BackupSettings::workerArchiveBytes | 256 MB | Uncompressed input per worker temp archive before it is sealed (compressed). Bounds worker memory at ~jobs × workerArchiveBytes; lower it on memory-constrained machines. |
BackupSettings::method / level | Deflate / 6 | Compression method and level (applied at archive close). |
RetrySettings | sensible defaults | Max retries and backoff for transient errors. |
dbtool backup / dbtool restore CLI usage.