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 @@ -48,6 +48,7 @@ public class AndroidxSqliteDriver(
private val onCreate: AndroidxSqliteDriver.() -> Unit = {},
private val onUpdate: AndroidxSqliteDriver.(Long, Long) -> Unit = { _, _ -> },
private val onOpen: AndroidxSqliteDriver.() -> Unit = {},
connectionPool: ConnectionPool? = null,
vararg migrationCallbacks: AfterVersion,
) : SqlDriver {
public constructor(
Expand All @@ -60,6 +61,7 @@ public class AndroidxSqliteDriver(
onCreate: SqlDriver.() -> Unit = {},
onUpdate: SqlDriver.(Long, Long) -> Unit = { _, _ -> },
onOpen: SqlDriver.() -> Unit = {},
connectionPool: ConnectionPool? = null,
vararg migrationCallbacks: AfterVersion,
) : this(
createConnection = driver::open,
Expand All @@ -71,14 +73,15 @@ public class AndroidxSqliteDriver(
onCreate = onCreate,
onUpdate = onUpdate,
onOpen = onOpen,
connectionPool = connectionPool,
migrationCallbacks = migrationCallbacks,
)

@Suppress("NonBooleanPropertyPrefixedWithIs")
private val isFirstInteraction = atomic(true)

private val connectionPool by lazy {
ConnectionPool(
connectionPool ?: AndroidxDriverConnectionPool(
createConnection = createConnection,
name = when(databaseType) {
is AndroidxSqliteDatabaseType.File -> databaseType.databaseFilePath
Expand Down Expand Up @@ -199,12 +202,12 @@ public class AndroidxSqliteDriver(
else -> (enclosing as Transaction).connection
}
val transaction = Transaction(enclosing, transactionConnection)
transactions.set(transaction)

if(enclosing == null) {
transactionConnection.execSQL("BEGIN IMMEDIATE")
}

transactions.set(transaction)

return QueryResult.Value(transaction)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,22 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

internal class ConnectionPool(
public interface ConnectionPool : AutoCloseable {
public fun acquireWriterConnection(): SQLiteConnection
public fun releaseWriterConnection()
public fun acquireReaderConnection(): SQLiteConnection
public fun releaseReaderConnection(connection: SQLiteConnection)
public fun setForeignKeyConstraintsEnabled(isForeignKeyConstraintsEnabled: Boolean)
public fun setJournalMode(journalMode: SqliteJournalMode)
public fun setSync(sync: SqliteSync)
}

internal class AndroidxDriverConnectionPool(
private val createConnection: (String) -> SQLiteConnection,
private val name: String,
private val isFileBased: Boolean,
private val configuration: AndroidxSqliteConfiguration,
) {
) : ConnectionPool {
private val writerConnection: SQLiteConnection by lazy {
createConnection(name).withConfiguration()
}
Expand All @@ -39,23 +49,23 @@ internal class ConnectionPool(
* Acquires the writer connection, blocking if it's currently in use.
* @return The writer SQLiteConnection
*/
fun acquireWriterConnection() = runBlocking {
override fun acquireWriterConnection() = runBlocking {
writerMutex.lock()
writerConnection
}

/**
* Releases the writer connection (mutex unlocks automatically).
*/
fun releaseWriterConnection() {
override fun releaseWriterConnection() {
writerMutex.unlock()
}

/**
* Acquires a reader connection, blocking if none are available.
* @return A reader SQLiteConnection
*/
fun acquireReaderConnection() = when(maxReaderConnectionsCount) {
override fun acquireReaderConnection() = when(maxReaderConnectionsCount) {
0 -> acquireWriterConnection()
else -> runBlocking {
readerChannel.receive().value
Expand All @@ -66,25 +76,27 @@ internal class ConnectionPool(
* Releases a reader connection back to the pool.
* @param connection The SQLiteConnection to release
*/
fun releaseReaderConnection(connection: SQLiteConnection) = when(maxReaderConnectionsCount) {
0 -> releaseWriterConnection()
else -> runBlocking {
readerChannel.send(lazy { connection })
override fun releaseReaderConnection(connection: SQLiteConnection) {
when(maxReaderConnectionsCount) {
0 -> releaseWriterConnection()
else -> runBlocking {
readerChannel.send(lazy { connection })
}
}
}

fun setForeignKeyConstraintsEnabled(isForeignKeyConstraintsEnabled: Boolean) {
override fun setForeignKeyConstraintsEnabled(isForeignKeyConstraintsEnabled: Boolean) {
configuration.isForeignKeyConstraintsEnabled = isForeignKeyConstraintsEnabled
val foreignKeys = if(isForeignKeyConstraintsEnabled) "ON" else "OFF"
runPragmaOnAllConnections("PRAGMA foreign_keys = $foreignKeys;")
}

fun setJournalMode(journalMode: SqliteJournalMode) {
override fun setJournalMode(journalMode: SqliteJournalMode) {
configuration.journalMode = journalMode
runPragmaOnAllConnections("PRAGMA journal_mode = ${configuration.journalMode.value};")
}

fun setSync(sync: SqliteSync) {
override fun setSync(sync: SqliteSync) {
configuration.sync = sync
runPragmaOnAllConnections("PRAGMA synchronous = ${configuration.sync.value};")
}
Expand Down Expand Up @@ -121,7 +133,7 @@ internal class ConnectionPool(
/**
* Closes all connections in the pool.
*/
fun close() {
override fun close() {
runBlocking {
writerMutex.withLock {
writerConnection.close()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.eygraber.sqldelight.androidx.driver

import androidx.sqlite.SQLiteConnection
import app.cash.sqldelight.TransacterImpl
import app.cash.sqldelight.db.AfterVersion
import app.cash.sqldelight.db.QueryResult
Expand All @@ -9,7 +10,9 @@ import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue

abstract class AndroidxSqliteTransacterTest {
Expand All @@ -18,7 +21,13 @@ abstract class AndroidxSqliteTransacterTest {

private fun setupDatabase(
schema: SqlSchema<QueryResult.Value<Unit>>,
): SqlDriver = AndroidxSqliteDriver(androidxSqliteTestDriver(), AndroidxSqliteDatabaseType.Memory, schema)
connectionPool: ConnectionPool? = null,
): SqlDriver = AndroidxSqliteDriver(
driver = androidxSqliteTestDriver(),
databaseType = AndroidxSqliteDatabaseType.Memory,
schema = schema,
connectionPool = connectionPool,
)

@BeforeTest
fun setup() {
Expand All @@ -43,6 +52,32 @@ abstract class AndroidxSqliteTransacterTest {
driver.close()
}

@Test
fun ifBeginningANonEnclosedTransactionFails_furtherTransactionsAreNotBlockedFromBeginning() {
this.driver.close()

val driver = setupDatabase(
object : SqlSchema<QueryResult.Value<Unit>> {
override val version = 1L
override fun create(driver: SqlDriver): QueryResult.Value<Unit> = QueryResult.Unit
override fun migrate(
driver: SqlDriver,
oldVersion: Long,
newVersion: Long,
vararg callbacks: AfterVersion,
): QueryResult.Value<Unit> = QueryResult.Unit
},
connectionPool = FirstTransactionsFailConnectionPool(),
)
val transacter = object : TransacterImpl(driver) {}
this.driver = driver
assertFails {
transacter.transaction(noEnclosing = true) {}
}
assertNull(driver.currentTransaction())
transacter.transaction(noEnclosing = true) {}
}

@Test
fun afterCommitRunsAfterTransactionCommits() {
var counter = 0
Expand Down Expand Up @@ -282,3 +317,35 @@ abstract class AndroidxSqliteTransacterTest {
)
}
}

private class FirstTransactionsFailConnectionPool : ConnectionPool {
private val firstTransactionFailConnection = object : SQLiteConnection {
private var isFirstBeginTransaction = true

private val connection = androidxSqliteTestDriver().open(":memory:")

override fun close() {
connection.close()
}

override fun prepare(sql: String) =
if(sql == "BEGIN IMMEDIATE" && isFirstBeginTransaction) {
isFirstBeginTransaction = false
error("Throwing an error")
}
else {
connection.prepare(sql)
}
}

override fun close() {
firstTransactionFailConnection.close()
}
override fun acquireWriterConnection() = firstTransactionFailConnection
override fun releaseWriterConnection() {}
override fun acquireReaderConnection() = firstTransactionFailConnection
override fun releaseReaderConnection(connection: SQLiteConnection) {}
override fun setForeignKeyConstraintsEnabled(isForeignKeyConstraintsEnabled: Boolean) {}
override fun setJournalMode(journalMode: SqliteJournalMode) {}
override fun setSync(sync: SqliteSync) {}
}