Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct SQLiteLayerTests {7 private func scratchDatabase() async throws -> SQLiteDatabase {8 let database = try await SQLiteDatabase(location: .memory, configuration: .init())9 try await database.write {10 try $0.executeScript("CREATE TABLE item (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, score REAL, payload BLOB, flag INTEGER, at REAL)")11 }12 return database13 }1415 @Test func typedValuesRoundTrip() async throws {16 let database = try await scratchDatabase()17 let blob = Data((0..<1_024).map { UInt8($0 % 251) })18 let text = "Ünïcødé 漢字 🚀 with\u{0}NUL and 'quotes' \"too\""19 let date = second(12_345)20 try await database.write {21 try $0.execute("INSERT INTO item (id, name, score, payload, flag, at) VALUES (?, ?, ?, ?, ?, ?)",22 [7, text, 2.5, blob, true, date])23 try $0.execute("INSERT INTO item (id, name, score, payload, flag, at) VALUES (?, ?, ?, ?, ?, ?)",24 [8, "empty", nil, Data(), false, nil])25 }26 let rows = try await database.read { try $0.query("SELECT * FROM item ORDER BY id") }27 #expect(rows.count == 2)28 #expect(try rows[0].get("id", as: Int.self) == 7)29 #expect(try rows[0].get("name", as: String.self) == text)30 #expect(try rows[0].get("score", as: Double.self) == 2.5)31 #expect(try rows[0].get("payload", as: Data.self) == blob)32 #expect(try rows[0].get("flag", as: Bool.self) == true)33 #expect(try rows[0].get("at", as: Date.self) == date)34 #expect(try rows[1].get("score", as: Double?.self) == nil)35 // A zero-length blob stays a blob, it does not become NULL.36 #expect(try rows[1].get("payload", as: Data.self) == Data())37 #expect(try rows[1].get("at", as: Date?.self) == nil)38 #expect(throws: PersistenceError.self) { try rows[0].get("name", as: Int.self) }39 #expect(throws: PersistenceError.self) { try rows[0].get("missing", as: Int.self) }40 }4142 @Test func identifiersAndURLsBindAsText() async throws {43 let database = try await scratchDatabase()44 let id = TabID()45 let address = url("https://example.com/a?b=c#d")46 let stored = try await database.write { connection -> [SQLiteRow] in47 try connection.query("SELECT ? AS id, ? AS url, typeof(?) AS kind", [id, address, id])48 }49 #expect(try stored[0].get("id", as: TabID.self) == id)50 #expect(try stored[0].get("url", as: URL.self) == address)51 #expect(try stored[0].get("kind", as: String.self) == "text")52 }5354 @Test func errorsCarrySQLiteCodeAndMessage() async throws {55 let database = try await scratchDatabase()56 try await database.write { try $0.execute("INSERT INTO item (name) VALUES ('a')") }57 do {58 try await database.write { try $0.execute("INSERT INTO item (name) VALUES ('a')") }59 Issue.record("expected a constraint violation")60 } catch let error as SQLiteError {61 #expect(error.code == 19) // SQLITE_CONSTRAINT62 #expect(error.extendedCode == 2067) // SQLITE_CONSTRAINT_UNIQUE63 #expect(error.isConstraintViolation)64 #expect(error.message.contains("UNIQUE"))65 #expect(error.sql?.contains("INSERT INTO item") == true)66 }67 do {68 try await database.write { try $0.execute("SELEC nonsense") }69 Issue.record("expected a syntax error")70 } catch let error as SQLiteError {71 #expect(error.code == 1) // SQLITE_ERROR72 #expect(error.message.contains("syntax"))73 }74 // A wrong parameter count is caught before running, not silently bound as NULL.75 await #expect(throws: SQLiteError.self) {76 try await database.write { try $0.execute("INSERT INTO item (name) VALUES (?)", []) }77 }78 }7980 @Test func transactionCommitsAtomicallyAndRollsBackOnThrow() async throws {81 struct Boom: Error {}82 let database = try await scratchDatabase()83 try await database.transaction { connection in84 try connection.execute("INSERT INTO item (name) VALUES ('kept-1')")85 try connection.execute("INSERT INTO item (name) VALUES ('kept-2')")86 }87 await #expect(throws: Boom.self) {88 try await database.transaction { connection in89 try connection.execute("INSERT INTO item (name) VALUES ('lost-1')")90 try connection.execute("INSERT INTO item (name) VALUES ('lost-2')")91 throw Boom()92 }93 }94 // A failing statement in the middle also undoes the statements before it.95 await #expect(throws: SQLiteError.self) {96 try await database.transaction { connection in97 try connection.execute("INSERT INTO item (name) VALUES ('lost-3')")98 try connection.execute("INSERT INTO item (name) VALUES ('kept-1')")99 }100 }101 let names = try await database.read { connection in102 try connection.query("SELECT name FROM item ORDER BY name").map { try $0.get("name", as: String.self) }103 }104 #expect(names == ["kept-1", "kept-2"])105 // The connection is usable and not stuck in a transaction.106 #expect(try await database.write { $0.isInTransaction } == false)107 }108109 @Test func nestedTransactionRollsBackOnlyTheInnerWork() async throws {110 struct Boom: Error {}111 let database = try await scratchDatabase()112 try await database.transaction { connection in113 try connection.execute("INSERT INTO item (name) VALUES ('outer')")114 do {115 try connection.transaction {116 try connection.execute("INSERT INTO item (name) VALUES ('inner')")117 throw Boom()118 }119 } catch is Boom {}120 try connection.transaction { _ = try connection.execute("INSERT INTO item (name) VALUES ('inner-ok')") }121 }122 let names = try await database.read { connection in123 try connection.query("SELECT name FROM item ORDER BY name").map { try $0.get("name", as: String.self) }124 }125 #expect(names == ["inner-ok", "outer"])126 }127128 @Test func preparedStatementsAreReusedAndReset() async throws {129 let database = try await scratchDatabase()130 try await database.transaction { connection in131 for index in 0..<2_000 {132 try connection.execute("INSERT INTO item (name, score) VALUES (?, ?)", ["n\(index)", Double(index)])133 }134 }135 let total = try await database.read { try $0.scalar("SELECT sum(score) FROM item", as: Double.self) }136 #expect(total == Double(2_000 * 1_999 / 2))137 // More distinct statements than the cache holds: eviction must not break anything.138 let mismatches = try await database.write { connection -> Int in139 var mismatches = 0140 for index in 0..<600 where try connection.scalar("SELECT \(index) + ?", [1], as: Int.self) != index + 1 {141 mismatches += 1142 }143 return mismatches144 }145 #expect(mismatches == 0)146 }147148 @Test func fileDatabaseUsesWALForeignKeysAndBusyTimeout() async throws {149 let scratch = try ScratchDirectory()150 let database = try await NavigatorDatabase(url: scratch.databaseURL)151 let pragmas = try await database.sqlite.write { connection in152 (try connection.scalar("PRAGMA journal_mode", as: String.self),153 try connection.scalar("PRAGMA foreign_keys", as: Int.self),154 try connection.scalar("PRAGMA busy_timeout", as: Int.self),155 try connection.scalar("PRAGMA synchronous", as: Int.self))156 }157 #expect(pragmas.0 == "wal")158 #expect(pragmas.1 == 1)159 #expect(pragmas.2 == 5_000)160 #expect(pragmas.3 == 1) // NORMAL161 // Readers are read-only connections: a write through the read path is refused by SQLite.162 await #expect(throws: SQLiteError.self) {163 try await database.sqlite.read { try $0.execute("DELETE FROM profiles") }164 }165 // Foreign keys are enforced: a space cannot reference a missing profile.166 await #expect(throws: SQLiteError.self) {167 try await database.sqlite.write {168 try $0.execute("""169 INSERT INTO spaces (id, profile_id, name, symbol, tint, focus, created_at, updated_at)170 VALUES ('x', 'missing', 'n', 's', 't', '{}', 0, 0)171 """)172 }173 }174 await database.close()175 await #expect(throws: PersistenceError.databaseClosed) { try await database.profiles.all() }176 }177178 @Test func concurrentReadersAndWritersStayConsistent() async throws {179 let scratch = try ScratchDirectory()180 let database = try await NavigatorDatabase(url: scratch.databaseURL)181 try await database.sqlite.write { try $0.executeScript("CREATE TABLE pair (id INTEGER PRIMARY KEY, writer INTEGER, half INTEGER)") }182 let writers = 4, perWriter = 150, readers = 8, perReader = 150183184 let oddSnapshots = try await withThrowingTaskGroup(of: Int.self) { group in185 for writer in 0..<writers {186 group.addTask {187 for _ in 0..<perWriter {188 // Two rows per transaction: a reader must never observe only one of them.189 try await database.sqlite.transaction { connection in190 try connection.execute("INSERT INTO pair (writer, half) VALUES (?, 0)", [writer])191 try connection.execute("INSERT INTO pair (writer, half) VALUES (?, 1)", [writer])192 }193 }194 return 0195 }196 }197 for _ in 0..<readers {198 group.addTask {199 var odd = 0200 for _ in 0..<perReader {201 let counts = try await database.sqlite.read { connection in202 // Two statements in one read: both must see the same snapshot.203 (try connection.scalar("SELECT count(*) FROM pair", as: Int.self) ?? 0,204 try connection.scalar("SELECT count(*) FROM pair WHERE half = 0", as: Int.self) ?? 0)205 }206 if counts.0 % 2 != 0 || counts.0 != counts.1 * 2 { odd += 1 }207 }208 return odd209 }210 }211 return try await group.reduce(0, +)212 }213 #expect(oddSnapshots == 0)214 let total = try await database.sqlite.read { try $0.scalar("SELECT count(*) FROM pair", as: Int.self) }215 #expect(total == writers * perWriter * 2)216 // Read-your-writes through the reader pool.217 try await database.sqlite.write { try $0.execute("INSERT INTO pair (writer, half) VALUES (99, 0)") }218 #expect(try await database.sqlite.read { try $0.scalar("SELECT count(*) FROM pair WHERE writer = 99", as: Int.self) } == 1)219 await database.close()220 }221}222