Search code examples
javakotlinandroid-roomdatabase-migrationsqlite-cipher

Migration from SQLCipher V1 to Room DB V2 on App Update:


I build two apps with the same package name:

  1. In the first app, I use SQLCipher using "Pass_Phrase" (Version_1 DB) for CRUD operations using Java.
  2. In the second app, I just wanted to migrate from SQLCipher to Room (Version_2 DB) and also read data from SQLCipher and put it into Room DB using Kotlin.

I completed the first app and was stuck at migration's step in the second app. Need your help. Thanks a lot!


Solution

  • For 2. you could use a Migration, this has the Room database passed to it as a SupportSQLiteDatabase

    So you could then either

    • open the original (encrypted) database and then access it as you would (have done), perhaps unloading the data into Cursors for loading into the Room version, or
    • ATTACH the original database to the Room database (via the SupportSQLiteDatabase's execSQL method), and then copy the data using SQL and finally DETACH the original database.

    When a database is attached, then it's components, such as tables, are available (you should use the given schema_name to distinguish components with the same name). See ATTACH

    • Note the ATTACH SQL would be along the lines of ATTACH 'the_path_to_the_database' AS 'the_schema_name_to_use' KEY 'the_key'
      • the_path_to_the_database being the path to the database to be attached
      • the_schema_name_to_use can be an arbitrary value with some limitations (not main or temp).
      • the_key being the secret key

    The answer here includes an example that uses the first method (as per the MainDatabase class, albeit in Java (which should take little effort to convert to Kotlin))