Skip to content

Conversation

opatry
Copy link
Owner

@opatry opatry commented Jun 1, 2025

Description

  • Abstract RoomDatabase.withTransaction to allow Jvm implementation using Transactor
  • Generalize the use of transactions where relevant
  • Validate it really works 😅
  • Find a way to unit test this characteristic

Checklist

  • I have read the CONTRIBUTING guide
  • Code compiles correctly
  • Created tests which fail without the change (if possible)
  • All tests passing

See https://developer.android.com/training/data-storage/room/room-kmp-migration#sqlite-driver-to_1

Room Android

val database: RoomDatabase = ...
database.runInTransaction {
  // perform database operations in transaction
}

Room KMP

val database: RoomDatabase = ...
database.useWriterConnection { transactor ->
  transactor.immediateTransaction {
    // perform database operations in transaction
  }
}
  • So maybe we could just remove the expect/actual and just always rely on the KMP version even for Android.

Summary by Sourcery

Introduce a TransactionRunner abstraction to centralize database transactions and wrap all TaskRepository operations in transactions, and provide platform-specific implementations via DI modules for JVM and Android while updating tests and DI definitions to accommodate the new interface.

Enhancements:

  • Add TransactionRunner interface to common code to encapsulate transaction execution.
  • Refactor TaskRepository to wrap all database operations in TransactionRunner.runInTransaction calls.
  • Provide JVM and Android implementations of TransactionRunner in respective DI modules using Room’s useWriterConnection and withTransaction.
  • Update DI module tests and repository tests to inject and use TransactionRunner.

Tests:

  • Introduce TestTransactionRunner in common tests for TaskRepository.
  • Update DI verification tests to include TransactionRunner dependency for TaskRepository.

@opatry opatry marked this pull request as draft June 1, 2025 10:11
@opatry opatry linked an issue Jun 1, 2025 that may be closed by this pull request
@opatry opatry force-pushed the kmp-transaction-runner branch 2 times, most recently from 9391eb6 to 2a5533c Compare June 7, 2025 08:28
@opatry opatry force-pushed the kmp-transaction-runner branch from 2a5533c to cdd836e Compare June 7, 2025 08:28
Copy link
Contributor

github-actions bot commented Jun 7, 2025

Job Summary for Gradle

Build & Test :: unit-tests
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
Taskfolio test :tasks-app-android:testStoreReleaseUnitTest jvmTest 8.12.1 Build Scan not published

@opatry
Copy link
Owner Author

opatry commented Jun 25, 2025

/gemini review this pr

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the TransactionRunner abstraction to allow JVM implementation. The changes are solid, but there are a few areas in TaskRepository.kt that could be improved for maintainability and correctness, especially around handling data returned from transactions and fixing a potential bug.

