166 lines
12 KiB
Markdown
166 lines
12 KiB
Markdown
# Sqlite — first-class SQLite C API integration
|
||
|
||
Status: plan; all implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||
R-007 and [C-02–C-05/C-08](../ARCHITECTURE.md) require this module to remain distinct from
|
||
the original [Storage](../subsystems/Storage.md) engine.
|
||
|
||
## Source-backed baseline
|
||
|
||
[Sqlite.hpp](../../../include/Void/Sqlite/Sqlite.hpp) exposes `Void::Sqlite::Database`,
|
||
`Statement`, `Transaction`, `Migration`, `OpenMode` and a local Result alias. Database and
|
||
Statement are move-only RAII wrappers. Bind indexes are one-based; column indexes are
|
||
zero-based. `step()` returns Result<bool>, text reads copy, transactions roll back on
|
||
destruction unless marked done, and migrations use `PRAGMA user_version`.
|
||
[module.cmake](../../../src/Sqlite/module.cmake) links Functional and SQLite3::SQLite3.
|
||
|
||
[Sqlite.cpp](../../../src/Sqlite/Sqlite.cpp) opens writable databases with a 5,000 ms busy
|
||
timeout and attempts WAL/foreign_keys pragmas without checking their results. Bind/reset
|
||
and clear-bindings ignore SQLite return codes. Transaction stores a raw Database pointer,
|
||
and `commit()` marks it done before calling SQLite. Database close ignores the close result.
|
||
These are concrete lifecycle/error-completion targets, not evidence that all uses fail.
|
||
[Tests](../../../tests/standalone/Sqlite/Sqlite.cpp) cover memory open, SQL execution,
|
||
binding/nulls, successful commit, destructor rollback, migrations and bad SQL; they do
|
||
not establish busy-commit recovery, database moves with live transactions or WAL durability.
|
||
|
||
## Backend decision and NEW API
|
||
|
||
Keep SQLite itself as the SQL engine, pager, locking and file-format owner. Void supplies
|
||
checked RAII, lifetimes, configuration, async admission and migrations. Do not reimplement
|
||
SQL, parse database pages, or translate Storage batches into a pretend identical SQL API.
|
||
Pin/test supported SQLite versions through [build/distribution](../BUILD-AND-DISTRIBUTION.md);
|
||
capture runtime version/compile options in diagnostics without claiming untested versions.
|
||
|
||
NEW illustrative additions in `Void::Sqlite`:
|
||
|
||
```cpp
|
||
enum class JournalMode { Wal, Rollback };
|
||
enum class SyncMode { Full, Normal };
|
||
enum class BeginMode { Deferred, Immediate, Exclusive };
|
||
struct OpenOptions; // mode, journal/sync, limits, busy budget, capabilities
|
||
struct SqliteError; // primary and extended code, bounded message, operation
|
||
Result<Database> open_database(path, OpenOptions);
|
||
Result<void> Statement::bind_checked(int, ValueView);
|
||
Result<void> Statement::reset_checked();
|
||
Result<Transaction> Database::begin(BeginMode);
|
||
Result<void> Database::close();
|
||
Result<CheckpointReport> Database::checkpoint(CheckpointMode);
|
||
```
|
||
|
||
These are proposals, not existing declarations. ValueView is a NEW typed view over null,
|
||
int64, double, text and blob. Checked text/blob bindings copy by default; borrowed/static
|
||
bindings require an explicit lifetime owner retained until reset/rebind/finalize. Row views
|
||
expire at the next step/reset/finalize and cannot cross an await; owning row copies are
|
||
available. Typed reads reject unexpected type/range instead of silently coercing a text
|
||
column to zero. Named binds and blobs complete the basic API; parameter metadata validates
|
||
indexes, and strict single-statement prepare rejects non-whitespace trailing SQL.
|
||
|
||
Use a shared ConnectionState independent of the Database object's address. Statements and
|
||
transactions retain it, so moving/destroying a Database handle does not leave dangling
|
||
transaction pointers. NEW `close()` stops admission and returns Busy while handles remain;
|
||
destructor release defers final native close to the last owner and reports errors to an
|
||
optional bounded diagnostic hook. Explicit finalization is available when error reporting
|
||
matters. Native `handle()` access is an expert borrow under the connection's execution lease;
|
||
it does not grant concurrent unsynchronized use or ownership transfer.
|
||
|
||
## Transactions, concurrency and operational behavior
|
||
|
||
A connection has one execution owner at a time. Embedded synchronous callers serialize
|
||
operations explicitly. Managed async use moves work to a bounded blocking executor and
|
||
leases one connection for the complete transaction; no await releases that lease midway
|
||
through a transaction. SQLite's internal mutex modes do not replace wrapper object-lifetime
|
||
rules. Read pools default to four connections, with one writer lane; users opt into other
|
||
topologies knowingly. No global connection/thread pool is created by opening a Database.
|
||
|
||
Transaction state is Active, Committed, RolledBack or RecoveryRequired. Set Committed only
|
||
after successful COMMIT. A busy COMMIT can leave the transaction active; retain rollback/
|
||
retry capability and query SQLite's autocommit state after errors before deciding whether
|
||
it was automatically rolled back. This follows SQLite's [transaction semantics](https://www.sqlite.org/lang_transaction.html)
|
||
and [autocommit query](https://www.sqlite.org/c3ref/get_autocommit.html). Do not blindly replay
|
||
statements or automatically rerun a whole transaction after an error: triggers and external
|
||
callbacks may already have effects. Savepoints are NEW separately owned nested scopes;
|
||
ordinary `begin` inside an active transaction fails rather than pretending to nest.
|
||
|
||
NEW defaults for file databases are checked WAL + synchronous FULL + foreign_keys ON.
|
||
Query effective pragma results and fail configuration if a required mode is unavailable.
|
||
In-memory/read-only databases have explicitly different effective capabilities. NORMAL is
|
||
an explicit weaker durability choice. WAL permits readers alongside one writer, but long
|
||
read transactions can hold back checkpoints; it also requires same-host shared-memory
|
||
coordination and is not the selected network-filesystem deployment mode.
|
||
[SQLite WAL documentation](https://sqlite.org/wal.html) defines these constraints; no claim
|
||
is made that Void's native WAL shares SQLite's layout or exact durability modes.
|
||
|
||
Busy waiting uses a bounded configured budget (default five seconds), capped by the shared
|
||
absolute operation deadline. Install cancellation/progress handling per leased operation,
|
||
and clear it before connection reuse. A connection-wide interrupt must never accidentally
|
||
cancel the next borrower's query; serialize lease handoff through completion and native
|
||
interrupt cleanup. Stop can prevent execution or interrupt supported SQLite work, but a
|
||
commit racing with stop may have taken effect. Return domain outcome evidence rather than
|
||
claiming cancellation rolled it back. Avoid busy sleeps on an IO event-loop thread.
|
||
|
||
Checkpoint reports completed/remaining pages and Busy, with no automatic promise to shrink
|
||
a WAL held by readers. Default managed policy requests passive checkpoints at 16 MiB WAL,
|
||
warns at 64 MiB, and stops new write admission at a configured 256 MiB application threshold
|
||
until reader/checkpoint progress permits it. This is a wrapper admission policy, not a hard
|
||
SQLite file-size guarantee against other processes. Monitor external writers separately.
|
||
Never delete a live `-wal`/`-shm` file to reclaim space.
|
||
|
||
## Completion capabilities and budgets
|
||
|
||
Defaults for NEW wrappers: 128 live statements/connection, 1 MiB SQL text, 16 MiB bound
|
||
value/row-copy limit, 1,024 queued jobs and 64 MiB aggregate pending input, 64 cached
|
||
statements with an 8 MiB wrapper-memory ceiling. Evict only idle cache entries; an active
|
||
statement belongs to its borrower. Apply SQLite limit APIs where supported, and separately
|
||
bound wrapper allocations. SQLite pager/cache memory is configured and measured, not
|
||
assumed equal to wrapper memory. Bulk operations stream rows within one explicitly sized
|
||
transaction; a `query_all` convenience has a row and byte cap.
|
||
|
||
Migration completion validates a strictly increasing unique version list before any SQL.
|
||
The application supplies immutable migration identities/checksums; record them in an
|
||
application migration table in the same transaction as schema changes and user_version.
|
||
Reject unexpected newer schemas and checksum drift. A migration may be non-reversible;
|
||
require a verified backup and explicit application rollback plan before applying it. Do
|
||
not infer a down-migration from reversing SQL strings. Backup/restore use SQLite's supported
|
||
backup interface with bounded steps and consistent source lifetime, not a raw copy of an
|
||
open database file. Extension loading remains disabled by default; optional functions,
|
||
collations and authorizers have explicit lifetime and no-exception-across-C-callback wrappers.
|
||
|
||
## Ordered tasks
|
||
|
||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||
| --- | --- | --- | --- |
|
||
| M-SQLITE-01 | P0; existing tests, official SQLite contracts | Regress bind errors, busy/failed commit, outstanding statement close and move-with-live-transaction; record supported runtime/build options. | astra_implementer |
|
||
| M-SQLITE-02 | P1; M-SQLITE-01, Functional typed errors | ConnectionState ownership, checked bind/reset/finalize/close and transaction states; failed COMMIT cannot disable necessary rollback. | astra_implementer |
|
||
| M-SQLITE-03 | P2; M-SQLITE-02 | Checked options/pragmas, typed rows/blobs/named params, savepoints and migrations; malformed options/schema plans fail before mutation. | sol_implementer |
|
||
| M-SQLITE-04 | P2; M-SQLITE-03, Async/Time ownership | Leased async connections, bounded jobs, cancellation/busy handling; no cross-query interrupt or transaction interleaving. | astra_implementer |
|
||
| M-SQLITE-05 | P3; M-SQLITE-03/04, IO/Runtime operations | Checkpoint/backup/restore, health metrics and guarded callback adapters; active-reader pressure is visible and backup restores consistently. | astra_implementer |
|
||
| M-SQLITE-06 | P3; M-SQLITE-05, shared performance/consumer harness | Supported-version/mode matrix and Storage comparison with matched guarantees; publish all latency/memory/build tradeoffs. | sol_implementer |
|
||
|
||
P4 platforms may use SQLite locally, but Sqlite does not become a consensus/replication
|
||
engine by sharing a file across hosts. [NetworkedApplications](../platforms/NetworkedApplications.md)
|
||
selects its SQLite profile explicitly.
|
||
|
||
## Verification and migration
|
||
|
||
CURRENT TEMPLATE for source-verified test names:
|
||
`<existing-build>/tests/VoidTests --filter '^(open_in_memory|prepared_bind_and_read|transaction_.*|migrations_apply_in_order_and_are_idempotent|prepare_bad_sql_errors)$'`.
|
||
See [validation](../VALIDATION.md) for actual baseline commands and failures. PROPOSED after
|
||
M-SQLITE-01–05: two-connection busy fixtures, faulted COMMIT/destructor rollback, explicit
|
||
null vs empty text/blob, embedded NUL, int64 bounds, wrong column/index, expired row views,
|
||
long reader checkpoint pressure, cancellation at lease transfer, disk full and migration
|
||
checksum drift. Use real supported SQLite libraries in addition to deterministic wrapper
|
||
ports. Restart tests must use file databases; `:memory:` tests cannot prove durability.
|
||
|
||
[Performance](../PERFORMANCE.md) covers prepared/unprepared, batch/individual commits,
|
||
WAL/rollback, FULL/NORMAL, read pool contention and database-larger-than-cache workloads.
|
||
Report p50/p95/p99 including busy/admission, throughput, allocations, RSS/CPU and build cost,
|
||
with common repetitions/confidence intervals and all failed/rejected jobs counted.
|
||
|
||
[Migration](../MIGRATION.md): add checked methods first; deprecate chainable unchecked binds
|
||
and address-dependent transaction lifetimes only with a major-release adapter path. Example:
|
||
`stmt.bind(1, value); stmt.step();` becomes checked bind followed by checked step. File formats
|
||
remain SQLite's; wrapper upgrades do not convert them to Storage. Roll back code only when
|
||
the schema remains backward compatible, otherwise restore a verified backup with explicit
|
||
reconciliation of subsequent writes. Graph coverage reported no recorded gaps for cited
|
||
Sqlite files, and source was read directly. No SQL tests or performance measurements ran
|
||
for this documentation assignment.
|