Android Room persistance library. Drop Table - android

I need to know how to "DROP FROM Table" using Room Persistence Library.
I already know that we can delete all the rows using the method:
#Query("DELETE FROM table")
void deleteAll();
However, what I need is deleting the whole table. This is because of my primary_key is an autoincrement column, so using the previous code, it is not rested.
I already read answers about this topic in the next links:
Reset auto-increment in Android's Room library
Android Room - reset auto generated key on each app run
However, I can't believe that this library doesn't provide an easier way to do this, regardless of the reason or use.

Could use Migrations that Room provides for updating the database via our own queries. As we want to make changes to the database which Room cannot resolve (yet) from the code. We could delete the table, recreate it or update it. Depending on what is needed.
Option 1: Migrate with keeping other data
First increase the version of the database: update the version parameter in the #Database annotation.
Create a migration like this:
static final Migration MIGRATION_1_2 = new Migration(1, 2) { // From version 1 to version 2
#Override
public void migrate(SupportSQLiteDatabase database) {
// Remove the table
database.execSQL("DROP TABLE my_table"); // Use the right table name
// OR: We could update it, by using an ALTER query
// OR: If needed, we can create the table again with the required settings
// database.execSQL("CREATE TABLE IF NOT EXISTS my_table (id INTEGER, PRIMARY KEY(id), ...)")
}
};
Add the migration when building the database:
Room.databaseBuilder(context, MyDatabase.class, "mydatabase")
.addMigration(MIGRATION_1_2) // Add the migration
.build();
Run the app again. If the queries were correct, the migration is done
Option 2: Migrate with losing data
There is also a fast option, but all data in the database will be cleared!
This is because the database gets recreated when using the method below.
Like option one, increment the version of the database
Use .fallbackToDestructiveMigration() when creating the database, like so:
Room.databaseBuilder(context, MyDatabase.class, "mydatabase")
.fallbackToDestructiveMigration()
.build();
Run the app. It will remove the old database and recreate it. (All earlier data is wiped)

If you want to do this with auto migration then need to use spec as autoMigrations value for #Database annotation. Look like
this
autoMigrations = {#AutoMigration(from = 1, to = 2, spec = AppDatabase.MyAutoMigration.class)}
Example like you want to delete a table(YourTableName) from database version 1 and then migrate to version 2 then the full code looks like this
#Database(
version = 2,
entities = {Entity1.class, Entity2.class},
autoMigrations = {#AutoMigration(from = 1, to = 2, spec = AppDatabase.MyAutoMigration.class)},
exportSchema = true)
#TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
#DeleteTable.Entries(value = #DeleteTable(tableName = "YourTableName"))
public static class MyAutoMigration implements AutoMigrationSpec {
}
// Your DAO 1
// Your DAO 2
}

Related

createFromAsset and fallbackToDestructiveMigration methods of Room library - no data exists

I have a .db file in assets folder. My RoomDatabase class is as the following. I install the app to my device. Then I changed version = 2 in the below class, and make my prepopulated database version 2. Then i renamed one of the columns in my table so that schema is changed. Then i installed the app again. And boom! Room gives me the following error :
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.
#Database(entities = [Word::class], version = 1, exportSchema = false)
abstract class WordRoomDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao
companion object {
#Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(context: Context): WordRoomDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(ctx: Context): WordRoomDatabase {
val passphrase: ByteArray = SQLiteDatabase.getBytes("my password".toCharArray())
val factory = SupportFactory(passphrase)
return Room.databaseBuilder(ctx.applicationContext, WordRoomDatabase::class.java, "word_database2.db")
.openHelperFactory(factory)
.createFromAsset("word_database.db")
.fallbackToDestructiveMigration()
.build()
}
}
}
After this point, I completely deleted my app. Make the prepopulated database version and #Database version 1. I made allowBackup false in AndroidManifest.xml. So there is no database exist in my device. But I am still facing the same error when I install the app to device. What a nonsense error is this. How can I solve it ?
I faced the same issue in the near past. I'm quoting from http://www.sqlite.org/lang_altertable.html
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a colum, remove a column, or add or remove constraints from a table.
Alternatively, you can create a new table and fill the new table with data of old table.
One last and the most important point I want to say about is that if you want to change the schema of .db file exist in assets folder, then you should do that with sqlite command line. When I try to change schema by using sqlite db browser, it does not work like you said. There is a problem in sqlite db browser for changing schema.
So , if you want to change schema, do it in sqlite command line.
Increase .pragma version in both code and .db(You can increase .pragma using db browser for sqlite).
For adding removing adding data without changing schema purposes, you can safely continue to work with sqlite db browser.

