1 package expo.modules.updates.db.dao
2 
3 import androidx.room.Dao
4 import androidx.room.Insert
5 import androidx.room.Query
6 import androidx.room.Transaction
7 import expo.modules.updates.db.entity.JSONDataEntity
8 import java.util.*
9 
10 /**
11  * Utility class for accessing and modifying data in the `json_data` SQLite table.
12  */
13 @Dao
14 abstract class JSONDataDao {
15   /**
16    * for private use only
17    * must be marked public for Room
18    * so we use the underscore to discourage use
19    */
20   @Query("SELECT * FROM json_data WHERE `key` = :key AND scope_key = :scopeKey ORDER BY last_updated DESC LIMIT 1;")
_loadJSONDataForKeynull21   abstract fun _loadJSONDataForKey(key: String, scopeKey: String): List<JSONDataEntity>
22 
23   @Insert
24   abstract fun _insertJSONData(jsonDataEntity: JSONDataEntity)
25 
26   @Query("DELETE FROM json_data WHERE `key` = :key AND scope_key = :scopeKey;")
27   abstract fun _deleteJSONDataForKey(key: String, scopeKey: String)
28 
29   /**
30    * for public use
31    */
32   fun loadJSONStringForKey(key: String, scopeKey: String): String? {
33     val rows = _loadJSONDataForKey(key, scopeKey)
34     return if (rows.isEmpty()) {
35       null
36     } else rows[0].value
37   }
38 
39   @Transaction
setJSONStringForKeynull40   open fun setJSONStringForKey(key: String, value: String, scopeKey: String) {
41     _deleteJSONDataForKey(key, scopeKey)
42     _insertJSONData(JSONDataEntity(key, value, Date(), scopeKey))
43   }
44 
45   @Transaction
setMultipleFieldsnull46   open fun setMultipleFields(fields: Map<String, String>, scopeKey: String) {
47     val iterator = fields.entries.iterator()
48     while (iterator.hasNext()) {
49       val entry = iterator.next()
50       _deleteJSONDataForKey(entry.key, scopeKey)
51       _insertJSONData(JSONDataEntity(entry.key, entry.value, Date(), scopeKey))
52     }
53   }
54 
55   @Transaction
updateJSONStringForKeynull56   open fun updateJSONStringForKey(key: String, scopeKey: String, updater: (previousValue: String?) -> String) {
57     val previousValue = loadJSONStringForKey(key, scopeKey)
58     _deleteJSONDataForKey(key, scopeKey)
59     _insertJSONData(JSONDataEntity(key, updater(previousValue), Date(), scopeKey))
60   }
61 }
62