michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0:
michael@0: package org.mozilla.gecko.db;
michael@0:
michael@0: import android.content.ContentProvider;
michael@0: import android.content.ContentValues;
michael@0: import android.database.Cursor;
michael@0: import android.database.SQLException;
michael@0: import android.database.sqlite.SQLiteDatabase;
michael@0: import android.net.Uri;
michael@0: import android.os.Build;
michael@0: import android.text.TextUtils;
michael@0: import android.util.Log;
michael@0:
michael@0: /**
michael@0: * This abstract class exists to capture some of the transaction-handling
michael@0: * commonalities in Fennec's DB layer.
michael@0: *
michael@0: * In particular, this abstracts DB access, batching, and a particular
michael@0: * transaction approach.
michael@0: *
michael@0: * That approach is: subclasses implement the abstract methods
michael@0: * {@link #insertInTransaction(android.net.Uri, android.content.ContentValues)},
michael@0: * {@link #deleteInTransaction(android.net.Uri, String, String[])}, and
michael@0: * {@link #updateInTransaction(android.net.Uri, android.content.ContentValues, String, String[])}.
michael@0: *
michael@0: * These are all called expecting a transaction to be established, so failed
michael@0: * modifications can be rolled-back, and work batched.
michael@0: *
michael@0: * If no transaction is established, that's not a problem. Transaction nesting
michael@0: * can be avoided by using {@link #beginWrite(SQLiteDatabase)}.
michael@0: *
michael@0: * The decision of when to begin a transaction is left to the subclasses,
michael@0: * primarily to avoid the pattern of a transaction being begun, a read occurring,
michael@0: * and then a write being necessary. This lock upgrade can result in SQLITE_BUSY,
michael@0: * which we don't handle well. Better to avoid starting a transaction too soon!
michael@0: *
michael@0: * You are probably interested in some subclasses:
michael@0: *
michael@0: * * {@link AbstractPerProfileDatabaseProvider} provides a simple abstraction for
michael@0: * querying databases that are stored in the user's profile directory.
michael@0: * * {@link PerProfileDatabaseProvider} is a simple version that only allows a
michael@0: * single ContentProvider to access each per-profile database.
michael@0: * * {@link SharedBrowserDatabaseProvider} is an example of a per-profile provider
michael@0: * that allows for multiple providers to safely work with the same databases.
michael@0: */
michael@0: @SuppressWarnings("javadoc")
michael@0: public abstract class AbstractTransactionalProvider extends ContentProvider {
michael@0: private static final String LOGTAG = "GeckoTransProvider";
michael@0:
michael@0: private static boolean logDebug = Log.isLoggable(LOGTAG, Log.DEBUG);
michael@0: private static boolean logVerbose = Log.isLoggable(LOGTAG, Log.VERBOSE);
michael@0:
michael@0: protected abstract SQLiteDatabase getReadableDatabase(Uri uri);
michael@0: protected abstract SQLiteDatabase getWritableDatabase(Uri uri);
michael@0:
michael@0: public abstract SQLiteDatabase getWritableDatabaseForTesting(Uri uri);
michael@0:
michael@0: protected abstract Uri insertInTransaction(Uri uri, ContentValues values);
michael@0: protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs);
michael@0: protected abstract int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs);
michael@0:
michael@0: /**
michael@0: * Track whether we're in a batch operation.
michael@0: *
michael@0: * When we're in a batch operation, individual write steps won't even try
michael@0: * to start a transaction... and neither will they attempt to finish one.
michael@0: *
michael@0: * Set this to Boolean.TRUE
when you're entering a batch --
michael@0: * a section of code in which {@link ContentProvider} methods will be
michael@0: * called, but nested transactions should not be started. Callers are
michael@0: * responsible for beginning and ending the enclosing transaction, and
michael@0: * for setting this to Boolean.FALSE
when done.
michael@0: *
michael@0: * This is a ThreadLocal separate from `db.inTransaction` because batched
michael@0: * operations start transactions independent of individual ContentProvider
michael@0: * operations. This doesn't work well with the entire concept of this
michael@0: * abstract class -- that is, automatically beginning and ending transactions
michael@0: * for each insert/delete/update operation -- and doing so without
michael@0: * causing arbitrary nesting requires external tracking.
michael@0: *
michael@0: * Note that beginWrite takes a DB argument, but we don't differentiate
michael@0: * between databases in this tracking flag. If your ContentProvider manages
michael@0: * multiple database transactions within the same thread, you'll need to
michael@0: * amend this scheme -- but then, you're already doing some serious wizardry,
michael@0: * so rock on.
michael@0: */
michael@0: final ThreadLocal isInBatchOperation = new ThreadLocal();
michael@0:
michael@0: /**
michael@0: * Return true if OS version and database parallelism support indicates
michael@0: * that this provider should bundle writes into transactions.
michael@0: */
michael@0: @SuppressWarnings("static-method")
michael@0: protected boolean shouldUseTransactions() {
michael@0: return Build.VERSION.SDK_INT >= 11;
michael@0: }
michael@0:
michael@0: protected static String computeSQLInClause(int items, String field) {
michael@0: final StringBuilder builder = new StringBuilder(field);
michael@0: builder.append(" IN (");
michael@0: int i = 0;
michael@0: for (; i < items - 1; ++i) {
michael@0: builder.append("?, ");
michael@0: }
michael@0: if (i < items) {
michael@0: builder.append("?");
michael@0: }
michael@0: builder.append(")");
michael@0: return builder.toString();
michael@0: }
michael@0:
michael@0: private boolean isInBatch() {
michael@0: final Boolean isInBatch = isInBatchOperation.get();
michael@0: if (isInBatch == null) {
michael@0: return false;
michael@0: }
michael@0: return isInBatch.booleanValue();
michael@0: }
michael@0:
michael@0: /**
michael@0: * If we're not currently in a transaction, and we should be, start one.
michael@0: */
michael@0: protected void beginWrite(final SQLiteDatabase db) {
michael@0: if (isInBatch()) {
michael@0: trace("Not bothering with an intermediate write transaction: inside batch operation.");
michael@0: return;
michael@0: }
michael@0:
michael@0: if (shouldUseTransactions() && !db.inTransaction()) {
michael@0: trace("beginWrite: beginning transaction.");
michael@0: db.beginTransaction();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * If we're not in a batch, but we are in a write transaction, mark it as
michael@0: * successful.
michael@0: */
michael@0: protected void markWriteSuccessful(final SQLiteDatabase db) {
michael@0: if (isInBatch()) {
michael@0: trace("Not marking write successful: inside batch operation.");
michael@0: return;
michael@0: }
michael@0:
michael@0: if (shouldUseTransactions() && db.inTransaction()) {
michael@0: trace("Marking write transaction successful.");
michael@0: db.setTransactionSuccessful();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * If we're not in a batch, but we are in a write transaction,
michael@0: * end it.
michael@0: *
michael@0: * @see PerProfileDatabaseProvider#markWriteSuccessful(SQLiteDatabase)
michael@0: */
michael@0: protected void endWrite(final SQLiteDatabase db) {
michael@0: if (isInBatch()) {
michael@0: trace("Not ending write: inside batch operation.");
michael@0: return;
michael@0: }
michael@0:
michael@0: if (shouldUseTransactions() && db.inTransaction()) {
michael@0: trace("endWrite: ending transaction.");
michael@0: db.endTransaction();
michael@0: }
michael@0: }
michael@0:
michael@0: protected void beginBatch(final SQLiteDatabase db) {
michael@0: trace("Beginning batch.");
michael@0: isInBatchOperation.set(Boolean.TRUE);
michael@0: db.beginTransaction();
michael@0: }
michael@0:
michael@0: protected void markBatchSuccessful(final SQLiteDatabase db) {
michael@0: if (isInBatch()) {
michael@0: trace("Marking batch successful.");
michael@0: db.setTransactionSuccessful();
michael@0: return;
michael@0: }
michael@0: Log.w(LOGTAG, "Unexpectedly asked to mark batch successful, but not in batch!");
michael@0: throw new IllegalStateException("Not in batch.");
michael@0: }
michael@0:
michael@0: protected void endBatch(final SQLiteDatabase db) {
michael@0: trace("Ending batch.");
michael@0: db.endTransaction();
michael@0: isInBatchOperation.set(Boolean.FALSE);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Turn a single-column cursor of longs into a single SQL "IN" clause.
michael@0: * We can do this without using selection arguments because Long isn't
michael@0: * vulnerable to injection.
michael@0: */
michael@0: protected static String computeSQLInClauseFromLongs(final Cursor cursor, String field) {
michael@0: final StringBuilder builder = new StringBuilder(field);
michael@0: builder.append(" IN (");
michael@0: final int commaLimit = cursor.getCount() - 1;
michael@0: int i = 0;
michael@0: while (cursor.moveToNext()) {
michael@0: builder.append(cursor.getLong(0));
michael@0: if (i++ < commaLimit) {
michael@0: builder.append(", ");
michael@0: }
michael@0: }
michael@0: builder.append(")");
michael@0: return builder.toString();
michael@0: }
michael@0:
michael@0: @Override
michael@0: public int delete(Uri uri, String selection, String[] selectionArgs) {
michael@0: trace("Calling delete on URI: " + uri + ", " + selection + ", " + selectionArgs);
michael@0:
michael@0: final SQLiteDatabase db = getWritableDatabase(uri);
michael@0: int deleted = 0;
michael@0:
michael@0: try {
michael@0: deleted = deleteInTransaction(uri, selection, selectionArgs);
michael@0: markWriteSuccessful(db);
michael@0: } finally {
michael@0: endWrite(db);
michael@0: }
michael@0:
michael@0: if (deleted > 0) {
michael@0: final boolean shouldSyncToNetwork = !isCallerSync(uri);
michael@0: getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork);
michael@0: }
michael@0:
michael@0: return deleted;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public Uri insert(Uri uri, ContentValues values) {
michael@0: trace("Calling insert on URI: " + uri);
michael@0:
michael@0: final SQLiteDatabase db = getWritableDatabase(uri);
michael@0: Uri result = null;
michael@0: try {
michael@0: result = insertInTransaction(uri, values);
michael@0: markWriteSuccessful(db);
michael@0: } catch (SQLException sqle) {
michael@0: Log.e(LOGTAG, "exception in DB operation", sqle);
michael@0: } catch (UnsupportedOperationException uoe) {
michael@0: Log.e(LOGTAG, "don't know how to perform that insert", uoe);
michael@0: } finally {
michael@0: endWrite(db);
michael@0: }
michael@0:
michael@0: if (result != null) {
michael@0: final boolean shouldSyncToNetwork = !isCallerSync(uri);
michael@0: getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork);
michael@0: }
michael@0:
michael@0: return result;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
michael@0: trace("Calling update on URI: " + uri + ", " + selection + ", " + selectionArgs);
michael@0:
michael@0: final SQLiteDatabase db = getWritableDatabase(uri);
michael@0: int updated = 0;
michael@0:
michael@0: try {
michael@0: updated = updateInTransaction(uri, values, selection,
michael@0: selectionArgs);
michael@0: markWriteSuccessful(db);
michael@0: } finally {
michael@0: endWrite(db);
michael@0: }
michael@0:
michael@0: if (updated > 0) {
michael@0: final boolean shouldSyncToNetwork = !isCallerSync(uri);
michael@0: getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork);
michael@0: }
michael@0:
michael@0: return updated;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public int bulkInsert(Uri uri, ContentValues[] values) {
michael@0: if (values == null) {
michael@0: return 0;
michael@0: }
michael@0:
michael@0: int numValues = values.length;
michael@0: int successes = 0;
michael@0:
michael@0: final SQLiteDatabase db = getWritableDatabase(uri);
michael@0:
michael@0: debug("bulkInsert: explicitly starting transaction.");
michael@0: beginBatch(db);
michael@0:
michael@0: try {
michael@0: for (int i = 0; i < numValues; i++) {
michael@0: insertInTransaction(uri, values[i]);
michael@0: successes++;
michael@0: }
michael@0: trace("Flushing DB bulkinsert...");
michael@0: markBatchSuccessful(db);
michael@0: } finally {
michael@0: debug("bulkInsert: explicitly ending transaction.");
michael@0: endBatch(db);
michael@0: }
michael@0:
michael@0: if (successes > 0) {
michael@0: final boolean shouldSyncToNetwork = !isCallerSync(uri);
michael@0: getContext().getContentResolver().notifyChange(uri, null, shouldSyncToNetwork);
michael@0: }
michael@0:
michael@0: return successes;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Indicates whether a query should include deleted fields
michael@0: * based on the URI.
michael@0: * @param uri query URI
michael@0: */
michael@0: protected static boolean shouldShowDeleted(Uri uri) {
michael@0: String showDeleted = uri.getQueryParameter(BrowserContract.PARAM_SHOW_DELETED);
michael@0: return !TextUtils.isEmpty(showDeleted);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Indicates whether an insertion should be made if a record doesn't
michael@0: * exist, based on the URI.
michael@0: * @param uri query URI
michael@0: */
michael@0: protected static boolean shouldUpdateOrInsert(Uri uri) {
michael@0: String insertIfNeeded = uri.getQueryParameter(BrowserContract.PARAM_INSERT_IF_NEEDED);
michael@0: return Boolean.parseBoolean(insertIfNeeded);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Indicates whether query is a test based on the URI.
michael@0: * @param uri query URI
michael@0: */
michael@0: protected static boolean isTest(Uri uri) {
michael@0: if (uri == null) {
michael@0: return false;
michael@0: }
michael@0: String isTest = uri.getQueryParameter(BrowserContract.PARAM_IS_TEST);
michael@0: return !TextUtils.isEmpty(isTest);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Return true of the query is from Firefox Sync.
michael@0: * @param uri query URI
michael@0: */
michael@0: protected static boolean isCallerSync(Uri uri) {
michael@0: String isSync = uri.getQueryParameter(BrowserContract.PARAM_IS_SYNC);
michael@0: return !TextUtils.isEmpty(isSync);
michael@0: }
michael@0:
michael@0: protected static void trace(String message) {
michael@0: if (logVerbose) {
michael@0: Log.v(LOGTAG, message);
michael@0: }
michael@0: }
michael@0:
michael@0: protected static void debug(String message) {
michael@0: if (logDebug) {
michael@0: Log.d(LOGTAG, message);
michael@0: }
michael@0: }
michael@0: }