Skip to content

Instantly share code, notes, and snippets.

@NamtarR
Created March 22, 2019 12:57
Show Gist options
  • Save NamtarR/d5f08db5c94afd75718f2140b3320797 to your computer and use it in GitHub Desktop.
Save NamtarR/d5f08db5c94afd75718f2140b3320797 to your computer and use it in GitHub Desktop.
Android Room SQLite UPSERT without using actual https://www.sqlite.org/lang_UPSERT.html
package com.namtarr.upsert
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
class User(
@PrimaryKey
val id: Long,
val name: String
)
package com.namtarr.upsert
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Transaction
import androidx.room.Update
@Dao
abstract class UserDao {
@Transaction
open fun upsertUser(user: User) {
if (insertUser(user) == -1L) {
updateUser(user)
}
}
@Transaction
open fun upsertUsers(users: List<User>) {
val inserted = insertUsers(users).filter { it != -1L }
val usersToUpdate = users.filter { !inserted.contains(it.id) }
updateUsers(usersToUpdate)
}
@Update(onConflict = OnConflictStrategy.REPLACE)
protected abstract fun updateUser(user: User)
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract fun insertUser(user: User): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
protected abstract fun updateUsers(users: Collection<User>)
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract fun insertUsers(users: Collection<User>): List<Long>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment