I am trying to insert data from a prepopulated database (EnglishVocabs.db) into table "vocab" of my Android app (app_database.db). I am using the following code to perform this operation:
val appDbFile = context.getDatabasePath("app_database.db")
val appdb = SQLiteDatabase.openDatabase(appDbFile.path, null, SQLiteDatabase.OPEN_READWRITE)
val insertUniqueVocabsSqlForAppDb = """
ATTACH '${preDbFile.path}' AS preDb;
INSERT INTO vocab(word, language_id, parts_json)
SELECT DISTINCT B.word, ${Language.ENGLISH.id}, B.parts_json
FROM preDb.EnglishVocabs AS B
WHERE B.word NOT IN (SELECT A.word FROM vocab A);
""".trimIndent()
appdb.beginTransactionWithListener(object : SQLiteTransactionListener {
override fun onBegin() {
Logger.d("on begin")
}
override fun onCommit() {
Logger.d("on commit")
}
override fun onRollback() {
Logger.d("on rollback")
}
})
try {
Logger.d("attached db = ${appdb.attachedDbs}")
val c = appdb.rawQuery(insertUniqueVocabsSqlForAppDb, arrayOf())
appdb.setTransactionSuccessful()
Logger.d("transaction success")
if(c.moveToFirst()){
Logger.d("response = ${c.getStringOrNull(0)}")
}
c.close()
}catch (e: Exception){
Logger.e(e.stackTraceToString())
}finally {
appdb.endTransaction()
appdb.close()
}
I am able to successfully run this code and the onCommit() method of the transaction listener is being called, indicating that the transaction has been committed.
However, when I go to check the app_database.db, the data has not been inserted.
Interestingly, when I copy both the prepopulated and app databases to my PC and run the SQL code using SQLite DB Browser, the data is inserted successfully (40k rows in 200ms). I am not sure what the issue could be in the Android environment. I've grant all necessary permissions.
Can anyone help me understand why this might be happening and how I can fix it?
UPDATE:
I use sqldelight as my app database. and I tried sqlDriver.execute()... too, nothing works
The method rawQuery() is used to return rows and not for INSERT statements.
Instead you should use execSQL() in 2 separate calls:
appdb.execSQL("ATTACH '${preDbFile.path}' AS preDb");
val insertUniqueVocabsSqlForAppDb = """
INSERT INTO vocab(word, language_id, parts_json)
SELECT DISTINCT B.word, ${Language.ENGLISH.id}, B.parts_json
FROM preDb.EnglishVocabs AS B
WHERE B.word NOT IN (SELECT A.word FROM vocab A);
""".trimIndent()
appdb.execSQL(insertUniqueVocabsSqlForAppDb)
I have converted my app to use Android Room for SQLite DB. There are some crashes on different devices with my implementation.
Fatal Exception: android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)
at android.database.sqlite.SQLiteConnection.nativeExecute(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.execute(SQLiteConnection.java:707)
at android.database.sqlite.SQLiteConnection.setLocaleFromConfiguration(SQLiteConnection.java:473)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:261)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:205)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:505)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:206)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:198)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:918)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:898)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:762)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:751)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:373)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:316)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:145)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:106)
at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:97)
at androidx.room.RoomDatabase.internalBeginTransaction(RoomDatabase.java:482)
at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:471)
at com.luzeon.MyApp.sqlite.ViewLogDao_Impl$5.call(ViewLogDao_Impl.java:94)
at com.luzeon.MyApp.sqlite.ViewLogDao_Impl$5.call(ViewLogDao_Impl.java:91)
at androidx.room.CoroutinesRoom$Companion$execute$2.invokeSuspend(CoroutinesRoom.kt:61)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:47)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
I have created the apps Room DB
#Database(entities = [ViewLogModel::class], version = 4)
abstract class MyAppDatabase : RoomDatabase() {
abstract fun viewLogDao(): ViewLogDao
companion object {
// For Singleton Instance
#Volatile
private var INSTANCE: MyAppDatabase? = null
fun getAppDataBase(context: Context): MyAppDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(context.applicationContext, MyAppDatabase::class.java, "MyAppDatabase")
.createFromAsset(“myapp.db")
.setJournalMode(RoomDatabase.JournalMode.TRUNCATE) // disable WAL
.fallbackToDestructiveMigration()
.build()
}
}
fun destroyDataBase(){
INSTANCE = null
}
}
}
And have a DB Helper class
class MyAppDatabaseHelper(private val context: Context, private val coroutineScope: CoroutineScope) {
fun updateViewLog(viewLogModel: ViewLogModel) {
try {
// get the database
val db = MyAppDatabase.getAppDataBase(context)
coroutineScope.launch {
// store in db
db.viewLogDao().insertOrUpdateViewLog(viewLogModel)
}
} catch (e: Exception) {}
}
suspend fun getViewLog(memberId: Int): JSONArray {
try {
val jsonArray = JSONArray()
// get the database
val db = MyAppDatabase.getAppDataBase(context)
val viewLog = db.viewLogDao().getViewLog(memberId)
for (view in viewLog) {
// create the object
val jsonObject = JSONObject()
try {
jsonObject.put("mid", view.mid)
} catch (e: JSONException) {
}
try {
jsonObject.put("uts", view.uts)
} catch (e: JSONException) {
}
jsonArray.put(jsonObject)
}
// clear log (current user records or records older than 24hrs)
db.viewLogDao().deleteViewLog(memberId, Utilities.getUtsYesterday().toFloat())
// return the array
return jsonArray
} catch (e: Exception) {
return JSONArray()
}
}
}
With ViewLogDao
#Dao
interface ViewLogDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertOrUpdateViewLog(viewLog: ViewLogModel)
#Update
suspend fun updateViewLog(viewLog: ViewLogModel)
#Delete
suspend fun deleteAllViewLog(viewLog: ViewLogModel)
#Query("DELETE FROM viewlog WHERE VID= :vid OR UTS < :uts")
suspend fun deleteViewLog(vid: Int, uts: Float)
#Query("SELECT * FROM viewLog")
suspend fun getAll(): List<ViewLogModel>
#Query("SELECT * FROM viewLog WHERE vid = :vid")
suspend fun getViewLog(vid: Int): List<ViewLogModel>
}
And ViewLogModel
#Entity(tableName = "viewLog")
data class ViewLogModel(
#ColumnInfo(name = "VID") val vid: Int,
#ColumnInfo(name = "UTS") val uts: Float,
#ColumnInfo(name = "MID") #PrimaryKey val mid: Int)
I have not been able to find how to catch the SQLiteReadOnlyDatabaseException in the rare occurrences when the DB is read only. Or is there a way to ensure the ROOM Db is read/write?
I have not been able to find how to catch the SQLiteReadOnlyDatabaseException in the rare occurrences when the DB is read only. Or is there a way to ensure the ROOM Db is read/write?
The message code 1032 SQLITE_READONLY_DBMOVED :-
The SQLITE_READONLY_DBMOVED error code is an extended error code for SQLITE_READONLY. The SQLITE_READONLY_DBMOVED error code indicates that a database cannot be modified because the database file has been moved since it was opened, and so any attempt to modify the database might result in database corruption if the processes crashes because the rollback journal would not be correctly named.
If the message is to be believed then the database has been moved/renamed. From the message it would appear that the (one of the two being handled) database is being renamed whilst it is open.
In the log many of the entries are similar so it looks like two databases are being managed i.e. it is the stage of creating the database from the asset.
This may well be an issue with the createFromAsset handling which I understand to not necessarily be rock solid. e.g. at present there are issues with the prePackagedDatabaseCallback.
As such by using createFromAsset that you can do nothing other than raise an issue.
I would suggest circumventing the issue and pre-copying the asset yourself before passing control to Room.
to undertake the copy you do not need to open the database as a database just as a file.
The other alternative, could be to see if exclusively using WAL mode, overcomes the issue. As you are disabling WAL mode, then I guess that you have no wish to do so (hence why suggested as the last).
this would not only entail not disabling WAL mode but also having the asset set to WAL mode before distribution.
I am trying to get the user ID from the newest user. How can I make the insert method spit the ID when the ID is autogenerated?
in Model
#PrimaryKey(autoGenerate = true)
val userId: Int
in Dao
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun addUserWithLong(user: User): LiveData<Long>
in Repository
fun addUserWitLong(user: User): LiveData<Long> {
return userDao.addUserWithLong(user)
}
in ViewModel
fun addUserWithLong(user: User): LiveData<Long> {
return repository.addUserWitLong(user)
}
in Fragment
val id: Long? = userViewModel.addUserWithLong(user).value
I have read in the docs that #Insert returns Long as the row ID but I do not know how to program it. Now the error is "Not sure how handle insert method return type." Is there some way to make with LiveData and not with Rxjava. That is without the need to download more dependecies.
As per the documentation here
If the #Insert method receives a single parameter, it can return a
long value, which is the new rowId for the inserted item. If the
parameter is an array or a collection, then the method should return
an array or a collection of long values instead, with each value as
the rowId for one of the inserted items. To learn more about returning
rowId values, see the reference documentation for the #Insert
annotation, as well as the SQLite documentation for rowid tables
So you can use it like
#Insert(onConflict = OnConflictStrategy.REPLACE)
long addUserWithLong(user: User)
or if you are inserting a list
#Insert(onConflict = OnConflictStrategy.REPLACE)
long[] addUserWithLong(user: List<User>)
Edit-1
After checking answers from this post.
No, you can't. I wrote an answer to the issue. The reason is, that
LiveData is used to notify for changes. Insert, Update, Delete won't
trigger a change.
I just created a test project and successfully received Id of last inserted item in activity. Here is my implementation.
Dao
#Insert
suspend fun addUser(user: Users): Long
Repo
suspend fun insertUser(context: Context, users: Users): Long {
val db = AppDatabase.getInstance(context)
val dao = db.userDao()
return dao.addUser(users)
}
ViewModel
fun addUser(context: Context, users: Users) = liveData {
//you can also emit your customized object here.
emit("Inserting...")
try {
val userRepo = UsersRepo()
val response = userRepo.insertUser(context, users)
emit(response)
} catch (e: Exception) {
e.printStackTrace()
emit(e.message)
}
}
Activity
viewModel.addUser(applicationContext, user).observe(this, Observer { userId ->
Log.d("MainActivity", "Inserted User Id is $userId")
})
Check test application here.
I'm trying to implement offline first app by returning local data to UI before fetching remote data.
Here's my code
Repository
val trip: LiveData<DomainTrip> = Transformations.map(database.tripDao.getTrip(tripId)) {
it.asDomainModel()
}
suspend fun refreshTrip(token: String) {
withContext(Dispatchers.IO) {
val trip = webservice.getTrip(tripId, "Bearer $token").await()
database.tripDao.insertAll(trip.asDatabaseModel())
}
}
DAO
interface TripDao {
#Query("select * from databasetrip WHERE _id = :id")
fun getTrip(id: String): LiveData<DatabaseTrip>
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(trip: DatabaseTrip)
}
ViewModel
private val tripRepository = TripRepository(getDatabase(application), tripId)
var trip = tripRepository.trip
If the user is opening a trip that is already stored in the database, above code works without any problem. it.asDomainModel() gets called as soon as user opens that trip. it.asDomainModel() gets called again as soon as that trip is retrieved from remote and saved into the database.
My problem is, if user is opening a trip that is not in the database, above code crashes when it.asDomainModel() is called the first time, with null pointer exception on it.
What confuses me more is that if above code were applied to this dao query
#Query("select * from databasetripinfo")
fun getTrips(): LiveData<List<DatabaseTripInfo>>
i won't get any null pointers exception on both call of it.asDomainModel() even when my database is empty.
Can somebody please help me? How do I avoid null pointer exception on it.asDomainModel() when database does not have that record?
thx
It's all OK. If there is no item with the given id, the live data will return null. You can check for nullity before mapping in the transformation (it?.asDomainModel)
However for lists you will get empty list instead of null (it's a convention).
Android's Room persistence library graciously includes the #Insert and #Update annotations that work for objects or collections. I however have a use case (push notifications containing a model) that would require an UPSERT as the data may or may not exist in the database.
Sqlite doesn't have upsert natively, and workarounds are described in this SO question. Given the solutions there, how would one apply them to Room?
To be more specific, how can I implement an insert or update in Room that would not break any foreign key constraints? Using insert with onConflict=REPLACE will cause the onDelete for any foreign key to that row to be called. In my case onDelete causes a cascade, and reinserting a row will cause rows in other tables with the foreign key to be deleted. This is NOT the intended behavior.
EDIT:
as #Tunji_D mentioned,
Room officially supports #Upsert from version 2.5.0-alpha03. (release note)
please check his answer for more details.
OLD ANSWER:
Perhaps you can make your BaseDao like this.
secure the upsert operation with #Transaction,
and try to update only if insertion is failed.
#Dao
public abstract class BaseDao<T> {
/**
* Insert an object in the database.
*
* #param obj the object to be inserted.
* #return The SQLite row id
*/
#Insert(onConflict = OnConflictStrategy.IGNORE)
public abstract long insert(T obj);
/**
* Insert an array of objects in the database.
*
* #param obj the objects to be inserted.
* #return The SQLite row ids
*/
#Insert(onConflict = OnConflictStrategy.IGNORE)
public abstract List<Long> insert(List<T> obj);
/**
* Update an object from the database.
*
* #param obj the object to be updated
*/
#Update
public abstract void update(T obj);
/**
* Update an array of objects from the database.
*
* #param obj the object to be updated
*/
#Update
public abstract void update(List<T> obj);
/**
* Delete an object from the database
*
* #param obj the object to be deleted
*/
#Delete
public abstract void delete(T obj);
#Transaction
public void upsert(T obj) {
long id = insert(obj);
if (id == -1) {
update(obj);
}
}
#Transaction
public void upsert(List<T> objList) {
List<Long> insertResult = insert(objList);
List<T> updateList = new ArrayList<>();
for (int i = 0; i < insertResult.size(); i++) {
if (insertResult.get(i) == -1) {
updateList.add(objList.get(i));
}
}
if (!updateList.isEmpty()) {
update(updateList);
}
}
}
For more elegant way to do that I would suggest two options:
Checking for return value from insert operation with IGNORE as a OnConflictStrategy (if it equals to -1 then it means row wasn't inserted):
#Insert(onConflict = OnConflictStrategy.IGNORE)
long insert(Entity entity);
#Update(onConflict = OnConflictStrategy.IGNORE)
void update(Entity entity);
#Transaction
public void upsert(Entity entity) {
long id = insert(entity);
if (id == -1) {
update(entity);
}
}
Handling exception from insert operation with FAIL as a OnConflictStrategy:
#Insert(onConflict = OnConflictStrategy.FAIL)
void insert(Entity entity);
#Update(onConflict = OnConflictStrategy.FAIL)
void update(Entity entity);
#Transaction
public void upsert(Entity entity) {
try {
insert(entity);
} catch (SQLiteConstraintException exception) {
update(entity);
}
}
EDIT:
Starting in version 2.5.0-alpha03, Room now has support for an #Upsert annotation.
An example of its use can be seen in this pull request in the "Now in Android" sample app.
OLD ANSWER:
I could not find a SQLite query that would insert or update without causing unwanted changes to my foreign key, so instead I opted to insert first, ignoring conflicts if they occurred, and updating immediately afterwards, again ignoring conflicts.
The insert and update methods are protected so external classes see and use the upsert method only. Keep in mind that this isn't a true upsert as if any of the MyEntity POJOS have null fields, they will overwrite what may currently be in the database. This is not a caveat for me, but it may be for your application.
#Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract void insert(List<MyEntity> entities);
#Update(onConflict = OnConflictStrategy.IGNORE)
protected abstract void update(List<MyEntity> entities);
#Transaction
public void upsert(List<MyEntity> entities) {
insert(models);
update(models);
}
If the table has more than one column, you can use
#Insert(onConflict = OnConflictStrategy.REPLACE)
to replace a row.
Reference - Go to tips Android Room Codelab
This is the code in Kotlin:
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(entity: Entity): Long
#Update(onConflict = OnConflictStrategy.REPLACE)
fun update(entity: Entity)
#Transaction
fun upsert(entity: Entity) {
val id = insert(entity)
if (id == -1L) {
update(entity)
}
}
Just an update for how to do this with Kotlin retaining data of the model (Maybe to use it in a counter as in example):
//Your Dao must be an abstract class instead of an interface (optional database constructor variable)
#Dao
abstract class ModelDao(val database: AppDatabase) {
#Insert(onConflict = OnConflictStrategy.FAIL)
abstract fun insertModel(model: Model)
//Do a custom update retaining previous data of the model
//(I use constants for tables and column names)
#Query("UPDATE $MODEL_TABLE SET $COUNT=$COUNT+1 WHERE $ID = :modelId")
abstract fun updateModel(modelId: Long)
//Declare your upsert function open
open fun upsert(model: Model) {
try {
insertModel(model)
}catch (exception: SQLiteConstraintException) {
updateModel(model.id)
}
}
}
You can also use #Transaction and database constructor variable for more complex transactions using database.openHelper.writableDatabase.execSQL("SQL STATEMENT")
I found an interesting reading about it here.
It is the "same" as posted on https://stackoverflow.com/a/50736568/4744263. But, if you want an idiomatic and clean Kotlin version, here you go:
#Transaction
open fun insertOrUpdate(objList: List<T>) = insert(objList)
.withIndex()
.filter { it.value == -1L }
.forEach { update(objList[it.index]) }
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(obj: List<T>): List<Long>
#Update
abstract fun update(obj: T)
Alternatively to make UPSERT manually in loop like it's suggested in #yeonseok.seo post, we may use UPSERT feature provided by Sqlite v.3.24.0 in Android Room.
Nowadays, this feature is supported by Android 11 and 12 with default Sqlite version 3.28.0 and 3.32.2 respectively. If you need it in versions prior Android 11 you can replace default Sqlite with custom Sqlite project like this https://github.com/requery/sqlite-android (or built your own) to have this and other features that are available in latest Sqlite versions, but not available in Android Sqlite provided by default.
If you have Sqlite version starting from 3.24.0 on device, you can use UPSERT in Android Room like this:
#Query("INSERT INTO Person (name, phone) VALUES (:name, :phone) ON CONFLICT (name) DO UPDATE SET phone=excluded.phone")
fun upsert(name: String, phone: String)
Another approach I can think of is to get the entity via DAO by query, and then perform any desired updates.
This may be less efficient compared to the other solutions in this thread in terms of runtime because of having to retrieve the full entity, but allows much more flexibility in terms of operations allowed such as on what fields/variable to update.
For example :
private void upsert(EntityA entityA) {
EntityA existingEntityA = getEntityA("query1","query2");
if (existingEntityA == null) {
insert(entityA);
} else {
entityA.setParam(existingEntityA.getParam());
update(entityA);
}
}
Here is a way to use a real UPSERT clause in Room library.
The main advantage of this method is that you can update rows for which you don't know their ID.
Setup Android SQLite support library in your project to use modern SQLite features on all devices:
Inherit your daos from BasicDao.
Probably, you want to add in your BasicEntity: abstract fun toMap(): Map<String, Any?>
Use UPSERT in your Dao:
#Transaction
private suspend fun upsert(entity: SomeEntity): Map<String, Any?> {
return upsert(
SomeEntity.TABLE_NAME,
entity.toMap(),
setOf(SomeEntity.SOME_UNIQUE_KEY),
setOf(SomeEntity.ID),
)
}
// An entity has been created. You will get ID.
val rawEntity = someDao.upsert(SomeEntity(0, "name", "key-1"))
// An entity has been updated. You will get ID too, despite you didn't know it before, just by unique constraint!
val rawEntity = someDao.upsert(SomeEntity(0, "new name", "key-1"))
BasicDao:
import android.database.Cursor
import androidx.room.*
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
abstract class BasicDao(open val database: RoomDatabase) {
/**
* Upsert all fields of the entity except those specified in [onConflict] and [excludedColumns].
*
* Usually, you don't want to update PK, you can exclude it in [excludedColumns].
*
* [UPSERT](https://www.sqlite.org/lang_UPSERT.html) syntax supported since version 3.24.0 (2018-06-04).
* [RETURNING](https://www.sqlite.org/lang_returning.html) syntax supported since version 3.35.0 (2021-03-12).
*/
protected suspend fun upsert(
table: String,
entity: Map<String, Any?>,
onConflict: Set<String>,
excludedColumns: Set<String> = setOf(),
returning: Set<String> = setOf("*")
): Map<String, Any?> {
val updatableColumns = entity.keys
.filter { it !in onConflict && it !in excludedColumns }
.map { "`${it}`=excluded.`${it}`" }
// build sql
val comma = ", "
val placeholders = entity.map { "?" }.joinToString(comma)
val returnings = returning.joinToString(comma) { if (it == "*") it else "`${it}`" }
val sql = "INSERT INTO `${table}` VALUES (${placeholders})" +
" ON CONFLICT(${onConflict.joinToString(comma)}) DO UPDATE SET" +
" ${updatableColumns.joinToString(comma)}" +
" RETURNING $returnings"
val query: SupportSQLiteQuery = SimpleSQLiteQuery(sql, entity.values.toTypedArray())
val cursor: Cursor = database.openHelper.writableDatabase.query(query)
return getCursorResult(cursor).first()
}
protected fun getCursorResult(cursor: Cursor, isClose: Boolean = true): List<Map<String, Any?>> {
val result = mutableListOf<Map<String, Any?>>()
while (cursor.moveToNext()) {
result.add(cursor.columnNames.mapIndexed { index, columnName ->
val columnValue = if (cursor.isNull(index)) null else cursor.getString(index)
columnName to columnValue
}.toMap())
}
if (isClose) {
cursor.close()
}
return result
}
}
Entity example:
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
#Entity(
tableName = SomeEntity.TABLE_NAME,
indices = [Index(value = [SomeEntity.SOME_UNIQUE_KEY], unique = true)]
)
data class SomeEntity(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = ID)
val id: Long,
#ColumnInfo(name = NAME)
val name: String,
#ColumnInfo(name = SOME_UNIQUE_KEY)
val someUniqueKey: String,
) {
companion object {
const val TABLE_NAME = "some_table"
const val ID = "id"
const val NAME = "name"
const val SOME_UNIQUE_KEY = "some_unique_key"
}
fun toMap(): Map<String, Any?> {
return mapOf(
ID to if (id == 0L) null else id,
NAME to name,
SOME_UNIQUE_KEY to someUniqueKey
)
}
}
#Upsert is now available in room Version 2.5.0-beta01
check out the release notes
Should be possible with this sort of statement:
INSERT INTO table_name (a, b) VALUES (1, 2) ON CONFLICT UPDATE SET a = 1, b = 2
If you have legacy code: some entities in Java and BaseDao as Interface (where you cannot add a function body) or you too lazy for replacing all implements with extends for Java-children.
Note: It works only in Kotlin code. I'm sure that you write new code in Kotlin, I'm right? :)
Finally a lazy solution is to add two Kotlin Extension functions:
fun <T> BaseDao<T>.upsert(entityItem: T) {
if (insert(entityItem) == -1L) {
update(entityItem)
}
}
fun <T> BaseDao<T>.upsert(entityItems: List<T>) {
val insertResults = insert(entityItems)
val itemsToUpdate = arrayListOf<T>()
insertResults.forEachIndexed { index, result ->
if (result == -1L) {
itemsToUpdate.add(entityItems[index])
}
}
if (itemsToUpdate.isNotEmpty()) {
update(itemsToUpdate)
}
}