db/sqlite
lib/db/sqlite.vklib/db/sqlite.vk
Pure-Veko Zero-FFI SQLite 3 ("SQLite format 3\0") B-tree database reader/writer,
parameterized SQL engine (CREATE TABLE, CREATE [UNIQUE] INDEX, ALTER TABLE ADD COLUMN,
INSERT, UPDATE, DELETE, SELECT with aggregates, BEGIN/COMMIT/ROLLBACK),
and homoiconic Veko ORM & block query DSL (define-table, migrate, insert, find-by-id, q).
Runs identically across --vm, --wasm (zero .ffi!), and --native, producing standard
4096-byte slotted B-tree .sqlite files directly interoperable with the sqlite3 CLI.
ColumnDef = struct { name str, col_type str = ..., is_pk bool = ..., is_int_pk bool = ..., is_unique bool = ..., is_indexed bool = ..., not_null bool = ..., has_default bool = ..., default_val any = ... }
Column schema definition in a SQLite table.
IndexDef = struct { name str, table str, column str, is_unique bool = ..., sql str = ... }
Index metadata stored in sqlite_schema and backed by an index B-tree (0x0a / 0x02).
TableStore = struct { name str, columns block[ColumnDef], sql str, next_id i64 = ..., row_ids block = ..., rows map = ..., idx_cache map = ... }
In-memory representation of a loaded/mutable SQLite table (rowid -> row map + ordered rowids).
TableSpec = struct { name str, pk_col str = ..., columns block[ColumnDef] }
Declarative homoiconic ORM model returned by define-table.
SqliteDb = struct { path str = ..., page_size i64 = ..., change_counter i64 = ..., schema_cookie i64 = ..., user_version i64 = ..., table_order block = ..., tables map = ..., index_order block = ..., indexes map = ..., in_tx bool = ..., tx_snapshot bytes = ..., raw_img bytes = ..., table_roots map = ..., index_roots map = ..., btree_dirty bool = ... }
Handle to an open pure-Veko SQLite 3 database (file-backed or :memory:).
put-varint = fn [mut buf bytes, v i64]
read-varint = fn [buf bytes, off i64] map
seek-table-rowid = fn [db_bytes bytes, page_size i64, usable_size i64, root_pg i64, target_rid i64] any
$O(\log N)$ binary-search lookup of a single target_rid directly across 0x05 interior & 0x0d leaf table B-tree pages.
seek-index-btree = fn [db_bytes bytes, page_size i64, usable_size i64, pg_num i64, op str, target_val any, mut out_rids block]
$O(\log N + K)$ binary-search seek across 0x02 interior and 0x0a leaf SQLite index B-tree pages (=, <, <=, >, >=).
to-bytes = fn [db SqliteDb] bytes
from-bytes = fn [raw bytes] SqliteDb
Decodes a standard binary SQLite 3 image (raw) into an in-memory SqliteDb.
encode-rollback-journal = fn [orig_existed bool, page_size i64, orig_img bytes, new_img bytes] bytes
Builds a CRC-32-verified hot rollback journal (VKJRNL01) capturing all dirty/truncated original pages.
verify-rollback-journal = fn [jraw bytes] map
Validates a VKJRNL01 hot rollback journal image and returns { orig_existed, page_size, orig_size, records } or err.
recover-journal = fn [db_path str] enum
Replays and cleans up any hot rollback journal (<db_path>-journal) left by an interrupted commit.
open = fn [path str] SqliteDb
Opens an existing .sqlite / .db file from disk (automatically recovering <path>-journal if present),
creates a new file-backed database if it doesn't exist yet, or creates an in-memory database when path == ':memory:'.
save = fn [mut db SqliteDb] enum
Atomically flushes db to disk using a CRC-32 hot rollback journal (<path>-journal) + os/pwrite + os/fsync.
exec = fn [mut db SqliteDb, sql str, params block] any
Executes a DDL, transaction, or DML SQL statement (CREATE TABLE, CREATE [UNIQUE] INDEX,
ALTER TABLE ADD COLUMN, DROP TABLE, INSERT, UPDATE, DELETE, BEGIN, COMMIT, ROLLBACK).
Returns affected row count (or last inserted rowid on single-row INSERT).
use [sq = db/sqlite]
mut db = sq/open ':memory:'
_ = sq/exec mut db 'CREATE TABLE nodes (id INTEGER PRIMARY KEY, host TEXT UNIQUE, port INTEGER DEFAULT 443)' []
id1 = sq/exec mut db 'INSERT INTO nodes (host, port) VALUES (?, ?)' ['edge.veko-lang.org' 8443]
_ = sq/exec mut db 'ALTER TABLE nodes ADD COLUMN region TEXT DEFAULT \'ca-central\'' []
raw = sq/to-bytes db
db2 = sq/from-bytes raw
rows = sq/query-sql db2 'SELECT host, port, region FROM nodes WHERE id = ?' [id1]
if (len rows) != 1 or rows[0].port != 8443 or rows[0].region != 'ca-central' [ err 'sqlite roundtrip failed' ] else [ .ok ]
query-sql = fn [db SqliteDb, sql str, params block] block
Executes a parameterized SELECT query (? placeholders, optional INNER JOIN / LEFT JOIN)
and returns a block of row maps.
define-table = fn [table_name str, spec_blk block] TableSpec
Defines a declarative ORM TableSpec from a homoiconic (quote [...]) schema block:
define-table 'users' (quote [id i64 .pk, email str .unique, role str = 'member', score i64 = 0])
use [sq = db/sqlite]
users = sq/define-table 'users' (quote [
id i64 .pk
email str .unique
score i64 = 0
])
mut db = sq/open ':memory:'
_ = sq/migrate mut db users
uid = sq/insert mut db users { email = 'ada@veko-lang.org', score = 95 }
row = sq/find-by-id db users uid
top = sq/q db (quote [from users where [score >= 90] order-by [score .desc] limit 5])
if row.email != 'ada@veko-lang.org' or (len top) != 1 [ err 'ORM query failed' ] else [ .ok ]
migrate = fn [mut db SqliteDb, spec TableSpec] enum
Creates or auto-migrates spec on db (CREATE TABLE IF NOT EXISTS, ALTER TABLE ADD COLUMN for new fields, and CREATE [UNIQUE] INDEX IF NOT EXISTS).
insert = fn [mut db SqliteDb, spec TableSpec, record any] i64
Inserts a record map / struct into spec and returns the inserted rowid (i64).
find-by-id = fn [db SqliteDb, spec TableSpec, id any] map
Looks up a single record by primary key (err if not found, ready for /or).
update-by-id = fn [mut db SqliteDb, spec TableSpec, id any, patch map] i64
Updates fields in patch on the record matching id, returning updated row count.
delete-by-id = fn [mut db SqliteDb, spec TableSpec, id any] i64
Deletes the record matching id, returning deleted row count.
q = fn [db SqliteDb, dsl block] block
Executes a homoiconic Veko query dialect block against db:
sqlite/q db (quote [select [u.email o.total] from users u join orders o on [u.id == o.user_id] where [o.total >= 50] order-by [o.total .desc] limit 10])