Room Database schema update without data loss

I have developed one application in Android using Kotlin and it is available on playstore. I have used Room database to store the values. I have following queries:
Database schema is changed now, How to I need to handle that. I referred to below tutorial but still not clear to handle the schema change in Migration.
Visit https://developer.android.com/training/data-storage/room/migrating-db-versions.html
How can I test my current application with playstore version?
Thanks for the help in advance.
That's quite a complex question but basically you have 2 strategies:
fallbackToDestructiveMigration -> simple to implement but your users will lose their data once the app is updated
Provide a Migrationstrategy (preferable)
Case 1 - fallbackToDestructiveMigration
In your database initialization, simply invoke fallbackToDestructiveMigration on your database builder:
database = Room.databaseBuilder(context.getApplicationContext(),
UsersDatabase.class, "Sample.db")
.fallbackToDestructiveMigration()
.build();
In this case, since you have updated your database version (suppose from version 1 to version 2) Room can't find any migration strategy, so it will fallback to distructive migration, tables are dropped.
Case 2 - Smart migration
Suppose you have a table called "Users" and suppose you added a column to this table in version 2 of your database. Let's call this column "user_score" You should implement migrate interface of Migration class in order to update your "Users version 1" schema to "Users version 2" schema. To do so, you need an alter table, you can write it directly inside the migrate method:
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// Your migration strategy here
database.execSQL("ALTER TABLE Users ADD COLUMN user_score INTEGER")
}
};
database = Room.databaseBuilder(context.getApplicationContext(),
UsersDatabase.class, "Sample.db")
.addMigrations(MIGRATION_1_2)
.build();
More references here :
https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929
https://medium.com/#elye.project/android-sqlite-database-migration-b9ad47811d34
From room version 2.4.0, you can easily update using autoMigrations.
DATABASE CLASS
#Database(
version = 3,
autoMigrations = [
AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3)
],
.....
)
DATA CLASS
#Entity(tableName = "user")
data class DataUser(
....
// I added this column, like this
#ColumnInfo(defaultValue = "")var test: String = ""
)
see reference below
android developer: room version2.4.0
android developer: autoMigration
For your question 2, you can do the following things:
Download and install apk file in mobile device from playstore.
Build your apk file(signed apk). Before generating the apk file
don't forget to increase version code.
install the signed apk file in device by following below adb command
adb install -r "apk_file_path"
Hope this will work.
You should use a VCS (like git). For each version of your app you should create a tag, so you can easily switch between published versions to test compatibility.
The migration itself can be done by invoking raw queries on the room database in your migration. If you don't know how to write those, you should first read some tutorials about SQL.

Adding column in room db

I have been going through Room DB introduced in new architecture components in Android and thinking about migrating my current DBs to Room DBs.
But my current db implementation allows me to add columns to the table but as per Room, fields in POJO class represents the columns of table.
It is possible to add columns in Room DB using raw query, if yes, how shall I implement it.
I know this is an old post, but this might help someone out there that needs help with this.
Do you want to add said column on an upgrade of a DB or would you like to do it on first creation of the table?
If you want to do it on an upgrade of the DB then you can look at
Migrating Room databases
Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
.addMigrations(MIGRATION_1_2, MIGRATION_2_3).build();
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, `name` TEXT, PRIMARY KEY(`id`))");
}
};
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE Book ADD COLUMN pub_year INTEGER");
}
};
If you want to add the column on the fly you will have to get the instance of your DB then can try call the following:
getDatabaseInstance().query()
There is little point for using Room with this table. After all, you cannot dynamically modify any entities or DAO methods, and so Room will not know anything about these changed columns.
If the rest of your database is Room-friendly, and you just have this one weird table, you can call getOpenHelper() on your RoomDatabase to get the SupportSQLiteOpenHelper, then work from there. The SupportSQLite... classes resemble the native Android SQLite API.

How do I completely recreate my database in Android Room?

