LoginSignup
2
0

More than 3 years have passed since last update.

【Android】SQLCipher3からSQLCipher4へのマイグレーション方法

Last updated at Posted at 2019-09-06

今日、仕事でAndroidのSQLCipher3からSQLCipher4へのアップデートを行いました。
今回アップデートするにあたって日本語のサイトが少なかったので書いておきます。

公式サイトに書いてある通り、今回はメジャーアップデートで以前のバージョンのものを使う際はマイグレーション処理をしないといけないらしい。

記録として軽く書いておきます、今回はこちらのサイトを参考にしました。
こちらのサイトには下記のコードを実装してもうまくいかないとのことでした。


public class DatabaseMigrator {

    static public void checkAndMigrateDatabase(Context context, String databaseName, String password) {

        String path = context.getDatabasePath(databaseName).getPath();

        SQLiteDatabaseHook hook = new SQLiteDatabaseHook() {
            @Override
            public void postKey(SQLiteDatabase database) {

                Cursor c = database.rawQuery("PRAGMA cipher_migrate", null);

                Boolean migrationOccurred = false;

                if (c.getCount() == 1) {
                    c.moveToFirst();
                    String selection = c.getString(0);

                    migrationOccurred = selection.equals("0");

                    print("selection: " + selection);
                }

                c.close();

                print("migrationOccurred: " + migrationOccurred);
            }

            @Override
            public void preKey(SQLiteDatabase database) { }
        };

        SQLiteDatabase database = null;

        try {
            database = SQLiteDatabase.openDatabase(path, password, null, 0, hook);
        }
        catch (Exception e) {
            print("Exception while trying to open db: " + e);
        }

        if (database != null) {

            database.close();
        }
    }
}

実際に質問者と同じコードを試した結果、下記のエラーが出ました。(質問者の事象とは異なります。)

10920-10920/sample.sqlciphermigrationsample E/SQLiteOpenHelper: Couldn't open test_database.db for writing (will try read-only):
    net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;


色々調べた結果、下記のコードを


database = SQLiteDatabase.openDatabase(path, password, null, 0, hook);

下記のコードに変更したら動きました!


database = SQLiteDatabase.openOrCreateDatabase(path, password, null, hook);

実際に試したコード全体は後ほどgithubにあげています🙃。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0