Wed, 31 Dec 2014 07:22:50 +0100
Correct previous dual key logic pending first delivery installment.
michael@0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public |
michael@0 | 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
michael@0 | 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
michael@0 | 4 | |
michael@0 | 5 | package org.mozilla.gecko.db; |
michael@0 | 6 | |
michael@0 | 7 | import android.content.ContentProvider; |
michael@0 | 8 | import android.content.ContentValues; |
michael@0 | 9 | import android.database.Cursor; |
michael@0 | 10 | import android.database.SQLException; |
michael@0 | 11 | import android.database.sqlite.SQLiteDatabase; |
michael@0 | 12 | import android.net.Uri; |
michael@0 | 13 | import android.os.Build; |
michael@0 | 14 | import android.text.TextUtils; |
michael@0 | 15 | import android.util.Log; |
michael@0 | 16 | |
michael@0 | 17 | /** |
michael@0 | 18 | * This abstract class exists to capture some of the transaction-handling |
michael@0 | 19 | * commonalities in Fennec's DB layer. |
michael@0 | 20 | * |
michael@0 | 21 | * In particular, this abstracts DB access, batching, and a particular |
michael@0 | 22 | * transaction approach. |
michael@0 | 23 | * |
michael@0 | 24 | * That approach is: subclasses implement the abstract methods |
michael@0 | 25 | * {@link #insertInTransaction(android.net.Uri, android.content.ContentValues)}, |
michael@0 | 26 | * {@link #deleteInTransaction(android.net.Uri, String, String[])}, and |
michael@0 | 27 | * {@link #updateInTransaction(android.net.Uri, android.content.ContentValues, String, String[])}. |
michael@0 | 28 | * |
michael@0 | 29 | * These are all called expecting a transaction to be established, so failed |
michael@0 | 30 | * modifications can be rolled-back, and work batched. |
michael@0 | 31 | * |
michael@0 | 32 | * If no transaction is established, that's not a problem. Transaction nesting |
michael@0 | 33 | * can be avoided by using {@link #beginWrite(SQLiteDatabase)}. |
michael@0 | 34 | * |
michael@0 | 35 | * The decision of when to begin a transaction is left to the subclasses, |
michael@0 | 36 | * primarily to avoid the pattern of a transaction being begun, a read occurring, |
michael@0 | 37 | * and then a write being necessary. This lock upgrade can result in SQLITE_BUSY, |
michael@0 | 38 | * which we don't handle well. Better to avoid starting a transaction too soon! |
michael@0 | 39 | * |
michael@0 | 40 | * You are probably interested in some subclasses: |
michael@0 | 41 | * |
michael@0 | 42 | * * {@link AbstractPerProfileDatabaseProvider} provides a simple abstraction for |
michael@0 | 43 | * querying databases that are stored in the user's profile directory. |
michael@0 | 44 | * * {@link PerProfileDatabaseProvider} is a simple version that only allows a |
michael@0 | 45 | * single ContentProvider to access each per-profile database. |
michael@0 | 46 | * * {@link SharedBrowserDatabaseProvider} is an example of a per-profile provider |
michael@0 | 47 | * that allows for multiple providers to safely work with the same databases. |
michael@0 | 48 | */ |
michael@0 | 49 | @SuppressWarnings("javadoc") |
michael@0 | 50 | public abstract class AbstractTransactionalProvider extends ContentProvider { |
michael@0 | 51 | private static final String LOGTAG = "GeckoTransProvider"; |
michael@0 | 52 | |
michael@0 | 53 | private static boolean logDebug = Log.isLoggable(LOGTAG, Log.DEBUG); |
michael@0 | 54 | private static boolean logVerbose = Log.isLoggable(LOGTAG, Log.VERBOSE); |
michael@0 | 55 | |
michael@0 | 56 | protected abstract SQLiteDatabase getReadableDatabase(Uri uri); |
michael@0 | 57 | protected abstract SQLiteDatabase getWritableDatabase(Uri uri); |
michael@0 | 58 | |
michael@0 | 59 | public abstract SQLiteDatabase getWritableDatabaseForTesting(Uri uri); |
michael@0 | 60 | |
michael@0 | 61 | protected abstract Uri insertInTransaction(Uri uri, ContentValues values); |
michael@0 | 62 | protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs); |
michael@0 | 63 | protected abstract int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs); |
michael@0 | 64 | |
michael@0 | 65 | /** |
michael@0 | 66 | * Track whether we're in a batch operation. |
michael@0 | 67 | * |
michael@0 | 68 | * When we're in a batch operation, individual write steps won't even try |
michael@0 | 69 | * to start a transaction... and neither will they attempt to finish one. |
michael@0 | 70 | * |
michael@0 | 71 | * Set this to <code>Boolean.TRUE</code> when you're entering a batch -- |
michael@0 | 72 | * a section of code in which {@link ContentProvider} methods will be |
michael@0 | 73 | * called, but nested transactions should not be started. Callers are |
michael@0 | 74 | * responsible for beginning and ending the enclosing transaction, and |
michael@0 | 75 | * for setting this to <code>Boolean.FALSE</code> when done. |
michael@0 | 76 | * |
michael@0 | 77 | * This is a ThreadLocal separate from `db.inTransaction` because batched |
michael@0 | 78 | * operations start transactions independent of individual ContentProvider |
michael@0 | 79 | * operations. This doesn't work well with the entire concept of this |
michael@0 | 80 | * abstract class -- that is, automatically beginning and ending transactions |
michael@0 | 81 | * for each insert/delete/update operation -- and doing so without |
michael@0 | 82 | * causing arbitrary nesting requires external tracking. |
michael@0 | 83 | * |
michael@0 | 84 | * Note that beginWrite takes a DB argument, but we don't differentiate |
michael@0 | 85 | * between databases in this tracking flag. If your ContentProvider manages |
michael@0 | 86 | * multiple database transactions within the same thread, you'll need to |
michael@0 | 87 | * amend this scheme -- but then, you're already doing some serious wizardry, |
michael@0 | 88 | * so rock on. |
michael@0 | 89 | */ |
michael@0 | 90 | final ThreadLocal<Boolean> isInBatchOperation = new ThreadLocal<Boolean>(); |
michael@0 | 91 | |
michael@0 | 92 | /** |
michael@0 | 93 | * Return true if OS version and database parallelism support indicates |
michael@0 | 94 | * that this provider should bundle writes into transactions. |
michael@0 | 95 | */ |
michael@0 | 96 | @SuppressWarnings("static-method") |
michael@0 | 97 | protected boolean shouldUseTransactions() { |
michael@0 | 98 | return Build.VERSION.SDK_INT >= 11; |
michael@0 | 99 | } |
michael@0 | 100 | |
michael@0 | 101 | protected static String computeSQLInClause(int items, String field) { |
michael@0 | 102 | final StringBuilder builder = new StringBuilder(field); |
michael@0 | 103 | builder.append(" IN ("); |
michael@0 | 104 | int i = 0; |
michael@0 | 105 | for (; i < items - 1; ++i) { |
michael@0 | 106 | builder.append("?, "); |
michael@0 | 107 | } |
michael@0 | 108 | if (i < items) { |
michael@0 | 109 | builder.append("?"); |
michael@0 | 110 | } |
michael@0 | 111 | builder.append(")"); |
michael@0 | 112 | return builder.toString(); |
michael@0 | 113 | } |
michael@0 | 114 | |
michael@0 | 115 | private boolean isInBatch() { |
michael@0 | 116 | final Boolean isInBatch = isInBatchOperation.get(); |
michael@0 | 117 | if (isInBatch == null) { |
michael@0 | 118 | return false; |
michael@0 | 119 | } |
michael@0 | 120 | return isInBatch.booleanValue(); |
michael@0 | 121 | } |
michael@0 | 122 | |
michael@0 | 123 | /** |
michael@0 | 124 | * If we're not currently in a transaction, and we should be, start one. |
michael@0 | 125 | */ |
michael@0 | 126 | protected void beginWrite(final SQLiteDatabase db) { |
michael@0 | 127 | if (isInBatch()) { |
michael@0 | 128 | trace("Not bothering with an intermediate write transaction: inside batch operation."); |
michael@0 | 129 | return; |
michael@0 | 130 | } |
michael@0 | 131 | |
michael@0 | 132 | if (shouldUseTransactions() && !db.inTransaction()) { |
michael@0 | 133 | trace("beginWrite: beginning transaction."); |
michael@0 | 134 | db.beginTransaction(); |
michael@0 | 135 | } |
michael@0 | 136 | } |
michael@0 | 137 | |
michael@0 | 138 | /** |
michael@0 | 139 | * If we're not in a batch, but we are in a write transaction, mark it as |
michael@0 | 140 | * successful. |
michael@0 | 141 | */ |
michael@0 | 142 | protected void markWriteSuccessful(final SQLiteDatabase db) { |
michael@0 | 143 | if (isInBatch()) { |
michael@0 | 144 | trace("Not marking write successful: inside batch operation."); |
michael@0 | 145 | return; |
michael@0 | 146 | } |
michael@0 | 147 | |
michael@0 | 148 | if (shouldUseTransactions() && db.inTransaction()) { |
michael@0 | 149 | trace("Marking write transaction successful."); |
michael@0 | 150 | db.setTransactionSuccessful(); |
michael@0 | 151 | } |
michael@0 | 152 | } |
michael@0 | 153 | |
michael@0 | 154 | /** |
michael@0 | 155 | * If we're not in a batch, but we are in a write transaction, |
michael@0 | 156 | * end it. |
michael@0 | 157 | * |
michael@0 | 158 | * @see PerProfileDatabaseProvider#markWriteSuccessful(SQLiteDatabase) |
michael@0 | 159 | */ |
michael@0 | 160 | protected void endWrite(final SQLiteDatabase db) { |
michael@0 | 161 | if (isInBatch()) { |
michael@0 | 162 | trace("Not ending write: inside batch operation."); |
michael@0 | 163 | return; |
michael@0 | 164 | } |
michael@0 | 165 | |
michael@0 | 166 | if (shouldUseTransactions() && db.inTransaction()) { |
michael@0 | 167 | trace("endWrite: ending transaction."); |
michael@0 | 168 | db.endTransaction(); |
michael@0 | 169 | } |
michael@0 | 170 | } |
michael@0 | 171 | |
michael@0 | 172 | protected void beginBatch(final SQLiteDatabase db) { |
michael@0 | 173 | trace("Beginning batch."); |
michael@0 | 174 | isInBatchOperation.set(Boolean.TRUE); |
michael@0 | 175 | db.beginTransaction(); |
michael@0 | 176 | } |
michael@0 | 177 | |
michael@0 | 178 | protected void markBatchSuccessful(final SQLiteDatabase db) { |
michael@0 | 179 | if (isInBatch()) { |
michael@0 | 180 | trace("Marking batch successful."); |
michael@0 | 181 | db.setTransactionSuccessful(); |
michael@0 | 182 | return; |
michael@0 | 183 | } |
michael@0 | 184 | Log.w(LOGTAG, "Unexpectedly asked to mark batch successful, but not in batch!"); |
michael@0 | 185 | throw new IllegalStateException("Not in batch."); |
michael@0 | 186 | } |
michael@0 | 187 | |
michael@0 | 188 | protected void endBatch(final SQLiteDatabase db) { |
michael@0 | 189 | trace("Ending batch."); |
michael@0 | 190 | db.endTransaction(); |
michael@0 | 191 | isInBatchOperation.set(Boolean.FALSE); |
michael@0 | 192 | } |
michael@0 | 193 | |
michael@0 | 194 | /** |
michael@0 | 195 | * Turn a single-column cursor of longs into a single SQL "IN" clause. |
michael@0 | 196 | * We can do this without using selection arguments because Long isn't |
michael@0 | 197 | * vulnerable to injection. |
michael@0 | 198 | */ |
michael@0 | 199 | protected static String computeSQLInClauseFromLongs(final Cursor cursor, String field) { |
michael@0 | 200 | final StringBuilder builder = new StringBuilder(field); |
michael@0 | 201 | builder.append(" IN ("); |
michael@0 | 202 | final int commaLimit = cursor.getCount() - 1; |
michael@0 | 203 | int i = 0; |
michael@0 | 204 | while (cursor.moveToNext()) { |
michael@0 | 205 | builder.append(cursor.getLong(0)); |
michael@0 | 206 | if (i++ < commaLimit) { |
michael@0 | 207 | builder.append(", "); |
michael@0 | 208 | } |
michael@0 | 209 | } |
michael@0 | 210 | builder.append(")"); |
michael@0 | 211 | return builder.toString(); |
michael@0 | 212 | } |
michael@0 | 213 | |
michael@0 | 214 | @Override |
michael@0 | 215 | public int delete(Uri uri, String selection, String[] selectionArgs) { |
michael@0 | 216 | trace("Calling delete on URI: " + uri + ", " + selection + ", " + selectionArgs); |
michael@0 | 217 | |
michael@0 | 218 | final SQLiteDatabase db = getWritableDatabase(uri); |
michael@0 | 219 | int deleted = 0; |
michael@0 | 220 | |
michael@0 | 221 | try { |
michael@0 | 222 | deleted = deleteInTransaction(uri, selection, selectionArgs); |
michael@0 | 223 | markWriteSuccessful(db); |
michael@0 | 224 | } finally { |
michael@0 | 225 | endWrite(db); |
michael@0 | 226 | } |
michael@0 | 227 | |
michael@0 | 228 | if (deleted > 0) { |
michael@0 | 229 | final boolean shouldSyncToNetwork = !isCallerSync(uri); |
michael@0 | 230 | getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork); |
michael@0 | 231 | } |
michael@0 | 232 | |
michael@0 | 233 | return deleted; |
michael@0 | 234 | } |
michael@0 | 235 | |
michael@0 | 236 | @Override |
michael@0 | 237 | public Uri insert(Uri uri, ContentValues values) { |
michael@0 | 238 | trace("Calling insert on URI: " + uri); |
michael@0 | 239 | |
michael@0 | 240 | final SQLiteDatabase db = getWritableDatabase(uri); |
michael@0 | 241 | Uri result = null; |
michael@0 | 242 | try { |
michael@0 | 243 | result = insertInTransaction(uri, values); |
michael@0 | 244 | markWriteSuccessful(db); |
michael@0 | 245 | } catch (SQLException sqle) { |
michael@0 | 246 | Log.e(LOGTAG, "exception in DB operation", sqle); |
michael@0 | 247 | } catch (UnsupportedOperationException uoe) { |
michael@0 | 248 | Log.e(LOGTAG, "don't know how to perform that insert", uoe); |
michael@0 | 249 | } finally { |
michael@0 | 250 | endWrite(db); |
michael@0 | 251 | } |
michael@0 | 252 | |
michael@0 | 253 | if (result != null) { |
michael@0 | 254 | final boolean shouldSyncToNetwork = !isCallerSync(uri); |
michael@0 | 255 | getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork); |
michael@0 | 256 | } |
michael@0 | 257 | |
michael@0 | 258 | return result; |
michael@0 | 259 | } |
michael@0 | 260 | |
michael@0 | 261 | @Override |
michael@0 | 262 | public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { |
michael@0 | 263 | trace("Calling update on URI: " + uri + ", " + selection + ", " + selectionArgs); |
michael@0 | 264 | |
michael@0 | 265 | final SQLiteDatabase db = getWritableDatabase(uri); |
michael@0 | 266 | int updated = 0; |
michael@0 | 267 | |
michael@0 | 268 | try { |
michael@0 | 269 | updated = updateInTransaction(uri, values, selection, |
michael@0 | 270 | selectionArgs); |
michael@0 | 271 | markWriteSuccessful(db); |
michael@0 | 272 | } finally { |
michael@0 | 273 | endWrite(db); |
michael@0 | 274 | } |
michael@0 | 275 | |
michael@0 | 276 | if (updated > 0) { |
michael@0 | 277 | final boolean shouldSyncToNetwork = !isCallerSync(uri); |
michael@0 | 278 | getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork); |
michael@0 | 279 | } |
michael@0 | 280 | |
michael@0 | 281 | return updated; |
michael@0 | 282 | } |
michael@0 | 283 | |
michael@0 | 284 | @Override |
michael@0 | 285 | public int bulkInsert(Uri uri, ContentValues[] values) { |
michael@0 | 286 | if (values == null) { |
michael@0 | 287 | return 0; |
michael@0 | 288 | } |
michael@0 | 289 | |
michael@0 | 290 | int numValues = values.length; |
michael@0 | 291 | int successes = 0; |
michael@0 | 292 | |
michael@0 | 293 | final SQLiteDatabase db = getWritableDatabase(uri); |
michael@0 | 294 | |
michael@0 | 295 | debug("bulkInsert: explicitly starting transaction."); |
michael@0 | 296 | beginBatch(db); |
michael@0 | 297 | |
michael@0 | 298 | try { |
michael@0 | 299 | for (int i = 0; i < numValues; i++) { |
michael@0 | 300 | insertInTransaction(uri, values[i]); |
michael@0 | 301 | successes++; |
michael@0 | 302 | } |
michael@0 | 303 | trace("Flushing DB bulkinsert..."); |
michael@0 | 304 | markBatchSuccessful(db); |
michael@0 | 305 | } finally { |
michael@0 | 306 | debug("bulkInsert: explicitly ending transaction."); |
michael@0 | 307 | endBatch(db); |
michael@0 | 308 | } |
michael@0 | 309 | |
michael@0 | 310 | if (successes > 0) { |
michael@0 | 311 | final boolean shouldSyncToNetwork = !isCallerSync(uri); |
michael@0 | 312 | getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork); |
michael@0 | 313 | } |
michael@0 | 314 | |
michael@0 | 315 | return successes; |
michael@0 | 316 | } |
michael@0 | 317 | |
michael@0 | 318 | /** |
michael@0 | 319 | * Indicates whether a query should include deleted fields |
michael@0 | 320 | * based on the URI. |
michael@0 | 321 | * @param uri query URI |
michael@0 | 322 | */ |
michael@0 | 323 | protected static boolean shouldShowDeleted(Uri uri) { |
michael@0 | 324 | String showDeleted = uri.getQueryParameter(BrowserContract.PARAM_SHOW_DELETED); |
michael@0 | 325 | return !TextUtils.isEmpty(showDeleted); |
michael@0 | 326 | } |
michael@0 | 327 | |
michael@0 | 328 | /** |
michael@0 | 329 | * Indicates whether an insertion should be made if a record doesn't |
michael@0 | 330 | * exist, based on the URI. |
michael@0 | 331 | * @param uri query URI |
michael@0 | 332 | */ |
michael@0 | 333 | protected static boolean shouldUpdateOrInsert(Uri uri) { |
michael@0 | 334 | String insertIfNeeded = uri.getQueryParameter(BrowserContract.PARAM_INSERT_IF_NEEDED); |
michael@0 | 335 | return Boolean.parseBoolean(insertIfNeeded); |
michael@0 | 336 | } |
michael@0 | 337 | |
michael@0 | 338 | /** |
michael@0 | 339 | * Indicates whether query is a test based on the URI. |
michael@0 | 340 | * @param uri query URI |
michael@0 | 341 | */ |
michael@0 | 342 | protected static boolean isTest(Uri uri) { |
michael@0 | 343 | if (uri == null) { |
michael@0 | 344 | return false; |
michael@0 | 345 | } |
michael@0 | 346 | String isTest = uri.getQueryParameter(BrowserContract.PARAM_IS_TEST); |
michael@0 | 347 | return !TextUtils.isEmpty(isTest); |
michael@0 | 348 | } |
michael@0 | 349 | |
michael@0 | 350 | /** |
michael@0 | 351 | * Return true of the query is from Firefox Sync. |
michael@0 | 352 | * @param uri query URI |
michael@0 | 353 | */ |
michael@0 | 354 | protected static boolean isCallerSync(Uri uri) { |
michael@0 | 355 | String isSync = uri.getQueryParameter(BrowserContract.PARAM_IS_SYNC); |
michael@0 | 356 | return !TextUtils.isEmpty(isSync); |
michael@0 | 357 | } |
michael@0 | 358 | |
michael@0 | 359 | protected static void trace(String message) { |
michael@0 | 360 | if (logVerbose) { |
michael@0 | 361 | Log.v(LOGTAG, message); |
michael@0 | 362 | } |
michael@0 | 363 | } |
michael@0 | 364 | |
michael@0 | 365 | protected static void debug(String message) { |
michael@0 | 366 | if (logDebug) { |
michael@0 | 367 | Log.d(LOGTAG, message); |
michael@0 | 368 | } |
michael@0 | 369 | } |
michael@0 | 370 | } |