Comment on lines +58 to +67
single<TransactionRunner> {
object : TransactionRunner {
override suspend fun <R> runInTransaction(logic: suspend () -> R): R {
val db = get<TasksAppDatabase>()
return db.withTransaction {
logic()
}
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The TasksAppDatabase instance is resolved using get() inside runInTransaction, meaning it's resolved on every call. Resolving the dependency once when the TransactionRunner is created would be more efficient.

    single<TransactionRunner> {
        val db = get<TasksAppDatabase>()
        object : TransactionRunner {
            override suspend fun <R> runInTransaction(logic: suspend () -> R): R {
                return db.withTransaction(logic)
            }
        }
    }

Comment on lines +59 to +70
single<TransactionRunner> {
object : TransactionRunner {
override suspend fun <R> runInTransaction(logic: suspend () -> R): R {
val db = get<TasksAppDatabase>()
return db.useWriterConnection { transactor ->
transactor.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE) {
logic()
}
}
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The TasksAppDatabase for JVM resolves on every transaction. Optimizing by resolving it once when the TransactionRunner is created would be more efficient.

    single<TransactionRunner> {
        val db = get<TasksAppDatabase>()
        object : TransactionRunner {
            override suspend fun <R> runInTransaction(logic: suspend () -> R): R {
                return db.useWriterConnection { transactor ->
                    transactor.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE, logic)
                }
            }
        }
    }

Comment on lines +380 to +388
val taskListEntity = transactionRunner.runInTransaction {
requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
.copy(
title = newTitle,
lastUpdateDate = now
).also { taskListEntity ->
taskListDao.upsert(taskListEntity)
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of .also with a lambda parameter taskListEntity that shadows the outer variable being assigned can be confusing. Rewriting the code to be more explicit and easier to follow by using intermediate variables would improve readability and maintainability.

Suggested change
val taskListEntity = transactionRunner.runInTransaction {
requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
.copy(
title = newTitle,
lastUpdateDate = now
).also { taskListEntity ->
taskListDao.upsert(taskListEntity)
}
}
val taskListEntity = transactionRunner.runInTransaction {
val originalTaskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
val updatedTaskListEntity = originalTaskListEntity.copy(
title = newTitle,
lastUpdateDate = now
)
taskListDao.upsert(updatedTaskListEntity)
updatedTaskListEntity
}

Comment on lines +446 to 471
var taskId: Long = -1
val (taskListEntity, parentTaskEntity, taskEntity) = transactionRunner.runInTransaction {
val taskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
val parentTaskEntity = parentTaskId?.let { requireNotNull(taskDao.getById(it)) { "Invalid parent task id $parentTaskId" } }
val now = nowProvider.now()
val firstPosition = 0.toTaskPosition()
val currentTasks = taskDao.getTasksFromPositionOnward(taskListId, parentTaskId, firstPosition)
.toMutableList()
val taskEntity = TaskEntity(
parentListLocalId = taskListId,
parentTaskLocalId = parentTaskId,
title = title,
notes = notes,
lastUpdateDate = now,
dueDate = dueDate,
position = firstPosition,
)
// FIXME dedicated data structure for all returned data to avoid var & Triple
val taskId_ = taskDao.insert(taskEntity)
taskId = taskId_
if (currentTasks.isNotEmpty()) {
val updatedTasks = computeTaskPositions(currentTasks, newPositionStart = 1)
taskDao.upsertAll(updatedTasks)
}
Triple(taskListEntity, parentTaskEntity, taskEntity)
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation uses a var taskId which is modified as a side effect from within the transaction lambda. Refactor this to have the transaction block return all necessary data, avoiding side effects. Using a dedicated data class for the return type is the cleanest solution.

        val (transactionResult, taskId) = transactionRunner.runInTransaction {
            val taskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
            val parentTaskEntity = parentTaskId?.let { requireNotNull(taskDao.getById(it)) { "Invalid parent task id $parentTaskId" } }
            val now = nowProvider.now()
            val firstPosition = 0.toTaskPosition()
            val currentTasks = taskDao.getTasksFromPositionOnward(taskListId, parentTaskId, firstPosition)
                .toMutableList()
            val taskEntity = TaskEntity(
                parentListLocalId = taskListId,
                parentTaskLocalId = parentTaskId,
                title = title,
                notes = notes,
                lastUpdateDate = now,
                dueDate = dueDate,
                position = firstPosition,
            )
            val newTaskId = taskDao.insert(taskEntity)
            if (currentTasks.isNotEmpty()) {
                val updatedTasks = computeTaskPositions(currentTasks, newPositionStart = 1)
                taskDao.upsertAll(updatedTasks)
            }
            Triple(taskListEntity, parentTaskEntity, taskEntity) to newTaskId
        }
        val (taskListEntity, parentTaskEntity, taskEntity) = transactionResult

Comment on lines +524 to +533
val (taskListRemoteId, updatedTaskEntity) = transactionRunner.runInTransaction {
val taskEntity = requireNotNull(taskDao.getById(taskId)) { "Invalid task id $taskId" }
// FIXME early exit, how?
// val updatedTaskEntity = updateLogic(taskEntity, now) ?: return
val updatedTaskEntity = updateLogic(taskEntity, now) ?: error("TODO")

taskDao.upsert(updatedTaskEntity)
taskDao.upsert(updatedTaskEntity)

val taskListRemoteId = taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId
taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId to updatedTaskEntity
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Handle early exits from within a transaction block. A clean way to handle this is to have the transaction return a nullable result. If updateLogic returns null, the transaction block can also return null.

        val result = transactionRunner.runInTransaction {
            val taskEntity = requireNotNull(taskDao.getById(taskId)) { "Invalid task id $taskId" }
            updateLogic(taskEntity, now)?.let { updatedTaskEntity ->
                taskDao.upsert(updatedTaskEntity)
                taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId to updatedTaskEntity
            }
        } ?: return

        val (taskListRemoteId, updatedTaskEntity) = result

@opatry
Copy link
Owner Author

opatry commented Jun 25, 2025

@sourcery-ai review

@opatry
Copy link
Owner Author

opatry commented Jun 25, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Jun 25, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Jun 25, 2025

Warning

Rate limit exceeded

@opatry has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8af80b0 and cdd836e.

📒 Files selected for processing (7)
  • tasks-app-shared/src/androidMain/kotlin/net/opatry/tasks/app/di/platformModule.android.kt (2 hunks)
  • tasks-app-shared/src/androidUnitTest/kotlin/net/opatry/tasks/app/di/AndroidDITest.kt (2 hunks)
  • tasks-app-shared/src/commonTest/kotlin/net/opatry/tasks/data/util/runTaskRepositoryTest.kt (3 hunks)
  • tasks-app-shared/src/jvmMain/kotlin/net/opatry/tasks/app/di/platformModule.jvm.kt (2 hunks)
  • tasks-app-shared/src/jvmTest/kotlin/net/opatry/tasks/app/di/DesktopDITest.kt (2 hunks)
  • tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt (11 hunks)
  • tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TransactionRunner.kt (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

sourcery-ai bot commented Jun 25, 2025

Reviewer's Guide

This PR introduces a TransactionRunner abstraction to unify transaction handling across platforms, refactors TaskRepository to wrap DAO operations in runInTransaction blocks, and updates DI modules and tests to provide platform-specific implementations.

Sequence diagram for TaskRepository DAO operations with TransactionRunner

sequenceDiagram
    participant Client
    participant TaskRepository
    participant TransactionRunner
    participant DAO
    Client->>TaskRepository: call repository method (e.g., deleteTask)
    TaskRepository->>TransactionRunner: runInTransaction { ... }
    TransactionRunner->>DAO: perform DAO operations
    DAO-->>TransactionRunner: result
    TransactionRunner-->>TaskRepository: result
    TaskRepository-->>Client: result
Loading

Class diagram for TransactionRunner abstraction and TaskRepository refactor

classDiagram
    class TransactionRunner {
        <<interface>>
        +suspend runInTransaction(logic: suspend () -> R): R
    }
    class TaskRepository {
        -transactionRunner: TransactionRunner
        +deleteTaskList(taskListId: Long)
        +renameTaskList(taskListId: Long, newTitle: String)
        +clearTaskListCompletedTasks(taskListId: Long)
        +createTask(taskListId: Long, parentTaskId: Long?, title: String, notes: String, dueDate: Instant?): Long
        +deleteTask(taskId: Long)
        +applyTaskUpdate(taskId: Long, updateLogic: suspend (TaskEntity, Instant) -> TaskEntity?)
        +indentTask(taskId: Long)
        +unindentTask(taskId: Long)
        +moveToTop(taskId: Long)
        +moveToList(taskId: Long, destinationListId: Long)
    }
    TaskRepository --> TransactionRunner
Loading

Class diagram for platform-specific TransactionRunner implementations

classDiagram
    class TransactionRunner {
        <<interface>>
        +suspend runInTransaction(logic: suspend () -> R): R
    }
    class AndroidTransactionRunner {
        +suspend runInTransaction(logic: suspend () -> R): R
    }
    class JvmTransactionRunner {
        +suspend runInTransaction(logic: suspend () -> R): R
    }
    TransactionRunner <|.. AndroidTransactionRunner
    TransactionRunner <|.. JvmTransactionRunner
Loading

File-Level Changes

Change Details Files
Introduce TransactionRunner abstraction for cross-platform transactions
  • Define TransactionRunner interface in commonMain
  • Add JVM implementation using Room.useWriterConnection and Transactor.withTransaction
  • Add Android implementation using RoomDatabase.withTransaction in DI
tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TransactionRunner.kt
tasks-app-shared/src/jvmMain/kotlin/net/opatry/tasks/app/di/platformModule.jvm.kt
tasks-app-shared/src/androidMain/kotlin/net/opatry/tasks/app/di/platformModule.android.kt
Refactor TaskRepository to leverage TransactionRunner
  • Inject TransactionRunner into TaskRepository constructor
  • Wrap all DAO read/write sequences in runInTransaction blocks
  • Return necessary entities or data from transactional scopes
tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt
Update DI tests and test utilities to include TransactionRunner
  • Use TestTransactionRunner in runTaskRepositoryTest utility
  • Add TransactionRunner dependency to TaskRepository definitions in AndroidDITest
  • Add TransactionRunner dependency to TaskRepository definitions in DesktopDITest
tasks-app-shared/src/commonTest/kotlin/net/opatry/tasks/data/util/runTaskRepositoryTest.kt
tasks-app-shared/src/androidUnitTest/kotlin/net/opatry/tasks/app/di/AndroidDITest.kt
tasks-app-shared/src/jvmTest/kotlin/net/opatry/tasks/app/di/DesktopDITest.kt

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @opatry - I've reviewed your changes - here's some feedback:

  • TaskRepository’s runInTransaction blocks use mutable vars and Triple/Pair destructuring with FIXMEs—extract domain-specific result data classes or helper methods to eliminate the var/Triple pattern and improve readability.
  • There’s duplicated upsert-and-position-recompute logic across multiple repository methods—consider abstracting the fetch-update-upsert sequence into a reusable higher-order function to reduce boilerplate.
  • The JVM TransactionRunner uses IMMEDIATE transactions while Android uses the default type—review and align these choices to ensure consistent isolation semantics across platforms.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- TaskRepository’s runInTransaction blocks use mutable vars and Triple/Pair destructuring with FIXMEs—extract domain-specific result data classes or helper methods to eliminate the var/Triple pattern and improve readability.
- There’s duplicated upsert-and-position-recompute logic across multiple repository methods—consider abstracting the fetch-update-upsert sequence into a reusable higher-order function to reduce boilerplate.
- The JVM TransactionRunner uses IMMEDIATE transactions while Android uses the default type—review and align these choices to ensure consistent isolation semantics across platforms.

## Individual Comments

### Comment 1
<location> `tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt:447` </location>
<code_context>
+        val (taskListEntity, parentTaskEntity, taskEntity) = transactionRunner.runInTransaction {
</code_context>

<issue_to_address>
The use of a mutable var (taskId) outside the transaction block is error-prone.

Returning taskId as part of the Triple and using destructuring will help avoid mutable state and reduce the risk of concurrency or retry-related bugs.

Suggested implementation:

```
        val (taskListEntity, parentTaskEntity, taskId) = transactionRunner.runInTransaction {
            val taskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
            val parentTaskEntity = parentTaskId?.let { requireNotNull(taskDao.getById(it)) { "Invalid parent task id $parentTaskId" } }
            val now = nowProvider.now()
            val firstPosition = 0.toTaskPosition()
            val currentTasks = taskDao.getTasksFromPositionOnward(taskListId, parentTaskId, firstPosition)
                .toMutableList()
            val taskEntity = TaskEntity(
                parentListLocalId = taskListId,
                parentTaskLocalId = parentTaskId,
                title = title,
            )
            val insertedTaskId = taskDao.insert(taskEntity)
            Triple(taskListEntity, parentTaskEntity, insertedTaskId)

```

If you need to use `taskEntity` after the transaction, you can return a Quadruple or a data class containing all needed values instead of a Triple. Adjust the destructuring and return accordingly.
</issue_to_address>

### Comment 2
<location> `tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt:526` </location>
<code_context>
-        val updatedTaskEntity = updateLogic(taskEntity, now) ?: return
+        val (taskListRemoteId, updatedTaskEntity) = transactionRunner.runInTransaction {
+            val taskEntity = requireNotNull(taskDao.getById(taskId)) { "Invalid task id $taskId" }
+            // FIXME early exit, how?
+//            val updatedTaskEntity = updateLogic(taskEntity, now) ?: return
+            val updatedTaskEntity = updateLogic(taskEntity, now) ?: error("TODO")

-        taskDao.upsert(updatedTaskEntity)
</code_context>

<issue_to_address>
The workaround for early exit in runInTransaction is inelegant and may cause confusion.

Using error("TODO") as a placeholder will crash the app if updateLogic returns null. Please refactor runInTransaction or updateLogic to handle early returns or nulls more safely.
</issue_to_address>

### Comment 3
<location> `tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt:640` </location>
<code_context>
+            val taskListRemoteId = taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId

-        val taskListRemoteId = taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId
+            // FIXME
+            previousSubtaskRemoteId = previousSubtaskRemoteId_
+            Triple(taskListRemoteId, parentTaskEntity, updatedTaskEntity)
+        }
         if (taskListRemoteId != null && updatedTaskEntity.remoteId != null) {
</code_context>

<issue_to_address>
The use of a mutable variable (previousSubtaskRemoteId) outside the transaction block is fragile.

Returning all necessary values from the transaction block avoids potential bugs and improves code clarity.

Suggested implementation:

```
            val (taskListRemoteId, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId) = withContext(Dispatchers.IO) {
                // ... your transaction block code ...
                val taskListRemoteId_ = taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId
                // ... compute parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId_ ...
                Triple(taskListRemoteId_, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId_)
            }

            val task = /* ... use taskListRemoteId, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId as needed ... */
                try {
    }

```

- You will need to ensure that the transaction block returns a data structure (such as a data class or a tuple) containing all the required values: `taskListRemoteId`, `parentTaskEntity`, `updatedTaskEntity`, and `previousSubtaskRemoteId`.
- Update all usages of these variables after the transaction block to use the unpacked values.
- Remove any mutable variable declarations for `previousSubtaskRemoteId` outside the transaction block.
- If you need more than three values, consider using a data class instead of `Triple`.
</issue_to_address>

### Comment 4
<location> `tasks-core/src/commonMain/kotlin/net/opatry/tasks/data/TaskRepository.kt:793` </location>
<code_context>
+                taskDao.upsertAll(updatedTaskEntities)
+            }
+
+            // FIXME should already be available in entity, quick & dirty workaround
+            val newTaskListRemoteId = destinationTaskListEntity.remoteId
+            val taskListRemoteId = taskListDao.getById(taskEntity.parentListLocalId)?.remoteId

-        // FIXME should already be available in entity, quick & dirty workaround
-        val newTaskListRemoteId = destinationTaskListEntity.remoteId
-        val taskListRemoteId = taskListDao.getById(taskEntity.parentListLocalId)?.remoteId
-        if (taskListRemoteId != null && taskEntity.remoteId != null && newTaskListRemoteId != null) {
+            Triple(taskListRemoteId, newTaskListRemoteId, updatedTaskEntity)
+        }
+        if (taskListRemoteId != null && updatedTaskEntity.remoteId != null && newTaskListRemoteId != null) {
</code_context>

<issue_to_address>
Fetching remoteId from the database after upsert is inefficient and may be inconsistent.

Fetching remoteId after upsert risks inconsistencies if the entity changes in between. Please ensure remoteId is reliably available in the updated entity or refactor the model to eliminate the need for this extra lookup.

Suggested implementation:

```
            // Use remoteId directly from the in-memory entities to avoid extra DB lookup
            val newTaskListRemoteId = destinationTaskListEntity.remoteId
            val taskListRemoteId = taskEntity.parentListRemoteId

            Triple(taskListRemoteId, newTaskListRemoteId, updatedTaskEntity)
        }
        if (taskListRemoteId != null && updatedTaskEntity.remoteId != null && newTaskListRemoteId != null) {

```

- Ensure that `TaskEntity` has a `parentListRemoteId` property that is always set when the entity is loaded or updated. If this property does not exist, you will need to add it and ensure it is populated wherever `TaskEntity` is constructed or updated.
- Remove any other unnecessary lookups for `remoteId` from the database in similar contexts.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +447 to +456
val (taskListEntity, parentTaskEntity, taskEntity) = transactionRunner.runInTransaction {
val taskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
val parentTaskEntity = parentTaskId?.let { requireNotNull(taskDao.getById(it)) { "Invalid parent task id $parentTaskId" } }
val now = nowProvider.now()
val firstPosition = 0.toTaskPosition()
val currentTasks = taskDao.getTasksFromPositionOnward(taskListId, parentTaskId, firstPosition)
.toMutableList()
val taskEntity = TaskEntity(
parentListLocalId = taskListId,
parentTaskLocalId = parentTaskId,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): The use of a mutable var (taskId) outside the transaction block is error-prone.

Returning taskId as part of the Triple and using destructuring will help avoid mutable state and reduce the risk of concurrency or retry-related bugs.

Suggested implementation:

        val (taskListEntity, parentTaskEntity, taskId) = transactionRunner.runInTransaction {
            val taskListEntity = requireNotNull(taskListDao.getById(taskListId)) { "Invalid task list id $taskListId" }
            val parentTaskEntity = parentTaskId?.let { requireNotNull(taskDao.getById(it)) { "Invalid parent task id $parentTaskId" } }
            val now = nowProvider.now()
            val firstPosition = 0.toTaskPosition()
            val currentTasks = taskDao.getTasksFromPositionOnward(taskListId, parentTaskId, firstPosition)
                .toMutableList()
            val taskEntity = TaskEntity(
                parentListLocalId = taskListId,
                parentTaskLocalId = parentTaskId,
                title = title,
            )
            val insertedTaskId = taskDao.insert(taskEntity)
            Triple(taskListEntity, parentTaskEntity, insertedTaskId)

If you need to use taskEntity after the transaction, you can return a Quadruple or a data class containing all needed values instead of a Triple. Adjust the destructuring and return accordingly.

Comment on lines +526 to +528
// FIXME early exit, how?
// val updatedTaskEntity = updateLogic(taskEntity, now) ?: return
val updatedTaskEntity = updateLogic(taskEntity, now) ?: error("TODO")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): The workaround for early exit in runInTransaction is inelegant and may cause confusion.

Using error("TODO") as a placeholder will crash the app if updateLogic returns null. Please refactor runInTransaction or updateLogic to handle early returns or nulls more safely.

Comment on lines +640 to +642
// FIXME
previousSubtaskRemoteId = previousSubtaskRemoteId_
Triple(taskListRemoteId, parentTaskEntity, updatedTaskEntity)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The use of a mutable variable (previousSubtaskRemoteId) outside the transaction block is fragile.

Returning all necessary values from the transaction block avoids potential bugs and improves code clarity.

Suggested implementation:

            val (taskListRemoteId, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId) = withContext(Dispatchers.IO) {
                // ... your transaction block code ...
                val taskListRemoteId_ = taskListDao.getById(updatedTaskEntity.parentListLocalId)?.remoteId
                // ... compute parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId_ ...
                Triple(taskListRemoteId_, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId_)
            }

            val task = /* ... use taskListRemoteId, parentTaskEntity, updatedTaskEntity, previousSubtaskRemoteId as needed ... */
                try {
    }

  • You will need to ensure that the transaction block returns a data structure (such as a data class or a tuple) containing all the required values: taskListRemoteId, parentTaskEntity, updatedTaskEntity, and previousSubtaskRemoteId.
  • Update all usages of these variables after the transaction block to use the unpacked values.
  • Remove any mutable variable declarations for previousSubtaskRemoteId outside the transaction block.
  • If you need more than three values, consider using a data class instead of Triple.

Comment on lines +793 to +797
// FIXME should already be available in entity, quick & dirty workaround
val newTaskListRemoteId = destinationTaskListEntity.remoteId
val taskListRemoteId = taskListDao.getById(taskEntity.parentListLocalId)?.remoteId

// FIXME should already be available in entity, quick & dirty workaround
val newTaskListRemoteId = destinationTaskListEntity.remoteId
val taskListRemoteId = taskListDao.getById(taskEntity.parentListLocalId)?.remoteId
if (taskListRemoteId != null && taskEntity.remoteId != null && newTaskListRemoteId != null) {
Triple(taskListRemoteId, newTaskListRemoteId, updatedTaskEntity)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Fetching remoteId from the database after upsert is inefficient and may be inconsistent.

Fetching remoteId after upsert risks inconsistencies if the entity changes in between. Please ensure remoteId is reliably available in the updated entity or refactor the model to eliminate the need for this extra lookup.

Suggested implementation:

            // Use remoteId directly from the in-memory entities to avoid extra DB lookup
            val newTaskListRemoteId = destinationTaskListEntity.remoteId
            val taskListRemoteId = taskEntity.parentListRemoteId

            Triple(taskListRemoteId, newTaskListRemoteId, updatedTaskEntity)
        }
        if (taskListRemoteId != null && updatedTaskEntity.remoteId != null && newTaskListRemoteId != null) {

  • Ensure that TaskEntity has a parentListRemoteId property that is always set when the entity is loaded or updated. If this property does not exist, you will need to add it and ensure it is populated wherever TaskEntity is constructed or updated.
  • Remove any other unnecessary lookups for remoteId from the database in similar contexts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Transactional database updates when needed Despite task position recomputation, it takes some time (sync?) to update task menu state

1 participant