diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseTest.kt index e9546f3..6274d80 100644 --- a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseTest.kt +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/CloseTest.kt @@ -3,15 +3,19 @@ package io.github.pasichdev.sealite +import androidx.sqlite.execSQL import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue /** Closing is idempotent and race free: a handle is released exactly once. */ class CloseTest { @@ -39,6 +43,45 @@ class CloseTest { assertEquals(Sealite.CheckResult.Ok, Sealite.check(path, rawKey(1))) } + @Test + fun closingTheLastConnectionCheckpointsTheWalAndRemovesIt() { + val path = newPath() + withDb(path, rawKey(1)) { db -> + db.execSQL("PRAGMA journal_mode = WAL") + db.createNotes("a", "b") + } + // SQLite's own rule for the last connection of a WAL database: checkpoint, then delete the + // -wal. A file left behind means the rows are not in the main database file yet. + assertNull(readFileBytes("$path-wal"), "the -wal survived the close") + withDb(path, rawKey(1)) { assertEquals(listOf("a", "b"), it.notes()) } + } + + @Test + fun aCloseThatInterruptsARunningQueryStillCheckpointsTheWal() = runTest { + val path = newPath() + SealiteDriver(rawKey(1)).use { driver -> + val db = driver.open(path) + db.execSQL("PRAGMA journal_mode = WAL") + db.createNotes("a", "b") + // Counting a recursive CTE of this size takes seconds unless it is interrupted. + val statement = + db.prepare( + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 300000000) " + + "SELECT count(*) FROM c", + ) + withContext(Dispatchers.Default) { + coroutineScope { + val stepper = async { runCatching { statement.step() } } + delay(50) // the query is running: close() has to interrupt it + db.close() + assertTrue(stepper.await().isFailure, "the query can not finish in time") + } + } + } + assertNull(readFileBytes("$path-wal"), "the -wal survived the close") + withDb(path, rawKey(1)) { assertEquals(listOf("a", "b"), it.notes()) } + } + @Test fun racingClosesReleaseTheHandleOnce() = runTest { val path = newPath() diff --git a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/NativeBoundaryTest.kt b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/NativeBoundaryTest.kt index 8c68d53..ce8fe5f 100644 --- a/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/NativeBoundaryTest.kt +++ b/sealite/src/commonTest/kotlin/io/github/pasichdev/sealite/NativeBoundaryTest.kt @@ -13,6 +13,7 @@ import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue /** What crosses the native boundary: text, blobs, names, messages and statements that are not statements. */ @@ -166,4 +167,16 @@ class NativeBoundaryTest { assertTrue(s.step()) } } + + @Test + fun aPathWithAnEmbeddedNulIsRefusedInsteadOfOpeningTheFileNamedBeforeIt() { + val base = newTempDatabasePath() + try { + val e = assertFailsWith { rawOpen(base + "\u0000-tail", flags).close() } + assertTrue("NUL" in e.message.orEmpty(), e.message) + assertNull(readFileBytes(base), "the path cut at its NUL was created") + } finally { + deleteDatabaseFiles(base) + } + } } diff --git a/sealite/src/jvmAndAndroidMain/kotlin/io/github/pasichdev/sealite/internal/JniRawDb.jvmAndAndroid.kt b/sealite/src/jvmAndAndroidMain/kotlin/io/github/pasichdev/sealite/internal/JniRawDb.jvmAndAndroid.kt index 86b9c30..3d421c0 100644 --- a/sealite/src/jvmAndAndroidMain/kotlin/io/github/pasichdev/sealite/internal/JniRawDb.jvmAndAndroid.kt +++ b/sealite/src/jvmAndAndroidMain/kotlin/io/github/pasichdev/sealite/internal/JniRawDb.jvmAndAndroid.kt @@ -22,6 +22,7 @@ package io.github.pasichdev.sealite.internal +import androidx.sqlite.SQLiteException import androidx.sqlite.SQLiteStatement import androidx.sqlite.throwSQLiteException import kotlinx.atomicfu.atomic @@ -78,22 +79,39 @@ internal class JniRawDb( // Interrupt until the lock is free, not once: sqlite3_step clears a pending interrupt when it // starts with no other statement running, so one that lands in the instant between another // thread taking the lock and starting its step would be lost, and this wait as long as that - // whole query. - while (true) { + // whole query. No interrupt at all when nothing is running. + while (!lock.tryLock()) { nativeInterrupt(connectionPointer) - if (lock.tryLock()) break LockSupport.parkNanos(RETRY_NANOS) } try { statements.toList().forEach { it.finalizeLocked() } statements.clear() - closed = true - nativeClose(connectionPointer) + try { + clearPendingInterrupt() + } finally { + closed = true + nativeClose(connectionPointer) + } } finally { lock.unlock() } } + /** + * An interrupt stays pending until SQLite compiles or starts a statement with none running. Left + * pending, it makes `sqlite3_close_v2` give up the checkpoint of a WAL database: the rows stay in + * a `-wal` file that outlives the last connection. Must hold [lock], with every statement + * finalized. + */ + private fun clearPendingInterrupt() { + try { + JniStatement(this, nativePrepare(connectionPointer, "SELECT 1")).finalizeLocked() + } catch (_: SQLiteException) { + // Out of memory at most: the handle is closed all the same. + } + } + /** Called by a statement, under [lock], once it has finalized itself. */ internal fun forget(statement: JniStatement) { statements.remove(statement) diff --git a/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeRawDb.kt b/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeRawDb.kt index 9220165..6862185 100644 --- a/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeRawDb.kt +++ b/sealite/src/nativeMain/kotlin/io/github/pasichdev/sealite/internal/NativeRawDb.kt @@ -22,6 +22,7 @@ package io.github.pasichdev.sealite.internal +import androidx.sqlite.SQLiteException import androidx.sqlite.SQLiteStatement import androidx.sqlite.throwSQLiteException import cnames.structs.sqlite3 @@ -112,22 +113,39 @@ internal class NativeRawDb( // Interrupt until the lock is free, not once: sqlite3_step clears a pending interrupt when it // starts with no other statement running, so one that lands in the instant between another // thread taking the lock and starting its step would be lost, and this wait as long as that - // whole query. - while (true) { + // whole query. No interrupt at all when nothing is running. + while (!lock.tryLock()) { sealite_sqlite3_interrupt(dbPointer) - if (lock.tryLock()) break usleep(RETRY_MICROSECONDS) } try { statements.toList().forEach { it.finalizeLocked() } statements.clear() - closed = true - sealite_sqlite3_close_v2(dbPointer) + try { + clearPendingInterrupt() + } finally { + closed = true + sealite_sqlite3_close_v2(dbPointer) + } } finally { lock.unlock() } } + /** + * An interrupt stays pending until SQLite compiles or starts a statement with none running. Left + * pending, it makes `sqlite3_close_v2` give up the checkpoint of a WAL database: the rows stay in + * a `-wal` file that outlives the last connection. Must hold [lock], with every statement + * finalized. + */ + private fun clearPendingInterrupt() { + try { + prepare("SELECT 1").close() + } catch (_: SQLiteException) { + // Out of memory at most: the handle is closed all the same. + } + } + /** Called by a statement, under [lock], once it has finalized itself. */ internal fun forget(statement: NativeStatement) { statements.remove(statement) @@ -144,6 +162,8 @@ internal class NativeRawDb( } internal actual fun rawOpen(fileName: String, flags: Int): RawDb = memScoped { + // The C string would end at the NUL and name a different file; the JNI binding refuses it too. + if ('\u0000' in fileName) throwSQLiteException(SQLITE_MISUSE, "database path must not contain NUL") val dbPointer = allocPointerTo() val openResult = sealite_sqlite3_open_v2(filename = fileName, ppDb = dbPointer.ptr, flags = flags, zVfs = null) val db = dbPointer.value