Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -166,4 +167,16 @@ class NativeBoundaryTest {
assertTrue(s.step())
}
}

@Test
fun aPathWithAnEmbeddedNulIsRefusedInsteadOfOpeningTheFileNamedBeforeIt() {
val base = newTempDatabasePath()
try {
val e = assertFailsWith<SQLiteException> { 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)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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<sqlite3>()
val openResult = sealite_sqlite3_open_v2(filename = fileName, ppDb = dbPointer.ptr, flags = flags, zVfs = null)
val db = dbPointer.value
Expand Down