Skip to content

Commit

Permalink
Merge pull request #1248 from wordpress-mobile/fix_crash_in_account_s…
Browse files Browse the repository at this point in the history
…ql_utils

Add transaction to prevent other threads to overriding current account
  • Loading branch information
aforcier authored Jun 6, 2019
2 parents 3a44520 + 453607d commit 6f0a73b
Showing 1 changed file with 23 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.wordpress.android.fluxc.persistence;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import androidx.annotation.NonNull;

Expand All @@ -25,18 +26,29 @@ public static int insertOrUpdateDefaultAccount(AccountModel account) {
}

public static int insertOrUpdateAccount(AccountModel account, int localId) {
if (account == null) return 0;
account.setId(localId);
List<AccountModel> accountResults = WellSql.select(AccountModel.class)
.where()
.equals(AccountModelTable.ID, localId)
.endWhere().getAsModel();
if (accountResults.isEmpty()) {
WellSql.insert(account).execute();
if (account == null) {
return 0;
} else {
ContentValues cv = new UpdateAllExceptId<>(AccountModel.class).toCv(account);
return updateAccount(accountResults.get(0).getId(), cv);
}
account.setId(localId);
SQLiteDatabase db = WellSql.giveMeWritableDb();
db.beginTransaction();
try {
List<AccountModel> accountResults = WellSql.select(AccountModel.class)
.where()
.equals(AccountModelTable.ID, localId)
.endWhere().getAsModel();
if (accountResults.isEmpty()) {
WellSql.insert(account).execute();
db.setTransactionSuccessful();
return 0;
} else {
ContentValues cv = new UpdateAllExceptId<>(AccountModel.class).toCv(account);
int result = updateAccount(accountResults.get(0).getId(), cv);
db.setTransactionSuccessful();
return result;
}
} finally {
db.endTransaction();
}
}

Expand Down

0 comments on commit 6f0a73b

Please sign in to comment.