module storage import os fn temp_db(name string) !(Db, string) { dir := os.join_path(os.temp_dir(), 'koh3_test_${os.getpid()}_${name}') os.mkdir_all(dir)! db := connect(os.join_path(dir, 'test.db'), 5000)! return db, dir } fn test_links_the_vendored_sqlite() { // Guards the point of vendoring: the binary must carry our amalgamation, // not whatever SQLite the host happens to provide. assert libversion() == '3.49.1' } fn test_blob_round_trip_keeps_embedded_nul() { mut db, dir := temp_db('blob')! defer { db.close() os.rmdir_all(dir) or {} } db.exec('CREATE TABLE objects (hash TEXT PRIMARY KEY, data BLOB)')! payload := [u8(0x00), 0x41, 0x00, 0xff, 0x7a] mut ins := db.prepare('INSERT INTO objects (hash, data) VALUES (?, ?)')! ins.bind_text(1, 'abc')! ins.bind_blob(2, payload)! ins.step()! ins.finalize() mut sel := db.prepare('SELECT data, missing FROM (SELECT data, NULL AS missing FROM objects)')! assert sel.step()! assert sel.blob(0) == payload assert sel.text_or_none(1) == none sel.finalize() mut sel2 := db.prepare('SELECT hash FROM objects WHERE hash = ?')! sel2.bind_text(1, 'abc')! assert sel2.step()! assert sel2.text(0) == 'abc' assert !sel2.step()! sel2.finalize() } fn test_foreign_keys_enforce_references() { mut db, dir := temp_db('pragma')! defer { db.close() os.rmdir_all(dir) or {} } db.exec('PRAGMA journal_mode=WAL')! db.exec('PRAGMA foreign_keys=ON')! db.exec('CREATE TABLE saves (id TEXT PRIMARY KEY)')! db.exec('CREATE TABLE save_files (save_id TEXT REFERENCES saves(id), path TEXT)')! db.exec("INSERT INTO saves (id) VALUES ('a')")! if _ := db.exec("INSERT INTO save_files (save_id, path) VALUES ('ghost', 'x')") { assert false, 'a foreign key violation should have failed the insert' } else { assert err.msg().contains('FOREIGN KEY') } } // Two agents share one repo. A second writer must hear what is going on and // what to do, not SQLite's bare "database is locked". fn test_a_busy_repo_says_another_command_is_writing() { dir := os.join_path(os.temp_dir(), 'koh3_test_${os.getpid()}_busy') os.rmdir_all(dir) or {} os.mkdir_all(dir)! defer { os.rmdir_all(dir) or {} } first := create(dir)! defer { first.close() } second := open(dir)! defer { second.close() } first.begin()! // No waiting in a test: the second writer finds the lock taken at once. second.db.exec('PRAGMA busy_timeout = 0')! if _ := second.begin() { assert false, 'a second writer must not get the lock' } else { assert err.msg().contains('another koh command is writing') } first.rollback() }