I have a situation where I want to be able to do a hard reset of my database using Android Room. Using SQLiteOpenHelper, I could do this by writing a method to drop all tables and indices, then manually call SQLiteOpenHelper.onCreate().
I'm aware that I can get access to a SupportSQLiteOpenHelper via room and drop all the tables myself, but there doesn't seem to be a good way to kick-off the recreation process.
Also, I'm aware that I could delete every item from each table without dropping it, but that's not what I want. That doesn't reset the auto-incrementing primary key, so the "id" field of new items won't reset back to 1.
Thanks!
EDIT:
This is something I want to be able to do arbitrarily at runtime.
EDIT 2:
The method should be maintainable, i.e. not involve hand-writing SQL that matches Room's behavior. Ideally there would be some way to retrieve the SQL that Room generates, or a SQLiteOpenHelper.onCreate() equivalent method. Or anything else that solves this problem! :)
I found it easiest to do this via context.deleteDatabase(“name”) and then simply reinstantiating and repopulating the database via the Room.databaseBuilder().addCallback upon first access.
Simple answer is to increment your #Database version number. Generally speaking you should do this for schema changes, however it will achieve your aims of clearing the database and resetting all primary key values.
#Database(entities = { Hello.class }}, version = 1) // <- you want to increase version by 1
#TypeConverters({})
public abstract class AppDatabase extends RoomDatabase {
public abstract HelloDao helloTextDao();
}
EDIT: IF you want to do this at run time, I would clear all the data from your tables (to avoid FK issues), then call DROP TABLE table_name, on all of your respective tables. Then you will need to write queries for creating the tables ie : CREATE TABLE table_name (uid INTEGER PRIMARY KEY, name STRING);.
This will mean you have to maintain a list of create table queries up to date with your POJO's unfortunatly. Ideally you'd be able to use reflection to generate the query, howerever #ColumnInfo currently doesn't support reflection as it has its RetentionPolicy set to CLASS.
Hopefully this solves your problem, feel free to ask for further clarification in the comments. Happy hunting!
For my case, deleting database with context.deleteDatabase(“name”) still caches the data of the old database.
I solved this by manually deleting the database file
File databasesDir = new File(context.getApplicationInfo().dataDir + "/databases");
new File(databasesDir, "MyDatabaseName.db").delete();
I was not able to find a way to do this programatically.
But, you can go to yourApp -> Long click -> App Info -> Storage & Cache -> clear both cache and Storage.
Clearing storage displays a verification dialog that indicates that databases will be destroyed.
This may help you.
upgrade your Database version
When you call DatabaseBuilder, remember add this to your code fallbackToDestructiveMigration
Room.databaseBuilder(context, Database::class.java, DB_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
More detail please refer this
As per the answers given here, and here, and here, I could do it as following:
public void deleteAndReset() {
SQLiteDatabase database;
database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(MY_DATABASE_NAME), null);
String deleteTable = "DELETE FROM " + MY_TABLE_NAME;
database.execSQL(deleteTable);
String deleteSqliteSequence = "DELETE FROM sqlite_sequence WHERE name = '" + MY_TABLE_NAME + "'";
database.execSQL(deleteSqliteSequence);
}

How to migrate existing SQLite application to Room Persistance Library?

It might be a bit early to ask, but is it possible and how to migrate/upgrade an existing SQLite database application to a new Android Room Persistance Library?
Assuming your room entities match your current table schemas, you can keep using the same database/tables.
Room manages a master table which is initialized on creation or upgrade of the database, so you need to increment your database version and provide a dummy migration:
#Database(entities = SomeEntity.class, version = EXISTING_VERSION + 1)
public class MyDatabase extends RoomDatabase {
// ...
}
MyDatabase db = Room.databaseBuilder(context, MyDatabase.class, "db_name")
.addMigrations(new Migration(EXISTING_VERSION, EXISTING_VERSION + 1) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// NOOP
}
}).build();
For those who are wondering if there is any way to migrate from SQLite to Room even if your schema does not match, the answer is YES, you can migrate from SQLite to room even if the schema does not match.
It is possible, but a requires quite careful conversions. As the process requires so many steps to cover, I will just leave references you can follow.
Incrementally migrate from SQLite to Room
Hope it will be helpful for a few.

Categories

Resources