My database with products (name, price) gets initialized using createFromAsset. This works for static data, however it contains a column Favorite for marking a product as favorite.
The asset I initialize the database with could look like :
Name
Price
Favorite
Product A
5,99
no
Product B
6,99
no
I want to update the database; change a product's price and add a new product. However, I want the Favorite column to keep the value set by the user. If user marked "Product B" favorite and I change its price and add a Product C, this is what the database should look like after migration:
Name
Price
Favorite
Product A
5,99
no
Product B
1,99
yes
Product C
6,99
no
How to achieve this using Android Room? The only workaround I found :
Use fallbackToDestructiveMigration.
Update asset .db file so that it includes Product C.
Update database version.
-> Old database gets deleted, user sees Product C and updated price on Product B.
#Database(
entities = arrayOf(Product::class),
version = 2,
exportSchema = true
)
fun getDatabase(context: Context, scope: CoroutineScope): ProductDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ProductDatabase ::class.java,
"product_database"
).createFromAsset("database/products.db")
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
instance
}
}
However, this resets the Favorite column. I also tried AutoMigration, but that leaves the existing database unaltered so the user doesn't see Product C and updated Product B's price.
How would I solve this? Do I need to store the favorites in a separate database?
I don't know much about room migrations, but you can save a map of ProductID -> isFavorite to SharedPreferences or local storage.
Now that I think about it, you don't even need a map. Just a list of favorite products IDs, so next time you load the app, you set up the favorites column.
However, I think you should put the favorite productIDs in a separate table.
I think there might be something about room migration rules (like there is for Realm DB), but I don't know enough of that to tell you. Good luck!
Here's an adaptation of this answer
As an overview the core addition is the applyUpdatedAssetData function.
The function is called the when the single instance of the #Database annotated class is retrieved and importantly before the Room databaseBuilder builds the database.
It first checks to see if the actual database exists, if not then it does nothing and Room will copy the Asset.
Otherwise if then checks the version of the asset against the version of the actual database. If the actual database is at a lower version then it:-
Creates a copy of the asset as an SQliteDatabase and additionally opens the actual database as an SQliteDatabase. The rows are extracted from the asset into a Cursor. The Cursor is traversed and tries to update the Name and the price (importantly not the favourite), it then tries to insert the row.
If no matching row exists then it obviously is not updated and will be inserted.
If the row is a matching row (id or name in the example) then it will be updated and not inserted.
Here's a full working example (only briefly tested, but based very much on a tested use as per the link above).
Note unlike the link the code is all in Kotlin
The Database components including the functions used by the applyUpdateAssetData function:-
const val DATABASE_NAME = "products.db"
const val ASSET_NAME = DATABASE_NAME
const val ASSET_COPY_DATABASE_NAME = "asset_copy_$DATABASE_NAME"
#Entity(
indices = [
Index("name", unique = true)
]
)
data class Product(
#PrimaryKey
var id: Long?=null,
var name: String,
var price: Double,
var favourite: Boolean
)
#Dao
interface ProductDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(product: Product): Long
#Query("SELECT * FROM Product")
fun getAllProducts(): List<Product>
#Query("UPDATE product SET favourite =NOT favourite WHERE id=:id OR name=:name")
fun toggleFavourite(id: Long, name: String)
#Query("UPDATE product SET favourite=1 WHERE id=:id OR name=:name")
fun setFavourite(id: Long, name: String)
}
#Database(entities = [Product::class], version = DATABASE_VERSION)
abstract class ProductDatabase: RoomDatabase() {
abstract fun getProductDao(): ProductDao
companion object {
private var instance: ProductDatabase?=null
fun getInstance(context: Context): ProductDatabase {
if (instance==null) {
applyUpdatedAssetData(context) /*<<<<<<<<<< */
instance=Room.databaseBuilder(context,ProductDatabase::class.java, DATABASE_NAME)
.allowMainThreadQueries()
.createFromAsset(DATABASE_NAME)
.addMigrations(Migration1to2,Migration2to3)
.build()
}
return instance as ProductDatabase
}
/* Dummy Migrations */
object Migration1to2: Migration(1,2) {
override fun migrate(database: SupportSQLiteDatabase) {
Log.d("MIGRATIONINFO","Migration Invoked FROM=${this.startVersion} TO=${this.endVersion}")
}
}
object Migration2to3: Migration(2,3) {
override fun migrate(database: SupportSQLiteDatabase) {
Log.d("MIGRATIONINFO","Migration Invoked FROM=${this.startVersion} TO=${this.endVersion}")
}
}
// etc
/**
* Apply changes (update existing rows or add new rows )
*/
#SuppressLint("Range")
fun applyUpdatedAssetData(context: Context) {
if (!doesDatabaseExist(context, DATABASE_NAME)) return
val assetVersion = getAssetVersion(context, ASSET_NAME)
val actualVersion = getDBVersion(context.getDatabasePath(DATABASE_NAME))
Log.d("VERSIONINFO","Asset Version is $assetVersion. Actual DB Version is $actualVersion Code Db Version is ${DATABASE_VERSION}")
if (actualVersion < assetVersion) {
Log.d("APPLYASSET","As the asset version is greater than the actual version then apply data from the asset.")
getCopyOfDatabaseFromAsset(context, ASSET_NAME, context.getDatabasePath(
ASSET_COPY_DATABASE_NAME).path)
val assetDb = SQLiteDatabase.openDatabase(
context.getDatabasePath(ASSET_COPY_DATABASE_NAME).path,
null,
SQLiteDatabase.OPEN_READWRITE
)
val db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).path,null,SQLiteDatabase.OPEN_READWRITE)
val assetCursor = assetDb.query("Product",null,null,null,null,null,null)
val cv = ContentValues()
db.beginTransaction()
/* Apply updates and or insert new data */
while (assetCursor.moveToNext()) {
cv.clear()
/*
First prepare to update existing data i.e. just the name and price columns,
id and favourites will be unchanged.
If row doesn't exists then nothing to update (NO ERROR)
*/
cv.put("name",assetCursor.getString(assetCursor.getColumnIndex("name")))
cv.put("price",assetCursor.getDouble(assetCursor.getColumnIndex("price")))
db.update("product",cv,"id=?", arrayOf(assetCursor.getString(assetCursor.getColumnIndex("id"))))
/*
Now get the id and favourite and try to insert
if id exists then insert will be ignored
*/
cv.put("id",assetCursor.getLong(assetCursor.getColumnIndex("id")))
cv.put("favourite",assetCursor.getInt(assetCursor.getColumnIndex("favourite")))
db.insert("product",null,cv)
}
/* Cleanup */
assetCursor.close()
db.setTransactionSuccessful()
db.endTransaction()
db.close()
assetDb.close()
deleteAssetCopy(context, ASSET_COPY_DATABASE_NAME)
}
}
/* Test to see if the database exists */
private fun doesDatabaseExist(context: Context, databaseName: String): Boolean {
return File(context.getDatabasePath(databaseName).path).exists()
}
/* Copy the asset into the databases folder */
private fun getCopyOfDatabaseFromAsset(context: Context, assetName: String, copyName: String) {
val assetFile = context.assets.open(assetName)
val copyDb = File(context.getDatabasePath(copyName).path)
if (!copyDb.parentFile!!.exists()) {
copyDb.parentFile!!.mkdirs()
} else {
if (copyDb.exists()) {
copyDb.delete()
}
}
assetFile.copyTo(FileOutputStream(copyDb),8 * 1024)
}
/* delete the copied asset */
private fun deleteAssetCopy(context: Context, copyName: String) {
if (File(context.getDatabasePath(copyName).path).exists()) {
File(context.getDatabasePath(copyName).path).delete()
}
}
/* SQLite database header values */
private val SQLITE_HEADER_DATA_LENGTH = 100 /* Size of the database header */
private val SQLITE_HEADER_USER_VERSION_LENGTH = 4 /* Size of the user_version field */
private val SQLITE_HEADER_USER_VERSION_OFFSET = 60 /* offset of the user_version field */
/* Get the SQLite user_version from the existing database */
private fun getDBVersion(f: File): Int {
var rv = -1
val buffer = ByteArray(SQLITE_HEADER_DATA_LENGTH)
val istrm: InputStream
try {
istrm = FileInputStream(f)
istrm.read(buffer, 0, buffer.size)
istrm.close()
rv = getVersionFromBuffer(buffer)
} catch (e: IOException) {
e.printStackTrace()
}
return rv
}
/* Get the SQLite user_version from the Asset database */
private fun getAssetVersion(context: Context, asset: String): Int {
var rv = -1
val buffer = ByteArray(SQLITE_HEADER_DATA_LENGTH)
val istrm: InputStream
try {
istrm = context.assets.open(asset)
istrm.read(buffer, 0, buffer.size)
istrm.close()
rv = getVersionFromBuffer(buffer)
} catch (e: IOException) {
e.printStackTrace()
}
return rv
}
/**
* Extract the SQlite user_version from the database header
*/
fun getVersionFromBuffer(buffer: ByteArray): Int {
val rv = -1
if (buffer.size == SQLITE_HEADER_DATA_LENGTH) {
val bb: ByteBuffer = ByteBuffer.wrap(
buffer,
SQLITE_HEADER_USER_VERSION_OFFSET,
SQLITE_HEADER_USER_VERSION_LENGTH
)
return bb.int
}
return rv
}
}
}
For testing then the following in MainActivity :-
const val DATABASE_VERSION = 2
lateinit var db: ProductDatabase
lateinit var dao: ProductDao
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = ProductDatabase.getInstance(this)
dao = db.getProductDao()
logAllProducts("_RUN")
if (DATABASE_VERSION == 1) {
dao.setFavourite(-99999 /* obviously not an id that exists */,"Product B")
logAllProducts("_TOG")
}
}
fun logAllProducts(tagSuffix: String) {
for (p in dao.getAllProducts()) {
Log.d(
"PRDCTINFO$tagSuffix",
"ID is ${p.id} " +
"NAME is ${p.name}" +
" PRICE is ${p.price}" +
" FAVOURITE is ${p.favourite}" +
" DBVERSION=${db.openHelper.writableDatabase.version}"
)
}
}
}
And in the assets folder :-
where the respective V1 or V2 would be used to overwrite products.db accordingly.
First Run (using products.db in asset as at version 1 i.e. productsV1.db copied to replace products.db )
D/PRDCTINFO_RUN: ID is 1 NAME is Product A PRICE is 5.99 FAVOURITE is false DBVERSION=1
D/PRDCTINFO_RUN: ID is 2 NAME is Product B PRICE is 6.99 FAVOURITE is false DBVERSION=1
D/PRDCTINFO_TOG: ID is 1 NAME is Product A PRICE is 5.99 FAVOURITE is false DBVERSION=1
D/PRDCTINFO_TOG: ID is 2 NAME is Product B PRICE is 6.99 FAVOURITE is true DBVERSION=1
Second run (App just rerun)
D/PRDCTINFO_RUN: ID is 1 NAME is Product A PRICE is 5.99 FAVOURITE is false DBVERSION=1
D/PRDCTINFO_RUN: ID is 2 NAME is Product B PRICE is 6.99 FAVOURITE is true DBVERSION=1
D/PRDCTINFO_TOG: ID is 1 NAME is Product A PRICE is 5.99 FAVOURITE is false DBVERSION=1
D/PRDCTINFO_TOG: ID is 2 NAME is Product B PRICE is 6.99 FAVOURITE is true DBVERSION=1
as can be seen B is true before and after
Third Run - increase to use updated V2 asset and DATABASE_VERSION changed to 2
2022-09-17 10:52:58.183 D/VERSIONINFO: Asset Version is 2. Actual DB Version is 1 Code Db Version is 2
2022-09-17 10:52:58.184 D/APPLYASSET: As the asset version is greater than the actual version then apply data from the asset.
2022-09-17 11:06:09.717 D/VERSIONINFO: Asset Version is 2. Actual DB Version is 1 Code Db Version is 2
2022-09-17 11:06:09.717 D/APPLYASSET: As the asset version is greater than the actual version then apply data from the asset.
2022-09-17 11:06:09.777 E/SQLiteDatabase: Error inserting favourite=0 id=1 name=Product A price=5.99
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Product.id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at ....
2022-09-17 11:06:09.778 E/SQLiteDatabase: Error inserting favourite=0 id=2 name=Product B price=1.99
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Product.id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at ....
2022-09-17 11:06:09.897 D/MIGRATIONINFO: Migration Invoked FROM=1 TO=2
2022-09-17 11:06:09.967 D/PRDCTINFO_RUN: ID is 1 NAME is Product A PRICE is 5.99 FAVOURITE is false DBVERSION=2
2022-09-17 11:06:09.968 D/PRDCTINFO_RUN: ID is 2 NAME is Product B PRICE is 1.99 FAVOURITE is true DBVERSION=2
2022-09-17 11:06:09.970 D/PRDCTINFO_RUN: ID is 3 NAME is Product C PRICE is 7.99 FAVOURITE is false DBVERSION=2
As can be seen:-
The respective versions (3 of them) have been logged as expected, and thus that the change has been detected.
That there were trapped UNIQUE constraints AS EXPECTED i.e. the inserts of the two existing rows were ignored (albeit that the trapped errors were logged)
That the dummy Migration was invoked as expected and did nothing.
That B still has true for the Favourite
The the Price for B has been changed
That the new Product C has been added
Related
I have 2 fields in the local database(For eg. Name, Password). Now I uploaded the app to the Play Store. After that, I added one field in the database which is mobile number. So now the database has 3 fields(i.e Name, Password, Mobile Number). Now, what happens if I upload this app to the Play Store? Will it affect the database of the old users? How can I update that database without affecting the old local database of the users? I'm using Room Database
The update will be rolled out, via PlayStore, to old users unless it is a different App.
You MUST update the old users otherwise the App will crash. However, you can retain their data but you must cater for the new column.
As the schema has changed (a new column) and if there isn't a migration old users will experience a crash as Room checks to see if the schema, as per the #Entity annotated class (what is expected) against the database (what is found).
The crash would be along the lines of: java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number. Expected identity hash: e843da3b4913dbc08880c558d759fe82, found: d5c32de20cfd495f9eae5463c1ec7433
hashes will differ (expected(1st) is as per the #Entity the found is as per the schema in the existing database)
What you need to do is
set the default value to a suitable value that indicates that no mobile number has been provided, and
add a migration that introduces the new column, and
increase the version number (which will invoke the migration, perform the migration and then processing continues to the check/open of the database).
if there is no Migration then a crash will ensue e.g. java.lang.IllegalStateException: A migration from 1 to 2 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.
Demo
The following is a demo that will first create the App with the database at V1 without the Mobile field/column and then will migrate the existing database when the database is upgraded to V2. The existing users will have a value that indicates no mobile.
First the Database code for both versions with the V2 code commented out (The Migration doesn't need to be commented out but would obviously not be present for V1 (just saves having to repeat code)):-
const val DATABASE_VERSION = 1 /*<<<<<<<<<< WILL CHANGE to 2 FOR V2 */
const val USER_TABLE_NAME = "user"
const val USER_NAME_COLUMN = "name"
const val USER_PASSWORD_COLUMN = "password"
#Entity(tableName = USER_TABLE_NAME)
data class User(
#PrimaryKey
#ColumnInfo(name = USER_NAME_COLUMN)
val name: String, /* Original */
#ColumnInfo(name = USER_PASSWORD_COLUMN)
val password: String /* Original */
#Dao
interface UserDAOs {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(user: User): Long
#Query("SELECT * FROM user")
fun getAllUsers(): List<User>
}
#Database(entities = [User::class], exportSchema = false, version = DATABASE_VERSION)
abstract class TheDatabase: RoomDatabase() {
abstract fun getUserDAOs(): UserDAOs
companion object {
private var instance: TheDatabase?=null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance=Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
.allowMainThreadQueries() /* for brevity of the demo */
.build()
}
return instance as TheDatabase
}
}
}
Now some activity code to load some V1 data:-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: UserDAOs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getUserDAOs()
dao.getAllUsers() /*<<<< force open the database in case no code runs (this when the version and schema checking and migration for V2 will take place ) */
if (DATABASE_VERSION == 1) {
dao.insert(User("Fred", "passwordFred")) /* Original */
dao.insert(User("Mary", "passwordMary")) /* Original */
}
/* commented out for V1 as mobile not a field in the User */
/*
if (DATABASE_VERSION == 2) {
dao.insert(User("Jane","passwordJane","1234567890"))
dao.insert(User("John","passwordJohn","0987654321"))
dao.insert(User("Pat","passwordPat"))
}
*/
}
}
When run for a fresh install (aka old user) then the database, via App Inspection:-
room_master_table is where the schema hash is stored and will be the found
as expected the two rows exist and have expected values.
Next the code is changed.
The database code becomes:-
The Database version is increased:-
const val DATABASE_VERSION = 2 /*<<<<<<<<<< WILL CHANGE to 2 FOR V2 */
2 new const vals are added:-
const val USER_MOBILE_COLUMN = "mobile" /*<<<<<<<<<< ADDED for V2 */
const val USER_MOBILE_DEFAULT_VALUE = "xxxxxxxxxx" /*<<<<<<<<<< ADDED for V2 */
The User class becomes:-
#Entity(tableName = USER_TABLE_NAME)
data class User(
#PrimaryKey
#ColumnInfo(name = USER_NAME_COLUMN)
val name: String, /* Original */
#ColumnInfo(name = USER_PASSWORD_COLUMN)
val password: String /* Original */ ,/*<<<<<<<<< ADDED comma FOR V2 */
/*<<<<<<<<<< SCHEMA CHANGES FOR V2 (see comma above) >>>>>>>>>>*/
#ColumnInfo(name = USER_MOBILE_COLUMN, defaultValue = USER_MOBILE_DEFAULT_VALUE) /*<<<<<<<<<< ADDED FOR V2 */
val mobile: String = "not provided" /*<<<<<<<<<< ADDED for V2 (default value allows mobile to not be given for V1 code in Main Activity)*/
)
The #Database annotated class TheDatabase has the migration added:-
#Database(entities = [User::class], exportSchema = false, version = DATABASE_VERSION)
abstract class TheDatabase: RoomDatabase() {
abstract fun getUserDAOs(): UserDAOs
companion object {
private var instance: TheDatabase?=null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance=Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
.allowMainThreadQueries() /* for brevity of the demo */
.addMigrations(MIGRATE_1_to_2)
.build()
}
return instance as TheDatabase
}
val MIGRATE_1_to_2: Migration = object: Migration(1,2){
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE $USER_TABLE_NAME ADD COLUMN $USER_MOBILE_COLUMN TEXT NOT NULL DEFAULT '$USER_MOBILE_DEFAULT_VALUE'")
/* So as to show Migration add a row when migrating (would not be done normally) */
val cv = ContentValues()
cv.put(USER_NAME_COLUMN,"Alice")
cv.put(USER_PASSWORD_COLUMN,"passwordAlice")
cv.put(USER_MOBILE_COLUMN,"1111111111")
db.insert(USER_TABLE_NAME,OnConflictStrategy.IGNORE,cv)
}
}
}
}
The commented out activity code is un-commented for V2:-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: UserDAOs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getUserDAOs()
dao.getAllUsers() /*<<<< force open the database in case no code runs */
if (DATABASE_VERSION == 1) {
dao.insert(User("Fred", "passwordFred")) /* Original */
dao.insert(User("Mary", "passwordMary")) /* Original */
}
/* commented out for V1 as mobile not a field in the User */
if (DATABASE_VERSION == 2) {
dao.insert(User("Jane","passwordJane","1234567890"))
dao.insert(User("John","passwordJohn","0987654321"))
dao.insert(User("Pat","passwordPat"))
}
}
}
When the App is run then App Inspection now shows:-
As can be seen:-
Fred and Mary have have the recognisable indicator that the mobile wasn't provided i.e. it is xxxxxxxxxx
Alice has been added as part of the Migration (not that this would normally be included, it is just to show that the migration was performed)
Jane and John have been added with their provided mobile numbers
Pat has been added with the default value, as per the field default value (the database default value cannot be applied as mobile is not nullable)
Final Test
The remaining proof of concept, is when a new user installs the App i.e. a fresh/new install. In this scenario , for the demo, just the three V2 users will be inserted (Jane, John and Pat):-
Obviously the inserts are reflecting what the App user may do
How can I export my Room Database to a .CSV file. I would like it to be saved to device storage. I searched everything and no answer was suitable. I hope there is a way for this.
You cannot just save a database as a CSV. However the database, if fully checkpointed, is just a file. If not fully checkpointed then it (unless write-ahead logging as been disabled) would be three files.
The database itself consists of various parts, a header (first 100 bytes of the file) and then blocks of data for the various components. Most of these dependant upon the schema (the tables), there are also system tables
sqlite_master is a table that holds the schema
if autogenerate = true is used for a integer type primary key then there is also the sqlite_sequence table
room itself has the room_master_table in which room stores a hash, this being compared against a compiled hash based upon the Room's expected schema.
To save all that data as a CSV, would be complex (and needless as you can just copy the database file(s)).
If what you want is a CSV of the app's data, then that would depend upon the tables. If you a single table then extracting the data as a CSV would be relatively simple but could be complicated if the data includes commas.
If there are multiple tables, then you would have to distinguish the data for the tables.
Again the simplest way, if just securing the data is to copy the file.
However as an example based upon :-
A database that has 3 tables (apart from the system tables)
PostDataLocal (see below for columns)
GroupDataLocal
AdminDataLocal
an existing answer has been adapted for the example
Then:-
The following in an #Dao annotated interface (namely AllDao) :-
#Query("SELECT postId||','||content FROM postDataLocal")
fun getPostDataLocalCSV(): List<String>
#Query("SELECT groupPostIdMap||','||groupId||','||groupName FROM groupDataLocal")
fun getGroupDataLocalCSV(): List<String>
#Query("SELECT adminGroupIdMap||','||userId||','||adminName||','||avatar FROM adminDataLocal")
fun getAdminDataLocalCSV(): List<String>
And the following function where dao is an AllDao instance previously instantiated :-
private fun createCSV() {
val sb = StringBuilder()
var afterFirst = false
sb.append("{POSTDATALOCAL}")
for (s in dao.getPostDataLocalCSV()) {
if(afterFirst) sb.append(",")
afterFirst = true
sb.append(s)
}
afterFirst = false
sb.append("{GROUPDATALOCAL}")
for (s in dao.getGroupDataLocalCSV()) {
if (afterFirst) sb.append(",")
afterFirst = true
sb.append(s)
}
afterFirst = false
sb.append("{ADMINDATALOCAL}")
for (s in dao.getAdminDataLocalCSV()) {
if ((afterFirst)) sb.append(",")
afterFirst = true
sb.append(s)
}
Log.d("CSV_DATA","CSV is :-\n\t$sb")
}
And then in an activity (where dao has been instantiated) the following:-
createCSV()
Then, when the database contains the following data (extracted via App Inspection) :-
PostDataLocal
GroupDataLocal
AdminDataLocal
The result written to the log (as could be written to a file rather than the log) is :-
D/CSV_DATA: CSV is :-
{POSTDATALOCAL}1,Post001,2,Post002,3,Post003{GROUPDATALOCAL}1,1,Group001 (Post001),1,2,Group002 (Post001),1,3,Group003 (Post001),2,4,Group004 (Post002),2,5,Group005 (Post002),3,6,Group006 (Post003){ADMINDATALOCAL}1,1,Admin001,admin001.gif,1,2,Admin002,admin002.gif,1,3,Admin003,admin003.gif,2,4,Admin004,admin004.gif,2,5,Admin005,admin005.gif,3,6,Admin006,admin006.gif,4,7,Admin007,admin007.gif,5,8,Admin008,admin008.gif,6,9,Admin009,admin009.gif,6,10,Admin010,admin010.gif
Note how headers have been included to distinguish between the tables
of course no consideration has been given to the inclusion of commas in the data (the above is intended to just show that in-principle you can generate a CSV representation of the data relatively easily)
Additional
Here's a more automated version in which you don't need to create the #Query annotated functions, rather it interrogates sqlite_master to extract the tables and the uses the table_info pragma to ascertain the columns, building the respective SQL.
As such it should cater for any Room database.
It also allows for the replacement of commas in the data with an indicator of a comma that could then be replaced when processing the CSV.
The supportive (secondary/invoked by the primary) function being :-
private fun getTableColumnNames(tableName: String, suppDB: SupportSQLiteDatabase): List<String> {
val rv = arrayListOf<String>()
val csr = suppDB.query("SELECT name FROM pragma_table_info('${tableName}')",null)
while (csr.moveToNext()) {
rv.add(csr.getString(0))
}
csr.close()
return rv.toList()
}
And the Primary function :-
private fun AutoCreateCSV(): String {
val replaceCommaInData = "{COMMA}" /* commas in the data will be replaced by this */
val rv = StringBuilder()
val sql = StringBuilder()
var afterFirstTable = false
var afterFirstColumn = false
var afterFirstRow = false
val suppDb = db.getOpenHelper().writableDatabase
var currentTableName: String = ""
val csr = db.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE('sqlite_%') AND name NOT LIKE('room_%') AND name NOT LIKE('android_%')", null)
while (csr.moveToNext()) {
sql.clear()
sql.append("SELECT ")
currentTableName = csr.getString(0)
if (afterFirstTable) rv.append(",")
afterFirstTable = true
afterFirstColumn = false
rv.append("{$currentTableName},")
for (columnName in getTableColumnNames(currentTableName,suppDb)) {
if (afterFirstColumn) sql.append("||','||")
afterFirstColumn = true
sql.append("replace(`$columnName`,',','$replaceCommaInData')")
}
sql.append(" FROM `${currentTableName}`")
val csr2 = db.query(sql.toString(),null)
afterFirstRow = false
while (csr2.moveToNext()) {
if (afterFirstRow) rv.append(",")
afterFirstRow = true
rv.append(csr2.getString(0))
}
csr2.close()
}
csr.close()
return rv.toString()
}
Using the same data and as the primary function returns a String the following code Log.d("CSV_DATA2",AutoCreateCSV()) results in :-
D/CSV_DATA2: {PostDataLocal},1,Post001,2,Post002,3,Post003,{GroupDataLocal},1,1,Group001 (Post001),1,2,Group002 (Post001),1,3,Group003 (Post001),2,4,Group004 (Post002),2,5,Group005 (Post002),3,6,Group006 (Post003),{AdminDataLocal},1,1,Admin001,admin001.gif,1,2,Admin002,admin002.gif,1,3,Admin003,admin003.gif,2,4,Admin004,admin004.gif,2,5,Admin005,admin005.gif,3,6,Admin006,admin006.gif,4,7,Admin007,admin007.gif,5,8,Admin008,admin008.gif,6,9,Admin009,admin009.gif,6,10,Admin010,admin010.gif
and if the data includes a comma e.g. Post001 is changed to be the value Post001, <<note the comma in the data>>
Then :-
D/CSV_DATA2: {PostDataLocal},1,Post001{COMMA} <<note the comma in the data>>,2,Post002,3 ....
this additional solution also fixes a little bug in the first where some separating commas were omitted between the header and the data.
Get all your data as a list from room and use this library
https://github.com/doyaaaaaken/kotlin-csv
It works well, here is my usage
private fun exportDatabaseToCSVFile(context: Context, list: List<AppModel>) {
val csvFile = generateFile(context, getFileName())
if (csvFile != null) {
exportDirectorsToCSVFile(csvFile, list)
} else {
//
}
}
private fun generateFile(context: Context, fileName: String): File? {
val csvFile = File(context.filesDir, fileName)
csvFile.createNewFile()
return if (csvFile.exists()) {
csvFile
} else {
null
}
}
private fun getFileName(): String = "temp.csv"
fun exportDirectorsToCSVFile(csvFile: File, list: List<AppModel>) {
csvWriter().open(csvFile, append = false) {
// Header
writeRow(listOf("row1", "row2", "row3"))
list.forEachIndexed { index, appModel ->
writeRow(listOf(getRow1, getRow2, getRow3))
}
shareCsvFile(csvFile)
}
}
private fun shareCsvFile(csvFile: File) {
// share your file, don't forget adding provider in your Manifest
}
I want to make separated room databases due to my needs which is showing the data by months. For example: I need to show the expenses of April month so I need to export a database that represent April month's expenses and use it just for this month. Is there any solution for this? Here is my database:
Expense.kt
#Entity(tableName = "expenses_table")
data class Expense (
#PrimaryKey(autoGenerate = true)
val id: Int,
val expenseDate: String,
val expenseType: String,
val expenseCost: Int
)
ExpenseDao.kt
#Dao
interface ExpenseDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addExpense(expense: Expense)
#Query("SELECT * FROM expenses_table ORDER BY id ASC")
fun readAllData(): LiveData<List<Expense>>
}
ExpenseDatabase.kt
#Database(entities = [Expense::class], version = 1, exportSchema = false)
abstract class ExpenseDatabase: RoomDatabase() {
abstract fun expenseDao(): ExpenseDao
companion object {
#Volatile
private var INSTANCE: ExpenseDatabase? = null
fun getDatabase(context: Context): ExpenseDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ExpenseDatabase::class.java,
"expense_table"
).build()
INSTANCE = instance
return instance
}
}
}
}
I want to make separated room databases due to my needs which is showing the data by months.
The need for getting data by months does not equate to the need to have separate databases. However, the following is an example that just requires a few modifications to your ExpenseDatabase class :-
#Database(entities = [Expense::class], version = 1, exportSchema = false)
abstract class ExpenseDatabase: RoomDatabase() {
abstract fun expenseDao(): ExpenseDao
companion object {
#Volatile
private var INSTANCE: ExpenseDatabase? = null
fun getDatabase(context: Context, /* ADDED >>>>>*/yearMonthPrefix: String, /* ADDED >>>>>*/ swap: Boolean = false): ExpenseDatabase {
val tempInstance = INSTANCE
if (tempInstance != null && !swap) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ExpenseDatabase::class.java,
/* CHANGED >>>>>*/ "${yearMonthPrefix}_expense_table")
.build()
INSTANCE = instance
return instance
}
}
}
}
From the information you have provided. The simplest and probably most efficient solution to your problem is to have a single database where all expenses are stored in the expenses_table and a query is used to extract the expenses for the month.
The important factor here is the expenseDate column/field and the suitability of the format of the stored data. If you use an SQLite recognised format such as YYYY-MM-DD then this format is known/understood by the SQLite Date/Time functions.
If so you could then use the following to get a list of the Expense's for the current month.
#Query("SELECT * FROM expenses_table WHERE strftime('%Y%m',expenseDate) = strftime('%Y%m','now') ORDER BY id ASC")
fun readCurrentMonthsData(): LiveData<List<Expense>>
this taking advantage of the SQLite strftime function and the now time value
The following is a variation where you pass the year and month as a string and can thus get any month's data for any year:-
#Query("SELECT * FROM expenses_table WHERE substr(expenseDate,1,7)=:datepart ORDER BY id ASC")
fun readMonthsData(datepart: String): LiveData<List<Expense>>
this uses the SQLite substr function
DEMO
Consider the following ( .allowMainTrhreadQueries added to the buildDatabase to allow demo to use the main thread) :-
Note includes the queries (demo versions that return List<Expense> as opposed to LiveData<List<Expense>> for convenience and brevity)
class MainActivity : AppCompatActivity() {
lateinit var db: ExpenseDatabase
lateinit var dao: ExpenseDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = ExpenseDatabase.getDatabase(this, "202201")
dao = db.expenseDao()
dao.addExpenseDemo(Expense(0,"2022-01-01","Type",100))
dao.addExpenseDemo(Expense(0,"2022-01-11","Type",100))
dao.addExpenseDemo(Expense(0,"2022-01-21","Type",100))
dao.addExpenseDemo(Expense(0,"2022-01-31","Type",100))
/* Swap to February Dataabase */
db = ExpenseDatabase.getDatabase(this,"202202",true)
dao = db.expenseDao()
dao.addExpenseDemo(Expense(0,"2022-02-01","Type",100))
dao.addExpenseDemo(Expense(0,"2022-02-02","Type",100))
dao.addExpenseDemo(Expense(0,"2022-02-03","Type",100))
for (e: Expense in dao.readCurrentMonthsDataDemo()) {
Log.d("EXPENSEINFO001","Expense ID is ${e.id} Date is ${e.expenseDate} etc.")
}
/* None will be located as only 2022-02 rows in database */
for (e: Expense in dao.readMonthsDataDemo("2022-01")) {
Log.d("EXPENSEINFO002","Expense ID is ${e.id} Date is ${e.expenseDate} etc.")
}
/* Swap to January Database */
db = ExpenseDatabase.getDatabase(this,"202201", true)
dao = db.expenseDao()
/* None will be located as only 2022-01 rows in database */
for (e: Expense in dao.readCurrentMonthsDataDemo()) {
Log.d("EXPENSEINFO003","Expense ID is ${e.id} Date is ${e.expenseDate} etc.")
}
for (e: Expense in dao.readMonthsDataDemo("2022-01")) {
Log.d("EXPENSEINFO004","Expense ID is ${e.id} Date is ${e.expenseDate} etc.")
}
}
}
Demo Results (included in the log) :-
D/EXPENSEINFO001: Expense ID is 1 Date is 2022-02-01 etc.
D/EXPENSEINFO001: Expense ID is 2 Date is 2022-02-02 etc.
D/EXPENSEINFO001: Expense ID is 3 Date is 2022-02-03 etc.
D/EXPENSEINFO004: Expense ID is 1 Date is 2022-01-01 etc.
D/EXPENSEINFO004: Expense ID is 2 Date is 2022-01-11 etc.
D/EXPENSEINFO004: Expense ID is 3 Date is 2022-01-21 etc.
D/EXPENSEINFO004: Expense ID is 4 Date is 2022-01-31 etc.
The databases via App Inspection :-
And via Device File Explorer :-
Note that although the actual database files are only 4k each that the data in the -wal file will be applied (not all of it but at least 12K (at least 4K per table)). So multiple database files will waste a relatively high amount of the file space per database.
swapping databases will also result additional overheads.
That would not be an ideal solution. Even if you find a solution imagine after an year you will be having 12 different databases.
I will suggest you to query the database according to your need.
I'm making an android app with Room database.
My plan is to prepopulate database with some initial data when it is installed on device,
and user can edit it and insert new row on each table.
New row id by users will start from, for example, 10000,
(the point of my question)
and later I want to add more data in the rows up to 9999.
Can I do this when users update the app?
or is there any other way?
Maybe should I try to import csv file to room database?
Thanks!!
my code to prepopulate from an app asset
Room.databaseBuilder(application, AppDatabase::class.java, DB_NAME)
.createFromAsset("database/appdatabase.db")
.build()
To make it so that the users start IF you have #PrimaryKey(autogenerate = true) then when preparing the original pre-populated data you can easily set the next userid to be used.
For example, if the Entity is :-
#Entity
data class User(
#PrimaryKey(autoGenerate = true)
val userId: Long=0,
val userName: String,
)
i.e. userid and userName are the columns and when first running you want the first App provided userid to be 10000 then you could use (as an example) the following in you SQLite Tool:-
CREATE TABLE IF NOT EXISTS `User` (`userId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userName` TEXT);
INSERT INTO User (userName) VALUES('Fred'),('Mary'),('Sarah'); /* Add Users as required */
INSERT INTO User VALUES(10000 -1,'user to be dropped'); /* SETS the next userid value to be 10000 */
DELETE FROM user WHERE userid >= 10000 - 1; /* remove the row added */
Create the table according to the Entity (SQL was copied from the generated java #AppDatabase_Impl)
Loads some users
Add a user with a userId of 9999 (10000 - 1), this causes SQLite to record 9999 in the SQLite system table sqlite_sequnce for the user table.
Remove the user that was added to set the sequence number.
The following, if used after the above, demonstrates the result of doing the above :-
/* JUST TO DEMONSTRATE WHAT THE ABOVE DOES */
/* SHOULD NOT BE RUN as the first App user is added */
SELECT * FROM sqlite_sequence;
INSERT INTO user (username) VALUES('TEST USER FOR DEMO DO NOT ADD ME WHEN PREPARING DATA');
SELECT * FROM user;
The first query :-
i.e. SQLite has stored the value 9999 in the sqlite_sequence table for the table that is named user
The second query shows what happens when the first user is added :-
To recap running 1-4 prepares the pre-populated database so that the first App added user will have a userid of 10000.
Adding new data
You really have to decide how you are going to add the new data. Do you want a csv? Do you want to provide an updated AppDatabase? with all data or with just the new data? Do you need to preserve any existing User/App input data? What about a new installs? Th specifics will very likely matter.
Here's an example of how you could manage this. This uses an updated pre-populated data and assumes that existing data input by the App user is to be kept.
An important value is the 10000 demarcation between supplied userid's and those input via the App being used. As such the User Entity that has been used is:-
#Entity
data class User(
#PrimaryKey(autoGenerate = true)
val userId: Long=0,
val userName: String,
) {
companion object {
const val USER_DEMARCATION = 10000;
}
}
Some Dao's some that may be of use, others used in the class UserDao :-
#Dao
abstract class UserDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(user: User): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(users: List<User>): LongArray
#Query("SELECT * FROM user")
abstract fun getAllUsers(): List<User>
#Query("SELECT * FROM user WHERE userid < ${User.USER_DEMARCATION}")
abstract fun getOnlySuppliedUsers(): List<User>
#Query("SELECT * FROM user WHERE userid >= ${User.USER_DEMARCATION}")
abstract fun getOnlyUserInputUsers(): List<User>
#Query("SELECT count(*) > 0 AS count FROM user WHERE userid >= ${User.USER_DEMARCATION}")
abstract fun isAnyInputUsers(): Long
#Query("SELECT max(userid) + 1 FROM user WHERE userId < ${User.USER_DEMARCATION}")
abstract fun getNextSuppliedUserid(): Long
}
The #Database class AppDatabase :-
#Database(entities = [User::class],version = AppDatabase.DATABASE_VERSION, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
abstract fun getUserDao(): UserDao
companion object {
const val DATABASE_NAME = "appdatabase.db"
const val DATABASE_VERSION: Int = 2 /*<<<<<<<<<<*/
private var instance: AppDatabase? = null
private var contextPassed: Context? = null
fun getInstance(context: Context): AppDatabase {
contextPassed = context
if (instance == null) {
instance = Room.databaseBuilder(
context,
AppDatabase::class.java,
DATABASE_NAME
)
.allowMainThreadQueries()
.addMigrations(migration1_2)
.createFromAsset(DATABASE_NAME)
.build()
}
return instance as AppDatabase
}
val migration1_2 = object: Migration(1,2) {
val assetFileName = "appdatabase.db" /* NOTE appdatabase.db not used to cater for testing */
val tempDBName = "temp_" + assetFileName
val bufferSize = 1024 * 4
#SuppressLint("Range")
override fun migrate(database: SupportSQLiteDatabase) {
val asset = contextPassed?.assets?.open(assetFileName) /* Get the asset as an InputStream */
val tempDBPath = contextPassed?.getDatabasePath(tempDBName) /* Deduce the file name to copy the database to */
val os = tempDBPath?.outputStream() /* and get an OutputStream for the new version database */
/* Copy the asset to the respective file (OutputStream) */
val buffer = ByteArray(bufferSize)
while (asset!!.read(buffer,0,bufferSize) > 0) {
os!!.write(buffer)
}
/* Flush and close the newly created database file */
os!!.flush()
os.close()
/* Close the asset inputStream */
asset.close()
/* Open the new database */
val version2db = SQLiteDatabase.openDatabase(tempDBPath.path,null,SQLiteDatabase.OPEN_READONLY)
/* Grab all of the supplied rows */
val v2csr = version2db.rawQuery("SELECT * FROM user WHERE userId < ${User.USER_DEMARCATION}",null)
/* Insert into the actual database ignoring duplicates (by userId) */
while (v2csr.moveToNext()) {
database.execSQL("INSERT OR IGNORE INTO user VALUES(${v2csr.getLong(v2csr.getColumnIndex("userId"))},'${v2csr.getString(v2csr.getColumnIndex("userName"))}')",)
}
/* close cursor and the newly created database */
v2csr.close()
version2db.close()
tempDBPath.delete() /* Delete the temporary database file */
}
}
}
testing has been done on the main thread for convenience and brevity hence .allowMainThreadQueries
As can be seen a Migration from 1 to 2 is used this:-
takes the asset appdatabase.db 2nd version (another 3 "supplied" users have been added" using :-
CREATE TABLE IF NOT EXISTS `User` (`userId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userName` TEXT NOT NULL);
INSERT INTO User (userName) VALUES('Fred'),('Mary'),('Sarah'); /* Add Users as required */
INSERT INTO User (userName) VALUES('Tom'),('Elaine'),('Jane'); /*+++++ Version 2 users +++++*/
INSERT INTO User VALUES(10000 -1,'user to be dropped'); /* SETS the next userid value to be 10000 */
DELETE FROM user WHERE userid >= 10000 - 1; /* remove the row added */```
So at first the asset appdatabase.db contains the original data (3 supplied users) and with the sequence number set to 9999.
If the App has database version 1 then this pre-populated database is copied.
Users of the App may add their own and userid's will be assigned 10000, 10001 ...
When the next version is released the asset appdatabase is changed accordingly maintaining the 9999 sequence number ignoring any App input userid's (they aren't known) and the database version is changed from 1 to 2.
The migration1_2 is invoked when the App is updated. If a new user installs the App then the database is created immediately from the asset by Room's createFromAsset.
Can I do this when users update the app? or is there any other way?
As above it can be done when the app is updated AND the database version is increased. It could be done other ways BUT detecting the changed data is what can get complicated.
Maybe should I try to import csv file to room database?
A CSV does not have the advantage of dealing with new installs and inherent version checking.
can I use migration without changing the database schema?
Yes, as the above shows.
I have a Room database in my application with one table containing received and sent messages. Inside of the table, the messages are just differentiated by the phone number, being null for the backend-server (since a server has no phone number) and the phone number of the user for the sent messages. (Entered on app installation, just as Whatsapp.)
To sync the table with the backend, I introduced a new column, containing the backend id of the messages on the server. Since the server seperates sent and received messages (due to different information contained in the tables backend), the id of a sent message and the id of a received message can be equal, only distinguishable by the corresponding phone number. (Either null or own)
So I created a unique constraint over both columns: backend_id & phone number.
#Entity(indices = [Index(value = ["backend_id", "senderNumber"], unique = true)])
data class Message(
var senderNumber: String?,
var message: String?,
var backend_id: String? = null,
var time : Date? = Date(),
var status : Status = Status.PENDING
) : ListItem(time), Serializable {
#PrimaryKey(autoGenerate = true) var id : Long? = null
}
But trying it out with some messages, I had to realize, that the database gladly accepts equal backend_ids, if the phone number is null. To make sure this was not an accident, I even wrote a UnitTest:
#RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
lateinit var db : MyDatabase
lateinit var dao : MessageDao
#Before
fun createDb() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(
context, MyDatabase::class.java).build()
dao = db.messageDao()
}
#After
#Throws(IOException::class)
fun closeDb() {
db.close()
}
#Test(expected = Exception::class)
fun check_unique_constraint_is_violated() {
// Context of the app under test.
val message = Message(senderNumber = null, backend_id = "1", time = Date(), message = "Hello")
dao.insertAll(message)
dao.insertAll(message)
val allMessages = dao.getAll()
assertTrue(allMessages.size==2)
assertTrue(allMessages[0].backend_id==allMessages[1].backend_id)
}
}
This test fails, since it doesn´t throw any exception. Debugging it shows, that the Room database also doesn´t catch the exception silently, since both messages (being the same) are being inserted successfully, resulting in 2 messages.
So my question is: How can I ensure, that the result is unique over both columns, even if one of them is null? It seems a bit weird to me, that you can pass-by uniqueness, just by inserting null for one of the columns. It worked, when I only checked the backend_id in the index, throwing exceptions, when a sent and a received message had the same id. (But I obviously don´t want that.)
In case Database and Dao have any relevance to the solution:
Database:
#Database(entities = [Message::class], version = 1)
#TypeConverters(Converters::class)
abstract class MyDatabase : RoomDatabase() {
override fun init(configuration: DatabaseConfiguration) {
super.init(configuration)
//Create and execute some trigger, limiting the entries on the latest 50
}
abstract fun messageDao() : MessageDao
companion object {
private var db: MyDatabase? = null
private fun create(context : Context) : MyDatabase {
return Room.databaseBuilder(context, MyDatabase::class.java, "dbname").build()
}
fun getDB(context : Context) : MyDatabase {
synchronized(this) {
if(db==null) {
db = create(context)
}
return db!!
}
}
}
}
MessageDao:
#Dao
interface MessageDao {
#Query("SELECT * FROM Message")
fun getAll() : List<Message>
#Insert
fun insertAll(vararg messages: Message) : List<Long>
}
In SQLite (and others that conform to SQL-92) null is considered different to any other null and hence your issue.
As such you should not be using null. You can overcome this setting the default value to a specific value that indicates a no supplied value.
For example you could use:-
#NotNull
var backend_id: String = "0000000000"
0000000000 could be any value that suits your purpose.
"" could also be used.
Altenative
An alternative approach could be to handle the null in the index such as :-
#Entity(indices = [Index(value = ["coalesce(backend_id,'00000000')", "senderNumber"], unique = true)])
HOWEVER, Room will issue an error message because it doesn't determine that the backend_id column is the column being indexed and thus issues a compilation error e.g. :-
error: coalesce(backend_id,'00000000') referenced in the index does not exists in the Entity.
Therefore you would need to add the index outside of Room's creation of tables. You could do this via the onCreate or onOpen callback. Noting that onCreate is only called once when the database is first created and that onOpen is called every time the app is run.
The safest (data wise) but slightly less efficient is to use the onOpen callback.
Here's an example that creates the index (applying it to both columns, considering that both backend_id and senderNumber columns can be null).
This being done when building the database :-
....
.addCallback(object :RoomDatabase.Callback() {
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
db.execSQL(
"CREATE UNIQUE INDEX IF NOT EXISTS message_unique_sn_beid " +
"ON message (coalesce(backend_id,''),coalesce(senderNumber,''));")
}
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
}
})
.build()
....
The index name would be message_unique_sn_beid
Results using the Alternative
Basing the Message Entity on your (but with fewer columns) and an Insert Dao of :-
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(message: Message): Long
using the following (and with the index added via the onOpen callback) the when running :-
dao.insert(Message(null,"1234567890","blah"))
dao.insert(Message(null,"0123456789","blah","0123456789"))
dao.insert(Message(null,"1234567890","blah"))
dao.insert(Message(null,"1234567890","blah",null))
dao.insert(Message(null,null,message = "blah",backend_id = "9876543210"))
dao.insert(Message(null,null,message = "blah",backend_id = "9876543210"))
1st and 2nd rows will be added, 3rd and 4th rows will be ignored due to UNIQUE conflict 5th (3rd row in table) will be added, 6th will be ignored due to UNIQUE conflict.
Using Android Studio's Database Inspector:-
1. The message table :-
2. Looking at the sqlite_master (the schema) at items starting with mess (i.e. running SQL SELECT * FROM sqlite_master WHERE name LIKE 'mess%';) :-