Skip to content
Snippets Groups Projects
Commit e1065db1 authored by Adrien Béraud's avatar Adrien Béraud
Browse files

sqlite: check database creation, use try-with-ressources

Change-Id: I91173e90c5981af3d1ada070b7fd051a3dd4a2ed
parent 4329a7dc
No related branches found
No related tags found
No related merge requests found
...@@ -200,8 +200,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { ...@@ -200,8 +200,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
db.execSQL("CREATE INDEX IF NOT EXISTS `historytext_TIMESTAMP_idx` ON `historytext` ( `TIMESTAMP` );"); db.execSQL("CREATE INDEX IF NOT EXISTS `historytext_TIMESTAMP_idx` ON `historytext` ( `TIMESTAMP` );");
db.execSQL("CREATE INDEX IF NOT EXISTS `historytext_id_idx` ON `historytext` ( `id` );"); db.execSQL("CREATE INDEX IF NOT EXISTS `historytext_id_idx` ON `historytext` ( `id` );");
Cursor hasATable = db.rawQuery("SELECT name FROM sqlite_master WHERE type=? AND name=?;", try (Cursor hasATable = db.rawQuery("SELECT name FROM sqlite_master WHERE type=? AND name=?;",
new String[]{"table", "a"}); new String[]{"table", "a"})) {
if (hasATable.getCount() > 0) { if (hasATable.getCount() > 0) {
//~ Copying data from the old table "a" //~ Copying data from the old table "a"
db.execSQL("INSERT INTO `historycall` (TIMESTAMP_START, call_end, number, missed," + db.execSQL("INSERT INTO `historycall` (TIMESTAMP_START, call_end, number, missed," +
...@@ -210,10 +210,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { ...@@ -210,10 +210,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
db.execSQL("DROP TABLE IF EXISTS a_TIMESTAMP_START_idx;"); db.execSQL("DROP TABLE IF EXISTS a_TIMESTAMP_START_idx;");
db.execSQL("DROP TABLE a;"); db.execSQL("DROP TABLE a;");
} }
hasATable.close(); }
Cursor hasETable = db.rawQuery("SELECT name FROM sqlite_master WHERE type=? AND name=?;", try (Cursor hasETable = db.rawQuery("SELECT name FROM sqlite_master WHERE type=? AND name=?;",
new String[]{"table", "e"}); new String[]{"table", "e"})) {
if (hasETable.getCount() > 0) { if (hasETable.getCount() > 0) {
//~ Copying data from the old table "e" //~ Copying data from the old table "e"
db.execSQL("INSERT INTO historytext (id, TIMESTAMP, number, direction, accountID," + db.execSQL("INSERT INTO historytext (id, TIMESTAMP, number, direction, accountID," +
...@@ -224,7 +224,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { ...@@ -224,7 +224,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
db.execSQL("DROP TABLE IF EXISTS e_id_idx;"); db.execSQL("DROP TABLE IF EXISTS e_id_idx;");
db.execSQL("DROP TABLE e;"); db.execSQL("DROP TABLE e;");
} }
hasETable.close(); }
db.setTransactionSuccessful(); db.setTransactionSuccessful();
db.endTransaction(); db.endTransaction();
...@@ -414,14 +414,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { ...@@ -414,14 +414,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (db != null && db.isOpen()) { if (db != null && db.isOpen()) {
Log.d(TAG, "clearDatabase: Will clear database."); Log.d(TAG, "clearDatabase: Will clear database.");
ArrayList<String> tableNames = new ArrayList<>(); ArrayList<String> tableNames = new ArrayList<>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) { try (Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null)) {
while (!c.isAfterLast()) { tableNames.ensureCapacity(c.getCount());
while (c.moveToNext())
tableNames.add(c.getString(0)); tableNames.add(c.getString(0));
c.moveToNext();
}
} }
c.close();
try { try {
db.beginTransaction(); db.beginTransaction();
......
...@@ -49,15 +49,15 @@ import io.reactivex.subjects.Subject; ...@@ -49,15 +49,15 @@ import io.reactivex.subjects.Subject;
*/ */
public class HistoryServiceImpl extends HistoryService { public class HistoryServiceImpl extends HistoryService {
private static final String TAG = HistoryServiceImpl.class.getSimpleName(); private static final String TAG = HistoryServiceImpl.class.getSimpleName();
@Inject
protected Context mContext;
private ConcurrentHashMap<String, DatabaseHelper> databaseHelpers = new ConcurrentHashMap<>();
private final static String DATABASE_NAME = "history.db"; private final static String DATABASE_NAME = "history.db";
private final static String LEGACY_DATABASE_KEY = "legacy"; private final static String LEGACY_DATABASE_KEY = "legacy";
private static boolean migrationInitialized = false; private static boolean migrationInitialized = false;
private Subject<MigrationStatus> migrationStatusSubject = BehaviorSubject.create();
private final ConcurrentHashMap<String, DatabaseHelper> databaseHelpers = new ConcurrentHashMap<>();
private final Subject<MigrationStatus> migrationStatusSubject = BehaviorSubject.create();
@Inject
protected Context mContext;
public HistoryServiceImpl() { public HistoryServiceImpl() {
} }
...@@ -76,7 +76,7 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -76,7 +76,7 @@ public class HistoryServiceImpl extends HistoryService {
try { try {
return getHelper(dbName).getInteractionDataDao(); return getHelper(dbName).getInteractionDataDao();
} catch (SQLException e) { } catch (SQLException e) {
cx.ring.utils.Log.e(TAG, "Unable to get a interactionDataDao"); Log.e(TAG, "Unable to get a interactionDataDao");
return null; return null;
} }
} }
...@@ -86,7 +86,7 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -86,7 +86,7 @@ public class HistoryServiceImpl extends HistoryService {
try { try {
return getHelper(dbName).getConversationDataDao(); return getHelper(dbName).getConversationDataDao();
} catch (SQLException e) { } catch (SQLException e) {
cx.ring.utils.Log.e(TAG, "Unable to get a conversationDataDao"); Log.e(TAG, "Unable to get a conversationDataDao");
return null; return null;
} }
} }
...@@ -99,8 +99,7 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -99,8 +99,7 @@ public class HistoryServiceImpl extends HistoryService {
* @return the database helper * @return the database helper
*/ */
private DatabaseHelper initHelper(String accountId) { private DatabaseHelper initHelper(String accountId) {
File dbPath = new File(mContext.getFilesDir(), accountId); File db = new File(new File(mContext.getFilesDir(), accountId), DATABASE_NAME);
File db = new File(dbPath, DATABASE_NAME);
DatabaseHelper helper = new DatabaseHelper(mContext, db.getAbsolutePath()); DatabaseHelper helper = new DatabaseHelper(mContext, db.getAbsolutePath());
databaseHelpers.put(accountId, helper); databaseHelpers.put(accountId, helper);
return helper; return helper;
...@@ -120,7 +119,6 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -120,7 +119,6 @@ public class HistoryServiceImpl extends HistoryService {
return initLegacyDb(); return initLegacyDb();
} }
if (databaseHelpers.containsKey(accountId)) if (databaseHelpers.containsKey(accountId))
return databaseHelpers.get(accountId); return databaseHelpers.get(accountId);
else else
...@@ -135,7 +133,11 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -135,7 +133,11 @@ public class HistoryServiceImpl extends HistoryService {
* @return true if history.db exists in the database folder * @return true if history.db exists in the database folder
*/ */
private Boolean checkForLegacyDb() { private Boolean checkForLegacyDb() {
try {
return mContext.getDatabasePath(DATABASE_NAME).exists(); return mContext.getDatabasePath(DATABASE_NAME).exists();
} catch (Exception e) {
return false;
}
} }
/** /**
...@@ -204,7 +206,6 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -204,7 +206,6 @@ public class HistoryServiceImpl extends HistoryService {
*/ */
@Override @Override
protected void migrateDatabase(List<String> accounts) { protected void migrateDatabase(List<String> accounts) {
if (!checkForLegacyDb()) { if (!checkForLegacyDb()) {
migrationStatusSubject.onNext(MigrationStatus.LEGACY_DELETED); migrationStatusSubject.onNext(MigrationStatus.LEGACY_DELETED);
return; return;
...@@ -217,9 +218,7 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -217,9 +218,7 @@ public class HistoryServiceImpl extends HistoryService {
Log.i(TAG, "Initializing database migration..."); Log.i(TAG, "Initializing database migration...");
SQLiteDatabase db = mContext.openOrCreateDatabase(mContext.getDatabasePath(DATABASE_NAME).getAbsolutePath(), Context.MODE_PRIVATE, null); try (SQLiteDatabase db = mContext.openOrCreateDatabase(mContext.getDatabasePath(DATABASE_NAME).getAbsolutePath(), Context.MODE_PRIVATE, null)) {
try {
if (accounts == null || accounts.isEmpty()) { if (accounts == null || accounts.isEmpty()) {
Log.i(TAG, "No existing accounts found in directory, aborting migration..."); Log.i(TAG, "No existing accounts found in directory, aborting migration...");
...@@ -227,7 +226,6 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -227,7 +226,6 @@ public class HistoryServiceImpl extends HistoryService {
return; return;
} }
// create new database for each account // create new database for each account
for (String newDb : accounts) { for (String newDb : accounts) {
...@@ -275,12 +273,10 @@ public class HistoryServiceImpl extends HistoryService { ...@@ -275,12 +273,10 @@ public class HistoryServiceImpl extends HistoryService {
Log.i(TAG, "Migration complete. Each account now has its own database"); Log.i(TAG, "Migration complete. Each account now has its own database");
} catch (SQLiteException e) { } catch (SQLiteException e) {
db.close();
migrationStatusSubject.onNext(MigrationStatus.FAILED); migrationStatusSubject.onNext(MigrationStatus.FAILED);
migrationInitialized = false; migrationInitialized = false;
Log.e(TAG, "Error migrating database.", e); Log.e(TAG, "Error migrating database.", e);
} catch (NullPointerException e) { } catch (NullPointerException e) {
db.close();
migrationStatusSubject.onNext(MigrationStatus.FAILED); migrationStatusSubject.onNext(MigrationStatus.FAILED);
migrationInitialized = false; migrationInitialized = false;
Log.e(TAG, "An unexpected error occurred. The migration will run again when the helper is called again", e); Log.e(TAG, "An unexpected error occurred. The migration will run again when the helper is called again", e);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment