Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backup Room database

I'm trying to backup a room database programmatically.

For that, I'm simply copying the .sqlite file that contains the whole database

But, before copying, due to the fact that room has write ahead logging enabled, we must close the database so that -shm file and -wal file merge into a single .sqlite file. As pointed out here

I run .close() on RoomDatabase object:

Everything works fine with the backup, BUT, later on, when I try to execute an INSERT query, I get this error:

android.database.sqlite.SQLiteException: no such table: room_table_modification_log (code 1) 

How can I properly re-open room db after I close it?

PS: .isOpen() on RoomDatabase object returns true before INSERT

Room version: 1.1.1-rc1

like image 917
Alex Busuioc Avatar asked Jun 22 '18 11:06

Alex Busuioc


People also ask

What are room databases?

Room Database is a part of the Android Architecture components which provides an abstraction layer over SQLite which allows for more robust database access while still providing the full power of SQLite.

How does room database work?

Room autogenerates implementations of your @Database and @Dao annotated classes the first time you compile your code after creating a Room Database. The implementation of UserDatabase and UserDao in the preceding example is generated automatically by the Room annotation processor.


1 Answers

How can I properly re-open room db after I close it?

I am sorry that this doesn't answer that question.

But if moving everything to the original database file is what you want to do, then you don't have to close the database in the first place. You can instead force a checkpoint using the wal_checkpoint pragma.

Query the following statement against the database. We use raw queries here as pragma is not yet supported by Room (it will trigger a UNKNOWN query type error). Have this query inside of your DAO:

@RawQuery int checkpoint(SupportSQLiteQuery supportSQLiteQuery); 

And then when you call the checkpoint method, use the query then:

myDAO.checkpoint(new SimpleSQLiteQuery("pragma wal_checkpoint(full)")); 

This link may shed some light on what wal_checkpoint does.

like image 108
Bertram Gilfoyle Avatar answered Sep 20 '22 13:09

Bertram Gilfoyle