This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Transaction

Transaction is a database concept commonly referred to as a “Transaction.” It has four attributes: Atomicity, Consistency, Isolation, Durability abbreviated to ACID.

Atomicity refers to the fact that any number of operations done in a transaction are like one operation and either succeed or fail. Success indicates that all operations are complete. Failure indicates that some operations are faulty. After the failure, the system reverts the database status to before the transaction is executed. Using this property can be very simple to solve the problem of database read and write conflict.

Consistency refers to the fact that the database changes state correctly on successfully committed transactions.

Isolation refers to the fact that transactions operate independently and transparently. This is masked in Room because Room can only execute a maximum of one transaction at a time, and other transactions are queued and executed on a first-come, first-served basis.

Persistence refers to ensuring that the result or effect of a committed transaction survives in the event of a system failure.

In fact, @INSERT, @update, and @DELETE are transactions, and an Insert, Update, or Delete is used in @Query, which is also marked by @Transaction by default.

This way, if one of your transactions is time consuming, you’ll have to queue the rest of the time.

However, you can also use this feature to combine a series of operations into a transaction, such as a search, change, and search operation (here’s the pseudocode) :

@Transaction
fun someOperation():Int{
    val a = find1()
    insert(a)
    return find2()
}
Copy the code

Although coroutines can also achieve this effect (provided suspend is added to all operation functions), coroutines recommend cancelling, and @Transaction guarantees atomicity. In fact, there is no difference in performance.

Note: you can’t suspend sqLite before @transaction after 2.2.6 because it causes multiple threads to read and write sqLite at the same time, resulting in a deadlock.

Optimize the first query speed

The first query will be slower, whether it’s one query or 3000 queries, it might actually take around 200ms, which is the limitation of SQLite…

Solution: Hot start Sqlite when the customer is not aware of the first check.