首页 > 解决方案 > 备份时的Android 9数据库日志模式WAL问题

问题描述

我的应用程序中有一些备份/恢复功能,在使用 >= Android 9 时会导致问题,SQLite 数据库确实使用 journal_mode WAL 而不是他们在旧手机上使用的 DELETE。我的 SQLLite 版本是 3.25.2

更多信息:

我正在使用完全集成到我的项目中的 Sugar ORM。Sugar ORM 使用自己的类,例如,扩展 SQLiteOpenHelper 的 SugarDb,并且该类是只读的。

问题:

  1. 如何以及在哪里检查 *.db 文件的 journal_mode 是否为 WAL?
  2. SQLite journal_mode 为 WAL 时如何正确复制/恢复 *.db 文件?
  3. 对于所有手持设备,如何以及在何处将 SQLite journal_mode 从 WAL 切换到 DELETE?

标签: androidsqlitedatabase-backupssqlite-journal-mode

解决方案


Some good background reading https://sqlite.org/wal.html

Answer to 3. Use https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#disableWriteAheadLogging() in the onConfigure of SQLiteOpenHelper (or in your case you probably have to extend and override the SugarDb class to do that.

You will probably have to extend getInstance as well to return your an instance of your own class (and not call super I think in that override), then where you call SugarDb.getInstance() you call getInstance on your extended class.

Answer to 2. As @CommonsWare says if your DB is closed correctly then all data is commited to the DB file from the Wal file on close.

Update: Looking at https://github.com/chennaione/sugar/blob/master/library/src/main/java/com/orm/SugarDb.java

For every time you have called SugarDb.getReadableDatabase() or SugarDb.getWritableDatabase()you should call SugarDb.close()

The easiest way to do that is as soon as you have finished the current database operations as you cannot query it's connection count, or you could maintain your own count and close at various times in the apps lifecycle like onPause or onDestroy or before your try to backup

Answer to 1. https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#isWriteAheadLoggingEnabled()


推荐阅读