sqlite_test.v

1.8 KB · raw

1module storage23import os45fn temp_db(name string) !(Db, string) {6	dir := os.join_path(os.temp_dir(), 'koh3_test_${os.getpid()}_${name}')7	os.mkdir_all(dir)!8	db := open(os.join_path(dir, 'test.db'), 5000)!9	return db, dir10}1112fn test_links_the_vendored_sqlite() {13	// Guards the point of vendoring: the binary must carry our amalgamation,14	// not whatever SQLite the host happens to provide.15	assert libversion() == '3.49.1'16}1718fn test_blob_round_trip_keeps_embedded_nul() {19	mut db, dir := temp_db('blob')!20	defer {21		db.close()22		os.rmdir_all(dir) or {}23	}24	db.exec('CREATE TABLE objects (hash TEXT PRIMARY KEY, data BLOB)')!25	payload := [u8(0x00), 0x41, 0x00, 0xff, 0x7a]26	mut ins := db.prepare('INSERT INTO objects (hash, data) VALUES (?, ?)')!27	ins.bind_text(1, 'abc')!28	ins.bind_blob(2, payload)!29	ins.step()!30	ins.finalize()3132	mut sel := db.prepare('SELECT data, missing FROM (SELECT data, NULL AS missing FROM objects)')!33	assert sel.step()!34	assert sel.blob(0) == payload35	assert sel.text_or_none(1) == none36	sel.finalize()3738	mut sel2 := db.prepare('SELECT hash FROM objects WHERE hash = ?')!39	sel2.bind_text(1, 'abc')!40	assert sel2.step()!41	assert sel2.text(0) == 'abc'42	assert !sel2.step()!43	sel2.finalize()44}4546fn test_foreign_keys_enforce_references() {47	mut db, dir := temp_db('pragma')!48	defer {49		db.close()50		os.rmdir_all(dir) or {}51	}52	db.exec('PRAGMA journal_mode=WAL')!53	db.exec('PRAGMA foreign_keys=ON')!54	db.exec('CREATE TABLE saves (id TEXT PRIMARY KEY)')!55	db.exec('CREATE TABLE save_files (save_id TEXT REFERENCES saves(id), path TEXT)')!56	db.exec("INSERT INTO saves (id) VALUES ('a')")!57	if _ := db.exec("INSERT INTO save_files (save_id, path) VALUES ('ghost', 'x')") {58		assert false, 'a foreign key violation should have failed the insert'59	} else {60		assert err.msg().contains('FOREIGN KEY')61	}62}