gnunet-android

GNUnet for Android
Log | Files | Refs | README

SQLiteDatabase.java (95416B)


      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 /*
     17 ** Modified to support SQLite extensions by the SQLite developers: 
     18 ** sqlite-dev@sqlite.org.
     19 */
     20 
     21 package org.sqlite.database.sqlite;
     22 
     23 import android.content.ContentValues;
     24 import android.database.Cursor;
     25 import org.sqlite.database.DatabaseErrorHandler;
     26 import org.sqlite.database.DatabaseUtils;
     27 import org.sqlite.database.DefaultDatabaseErrorHandler;
     28 import org.sqlite.database.SQLException;
     29 import org.sqlite.database.sqlite.SQLiteDebug.DbStats;
     30 import android.os.CancellationSignal;
     31 import android.os.Looper;
     32 import android.os.OperationCanceledException;
     33 import android.text.TextUtils;
     34 import android.util.EventLog;
     35 import android.util.Log;
     36 import android.util.Pair;
     37 import android.util.Printer;
     38 
     39 import org.sqlite.database.sqlite.CloseGuard;
     40 
     41 import java.io.File;
     42 import java.io.FileFilter;
     43 import java.util.ArrayList;
     44 import java.util.HashMap;
     45 import java.util.List;
     46 import java.util.Locale;
     47 import java.util.Map;
     48 import java.util.WeakHashMap;
     49 
     50 /**
     51  * Exposes methods to manage a SQLite database.
     52  *
     53  * <p>
     54  * SQLiteDatabase has methods to create, delete, execute SQL commands, and
     55  * perform other common database management tasks.
     56  * </p><p>
     57  * See the Notepad sample application in the SDK for an example of creating
     58  * and managing a database.
     59  * </p><p>
     60  * Database names must be unique within an application, not across all applications.
     61  * </p>
     62  *
     63  * <h3>Localized Collation - ORDER BY</h3>
     64  * <p>
     65  * In addition to SQLite's default <code>BINARY</code> collator, Android supplies
     66  * two more, <code>LOCALIZED</code>, which changes with the system's current locale,
     67  * and <code>UNICODE</code>, which is the Unicode Collation Algorithm and not tailored
     68  * to the current locale.
     69  * </p>
     70  */
     71 public final class SQLiteDatabase extends SQLiteClosable {
     72     private static final String TAG = "SQLiteDatabase";
     73 
     74     private static final int EVENT_DB_CORRUPT = 75004;
     75 
     76     // Stores reference to all databases opened in the current process.
     77     // (The referent Object is not used at this time.)
     78     // INVARIANT: Guarded by sActiveDatabases.
     79     private static WeakHashMap<SQLiteDatabase, Object> sActiveDatabases =
     80             new WeakHashMap<SQLiteDatabase, Object>();
     81 
     82     // Thread-local for database sessions that belong to this database.
     83     // Each thread has its own database session.
     84     // INVARIANT: Immutable.
     85     private final ThreadLocal<SQLiteSession> mThreadSession = new ThreadLocal<SQLiteSession>() {
     86         @Override
     87         protected SQLiteSession initialValue() {
     88             return createSession();
     89         }
     90     };
     91 
     92     // The optional factory to use when creating new Cursors.  May be null.
     93     // INVARIANT: Immutable.
     94     private final CursorFactory mCursorFactory;
     95 
     96     // Error handler to be used when SQLite returns corruption errors.
     97     // INVARIANT: Immutable.
     98     private final DatabaseErrorHandler mErrorHandler;
     99 
    100     // Shared database state lock.
    101     // This lock guards all of the shared state of the database, such as its
    102     // configuration, whether it is open or closed, and so on.  This lock should
    103     // be held for as little time as possible.
    104     //
    105     // The lock MUST NOT be held while attempting to acquire database connections or
    106     // while executing SQL statements on behalf of the client as it can lead to deadlock.
    107     //
    108     // It is ok to hold the lock while reconfiguring the connection pool or dumping
    109     // statistics because those operations are non-reentrant and do not try to acquire
    110     // connections that might be held by other threads.
    111     //
    112     // Basic rule: grab the lock, access or modify global state, release the lock, then
    113     // do the required SQL work.
    114     private final Object mLock = new Object();
    115 
    116     // Warns if the database is finalized without being closed properly.
    117     // INVARIANT: Guarded by mLock.
    118     private final CloseGuard mCloseGuardLocked = CloseGuard.get();
    119 
    120     // The database configuration.
    121     // INVARIANT: Guarded by mLock.
    122     private final SQLiteDatabaseConfiguration mConfigurationLocked;
    123 
    124     // The connection pool for the database, null when closed.
    125     // The pool itself is thread-safe, but the reference to it can only be acquired
    126     // when the lock is held.
    127     // INVARIANT: Guarded by mLock.
    128     private SQLiteConnectionPool mConnectionPoolLocked;
    129 
    130     // True if the database has attached databases.
    131     // INVARIANT: Guarded by mLock.
    132     private boolean mHasAttachedDbsLocked;
    133 
    134     /**
    135      * When a constraint violation occurs, an immediate ROLLBACK occurs,
    136      * thus ending the current transaction, and the command aborts with a
    137      * return code of SQLITE_CONSTRAINT. If no transaction is active
    138      * (other than the implied transaction that is created on every command)
    139      * then this algorithm works the same as ABORT.
    140      */
    141     public static final int CONFLICT_ROLLBACK = 1;
    142 
    143     /**
    144      * When a constraint violation occurs,no ROLLBACK is executed
    145      * so changes from prior commands within the same transaction
    146      * are preserved. This is the default behavior.
    147      */
    148     public static final int CONFLICT_ABORT = 2;
    149 
    150     /**
    151      * When a constraint violation occurs, the command aborts with a return
    152      * code SQLITE_CONSTRAINT. But any changes to the database that
    153      * the command made prior to encountering the constraint violation
    154      * are preserved and are not backed out.
    155      */
    156     public static final int CONFLICT_FAIL = 3;
    157 
    158     /**
    159      * When a constraint violation occurs, the one row that contains
    160      * the constraint violation is not inserted or changed.
    161      * But the command continues executing normally. Other rows before and
    162      * after the row that contained the constraint violation continue to be
    163      * inserted or updated normally. No error is returned.
    164      */
    165     public static final int CONFLICT_IGNORE = 4;
    166 
    167     /**
    168      * When a UNIQUE constraint violation occurs, the pre-existing rows that
    169      * are causing the constraint violation are removed prior to inserting
    170      * or updating the current row. Thus the insert or update always occurs.
    171      * The command continues executing normally. No error is returned.
    172      * If a NOT NULL constraint violation occurs, the NULL value is replaced
    173      * by the default value for that column. If the column has no default
    174      * value, then the ABORT algorithm is used. If a CHECK constraint
    175      * violation occurs then the IGNORE algorithm is used. When this conflict
    176      * resolution strategy deletes rows in order to satisfy a constraint,
    177      * it does not invoke delete triggers on those rows.
    178      * This behavior might change in a future release.
    179      */
    180     public static final int CONFLICT_REPLACE = 5;
    181 
    182     /**
    183      * Use the following when no conflict action is specified.
    184      */
    185     public static final int CONFLICT_NONE = 0;
    186 
    187     private static final String[] CONFLICT_VALUES = new String[]
    188             {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
    189 
    190     /**
    191      * Maximum Length Of A LIKE Or GLOB Pattern
    192      * The pattern matching algorithm used in the default LIKE and GLOB implementation
    193      * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
    194      * the pattern) for certain pathological cases. To avoid denial-of-service attacks
    195      * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
    196      * The default value of this limit is 50000. A modern workstation can evaluate
    197      * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
    198      * The denial of service problem only comes into play when the pattern length gets
    199      * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
    200      * are at most a few dozen bytes in length, paranoid application developers may
    201      * want to reduce this parameter to something in the range of a few hundred
    202      * if they know that external users are able to generate arbitrary patterns.
    203      */
    204     public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
    205 
    206     /**
    207      * Open flag: Flag for {@link #openDatabase} to open the database for reading and writing.
    208      * If the disk is full, this may fail even before you actually write anything.
    209      *
    210      * {@more} Note that the value of this flag is 0, so it is the default.
    211      */
    212     public static final int OPEN_READWRITE = 0x00000000;          // update native code if changing
    213 
    214     /**
    215      * Open flag: Flag for {@link #openDatabase} to open the database for reading only.
    216      * This is the only reliable way to open a database if the disk may be full.
    217      */
    218     public static final int OPEN_READONLY = 0x00000001;           // update native code if changing
    219 
    220     private static final int OPEN_READ_MASK = 0x00000001;         // update native code if changing
    221 
    222     /**
    223      * Open flag: Flag for {@link #openDatabase} to open the database without support for
    224      * localized collators.
    225      *
    226      * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
    227      * You must be consistent when using this flag to use the setting the database was
    228      * created with.  If this is set, {@link #setLocale} will do nothing.
    229      */
    230     public static final int NO_LOCALIZED_COLLATORS = 0x00000010;  // update native code if changing
    231 
    232     /**
    233      * Open flag: Flag for {@link #openDatabase} to create the database file if it does not
    234      * already exist.
    235      */
    236     public static final int CREATE_IF_NECESSARY = 0x10000000;     // update native code if changing
    237 
    238     /**
    239      * Open flag: Flag for {@link #openDatabase} to open the database file with
    240      * write-ahead logging enabled by default.  Using this flag is more efficient
    241      * than calling {@link #enableWriteAheadLogging}.
    242      *
    243      * Write-ahead logging cannot be used with read-only databases so the value of
    244      * this flag is ignored if the database is opened read-only.
    245      *
    246      * @see #enableWriteAheadLogging
    247      */
    248     public static final int ENABLE_WRITE_AHEAD_LOGGING = 0x20000000;
    249 
    250     /**
    251      * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}.
    252      *
    253      * Each prepared-statement is between 1K - 6K, depending on the complexity of the
    254      * SQL statement & schema.  A large SQL cache may use a significant amount of memory.
    255      */
    256     public static final int MAX_SQL_CACHE_SIZE = 100;
    257 
    258     private SQLiteDatabase(String path, int openFlags, CursorFactory cursorFactory,
    259             DatabaseErrorHandler errorHandler) {
    260         mCursorFactory = cursorFactory;
    261         mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
    262         mConfigurationLocked = new SQLiteDatabaseConfiguration(path, openFlags);
    263     }
    264 
    265     @Override
    266     protected void finalize() throws Throwable {
    267         try {
    268             dispose(true);
    269         } finally {
    270             super.finalize();
    271         }
    272     }
    273 
    274     @Override
    275     protected void onAllReferencesReleased() {
    276         dispose(false);
    277     }
    278 
    279     private void dispose(boolean finalized) {
    280         final SQLiteConnectionPool pool;
    281         synchronized (mLock) {
    282             if (mCloseGuardLocked != null) {
    283                 if (finalized) {
    284                     mCloseGuardLocked.warnIfOpen();
    285                 }
    286                 mCloseGuardLocked.close();
    287             }
    288 
    289             pool = mConnectionPoolLocked;
    290             mConnectionPoolLocked = null;
    291         }
    292 
    293         if (!finalized) {
    294             synchronized (sActiveDatabases) {
    295                 sActiveDatabases.remove(this);
    296             }
    297 
    298             if (pool != null) {
    299                 pool.close();
    300             }
    301         }
    302     }
    303 
    304     /**
    305      * Attempts to release memory that SQLite holds but does not require to
    306      * operate properly. Typically this memory will come from the page cache.
    307      *
    308      * @return the number of bytes actually released
    309      */
    310     public static int releaseMemory() {
    311         return SQLiteGlobal.releaseMemory();
    312     }
    313 
    314     /**
    315      * Control whether or not the SQLiteDatabase is made thread-safe by using locks
    316      * around critical sections. This is pretty expensive, so if you know that your
    317      * DB will only be used by a single thread then you should set this to false.
    318      * The default is true.
    319      * @param lockingEnabled set to true to enable locks, false otherwise
    320      *
    321      * @deprecated This method now does nothing.  Do not use.
    322      */
    323     @Deprecated
    324     public void setLockingEnabled(boolean lockingEnabled) {
    325     }
    326 
    327     /**
    328      * Gets a label to use when describing the database in log messages.
    329      * @return The label.
    330      */
    331     String getLabel() {
    332         synchronized (mLock) {
    333             return mConfigurationLocked.label;
    334         }
    335     }
    336 
    337     /**
    338      * Sends a corruption message to the database error handler.
    339      */
    340     void onCorruption() {
    341         EventLog.writeEvent(EVENT_DB_CORRUPT, getLabel());
    342         mErrorHandler.onCorruption(this);
    343     }
    344 
    345     /**
    346      * Gets the {@link SQLiteSession} that belongs to this thread for this database.
    347      * Once a thread has obtained a session, it will continue to obtain the same
    348      * session even after the database has been closed (although the session will not
    349      * be usable).  However, a thread that does not already have a session cannot
    350      * obtain one after the database has been closed.
    351      *
    352      * The idea is that threads that have active connections to the database may still
    353      * have work to complete even after the call to {@link #close}.  Active database
    354      * connections are not actually disposed until they are released by the threads
    355      * that own them.
    356      *
    357      * @return The session, never null.
    358      *
    359      * @throws IllegalStateException if the thread does not yet have a session and
    360      * the database is not open.
    361      */
    362     SQLiteSession getThreadSession() {
    363         return mThreadSession.get(); // initialValue() throws if database closed
    364     }
    365 
    366     SQLiteSession createSession() {
    367         final SQLiteConnectionPool pool;
    368         synchronized (mLock) {
    369             throwIfNotOpenLocked();
    370             pool = mConnectionPoolLocked;
    371         }
    372         return new SQLiteSession(pool);
    373     }
    374 
    375     /**
    376      * Gets default connection flags that are appropriate for this thread, taking into
    377      * account whether the thread is acting on behalf of the UI.
    378      *
    379      * @param readOnly True if the connection should be read-only.
    380      * @return The connection flags.
    381      */
    382     int getThreadDefaultConnectionFlags(boolean readOnly) {
    383         int flags = readOnly ? SQLiteConnectionPool.CONNECTION_FLAG_READ_ONLY :
    384                 SQLiteConnectionPool.CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY;
    385         if (isMainThread()) {
    386             flags |= SQLiteConnectionPool.CONNECTION_FLAG_INTERACTIVE;
    387         }
    388         return flags;
    389     }
    390 
    391     private static boolean isMainThread() {
    392         // FIXME: There should be a better way to do this.
    393         // Would also be nice to have something that would work across Binder calls.
    394         Looper looper = Looper.myLooper();
    395         return looper != null && looper == Looper.getMainLooper();
    396     }
    397 
    398     /**
    399      * Begins a transaction in EXCLUSIVE mode.
    400      * <p>
    401      * Transactions can be nested.
    402      * When the outer transaction is ended all of
    403      * the work done in that transaction and all of the nested transactions will be committed or
    404      * rolled back. The changes will be rolled back if any transaction is ended without being
    405      * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
    406      * </p>
    407      * <p>Here is the standard idiom for transactions:
    408      *
    409      * <pre>
    410      *   db.beginTransaction();
    411      *   try {
    412      *     ...
    413      *     db.setTransactionSuccessful();
    414      *   } finally {
    415      *     db.endTransaction();
    416      *   }
    417      * </pre>
    418      */
    419     public void beginTransaction() {
    420         beginTransaction(null /* transactionStatusCallback */, true);
    421     }
    422 
    423     /**
    424      * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
    425      * the outer transaction is ended all of the work done in that transaction
    426      * and all of the nested transactions will be committed or rolled back. The
    427      * changes will be rolled back if any transaction is ended without being
    428      * marked as clean (by calling setTransactionSuccessful). Otherwise they
    429      * will be committed.
    430      * <p>
    431      * Here is the standard idiom for transactions:
    432      *
    433      * <pre>
    434      *   db.beginTransactionNonExclusive();
    435      *   try {
    436      *     ...
    437      *     db.setTransactionSuccessful();
    438      *   } finally {
    439      *     db.endTransaction();
    440      *   }
    441      * </pre>
    442      */
    443     public void beginTransactionNonExclusive() {
    444         beginTransaction(null /* transactionStatusCallback */, false);
    445     }
    446 
    447     /**
    448      * Begins a transaction in EXCLUSIVE mode.
    449      * <p>
    450      * Transactions can be nested.
    451      * When the outer transaction is ended all of
    452      * the work done in that transaction and all of the nested transactions will be committed or
    453      * rolled back. The changes will be rolled back if any transaction is ended without being
    454      * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
    455      * </p>
    456      * <p>Here is the standard idiom for transactions:
    457      *
    458      * <pre>
    459      *   db.beginTransactionWithListener(listener);
    460      *   try {
    461      *     ...
    462      *     db.setTransactionSuccessful();
    463      *   } finally {
    464      *     db.endTransaction();
    465      *   }
    466      * </pre>
    467      *
    468      * @param transactionListener listener that should be notified when the transaction begins,
    469      * commits, or is rolled back, either explicitly or by a call to
    470      * {@link #yieldIfContendedSafely}.
    471      */
    472     public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
    473         beginTransaction(transactionListener, true);
    474     }
    475 
    476     /**
    477      * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
    478      * the outer transaction is ended all of the work done in that transaction
    479      * and all of the nested transactions will be committed or rolled back. The
    480      * changes will be rolled back if any transaction is ended without being
    481      * marked as clean (by calling setTransactionSuccessful). Otherwise they
    482      * will be committed.
    483      * <p>
    484      * Here is the standard idiom for transactions:
    485      *
    486      * <pre>
    487      *   db.beginTransactionWithListenerNonExclusive(listener);
    488      *   try {
    489      *     ...
    490      *     db.setTransactionSuccessful();
    491      *   } finally {
    492      *     db.endTransaction();
    493      *   }
    494      * </pre>
    495      *
    496      * @param transactionListener listener that should be notified when the
    497      *            transaction begins, commits, or is rolled back, either
    498      *            explicitly or by a call to {@link #yieldIfContendedSafely}.
    499      */
    500     public void beginTransactionWithListenerNonExclusive(
    501             SQLiteTransactionListener transactionListener) {
    502         beginTransaction(transactionListener, false);
    503     }
    504 
    505     private void beginTransaction(SQLiteTransactionListener transactionListener,
    506             boolean exclusive) {
    507         acquireReference();
    508         try {
    509             getThreadSession().beginTransaction(
    510                     exclusive ? SQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
    511                             SQLiteSession.TRANSACTION_MODE_IMMEDIATE,
    512                     transactionListener,
    513                     getThreadDefaultConnectionFlags(false /*readOnly*/), null);
    514         } finally {
    515             releaseReference();
    516         }
    517     }
    518 
    519     /**
    520      * End a transaction. See beginTransaction for notes about how to use this and when transactions
    521      * are committed and rolled back.
    522      */
    523     public void endTransaction() {
    524         acquireReference();
    525         try {
    526             getThreadSession().endTransaction(null);
    527         } finally {
    528             releaseReference();
    529         }
    530     }
    531 
    532     /**
    533      * Marks the current transaction as successful. Do not do any more database work between
    534      * calling this and calling endTransaction. Do as little non-database work as possible in that
    535      * situation too. If any errors are encountered between this and endTransaction the transaction
    536      * will still be committed.
    537      *
    538      * @throws IllegalStateException if the current thread is not in a transaction or the
    539      * transaction is already marked as successful.
    540      */
    541     public void setTransactionSuccessful() {
    542         acquireReference();
    543         try {
    544             getThreadSession().setTransactionSuccessful();
    545         } finally {
    546             releaseReference();
    547         }
    548     }
    549 
    550     /**
    551      * Returns true if the current thread has a transaction pending.
    552      *
    553      * @return True if the current thread is in a transaction.
    554      */
    555     public boolean inTransaction() {
    556         acquireReference();
    557         try {
    558             return getThreadSession().hasTransaction();
    559         } finally {
    560             releaseReference();
    561         }
    562     }
    563 
    564     /**
    565      * Returns true if the current thread is holding an active connection to the database.
    566      * <p>
    567      * The name of this method comes from a time when having an active connection
    568      * to the database meant that the thread was holding an actual lock on the
    569      * database.  Nowadays, there is no longer a true "database lock" although threads
    570      * may block if they cannot acquire a database connection to perform a
    571      * particular operation.
    572      * </p>
    573      *
    574      * @return True if the current thread is holding an active connection to the database.
    575      */
    576     public boolean isDbLockedByCurrentThread() {
    577         acquireReference();
    578         try {
    579             return getThreadSession().hasConnection();
    580         } finally {
    581             releaseReference();
    582         }
    583     }
    584 
    585     /**
    586      * Always returns false.
    587      * <p>
    588      * There is no longer the concept of a database lock, so this method always returns false.
    589      * </p>
    590      *
    591      * @return False.
    592      * @deprecated Always returns false.  Do not use this method.
    593      */
    594     @Deprecated
    595     public boolean isDbLockedByOtherThreads() {
    596         return false;
    597     }
    598 
    599     /**
    600      * Temporarily end the transaction to let other threads run. The transaction is assumed to be
    601      * successful so far. Do not call setTransactionSuccessful before calling this. When this
    602      * returns a new transaction will have been created but not marked as successful.
    603      * @return true if the transaction was yielded
    604      * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
    605      *   will not be yielded. Use yieldIfContendedSafely instead.
    606      */
    607     @Deprecated
    608     public boolean yieldIfContended() {
    609         return yieldIfContendedHelper(false /* do not check yielding */,
    610                 -1 /* sleepAfterYieldDelay */);
    611     }
    612 
    613     /**
    614      * Temporarily end the transaction to let other threads run. The transaction is assumed to be
    615      * successful so far. Do not call setTransactionSuccessful before calling this. When this
    616      * returns a new transaction will have been created but not marked as successful. This assumes
    617      * that there are no nested transactions (beginTransaction has only been called once) and will
    618      * throw an exception if that is not the case.
    619      * @return true if the transaction was yielded
    620      */
    621     public boolean yieldIfContendedSafely() {
    622         return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
    623     }
    624 
    625     /**
    626      * Temporarily end the transaction to let other threads run. The transaction is assumed to be
    627      * successful so far. Do not call setTransactionSuccessful before calling this. When this
    628      * returns a new transaction will have been created but not marked as successful. This assumes
    629      * that there are no nested transactions (beginTransaction has only been called once) and will
    630      * throw an exception if that is not the case.
    631      * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
    632      *   the lock was actually yielded. This will allow other background threads to make some
    633      *   more progress than they would if we started the transaction immediately.
    634      * @return true if the transaction was yielded
    635      */
    636     public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
    637         return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
    638     }
    639 
    640     private boolean yieldIfContendedHelper(boolean throwIfUnsafe, long sleepAfterYieldDelay) {
    641         acquireReference();
    642         try {
    643             return getThreadSession().yieldTransaction(sleepAfterYieldDelay, throwIfUnsafe, null);
    644         } finally {
    645             releaseReference();
    646         }
    647     }
    648 
    649     /**
    650      * Deprecated.
    651      * @deprecated This method no longer serves any useful purpose and has been deprecated.
    652      */
    653     @Deprecated
    654     public Map<String, String> getSyncedTables() {
    655         return new HashMap<String, String>(0);
    656     }
    657 
    658     /**
    659      * Open the database according to the flags {@link #OPEN_READWRITE}
    660      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
    661      *
    662      * <p>Sets the locale of the database to the  the system's current locale.
    663      * Call {@link #setLocale} if you would like something else.</p>
    664      *
    665      * @param path to database file to open and/or create
    666      * @param factory an optional factory class that is called to instantiate a
    667      *            cursor when query is called, or null for default
    668      * @param flags to control database access mode
    669      * @return the newly opened database
    670      * @throws SQLiteException if the database cannot be opened
    671      */
    672     public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
    673         return openDatabase(path, factory, flags, null);
    674     }
    675 
    676     /**
    677      * Open the database according to the flags {@link #OPEN_READWRITE}
    678      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
    679      *
    680      * <p>Sets the locale of the database to the  the system's current locale.
    681      * Call {@link #setLocale} if you would like something else.</p>
    682      *
    683      * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
    684      * used to handle corruption when sqlite reports database corruption.</p>
    685      *
    686      * @param path to database file to open and/or create
    687      * @param factory an optional factory class that is called to instantiate a
    688      *            cursor when query is called, or null for default
    689      * @param flags to control database access mode
    690      * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
    691      * when sqlite reports database corruption
    692      * @return the newly opened database
    693      * @throws SQLiteException if the database cannot be opened
    694      */
    695     public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
    696             DatabaseErrorHandler errorHandler) {
    697         SQLiteDatabase db = new SQLiteDatabase(path, flags, factory, errorHandler);
    698         db.open();
    699         return db;
    700     }
    701 
    702     /**
    703      * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
    704      */
    705     public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
    706         return openOrCreateDatabase(file.getPath(), factory);
    707     }
    708 
    709     /**
    710      * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
    711      */
    712     public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
    713         return openDatabase(path, factory, CREATE_IF_NECESSARY, null);
    714     }
    715 
    716     /**
    717      * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
    718      */
    719     public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
    720             DatabaseErrorHandler errorHandler) {
    721         return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
    722     }
    723 
    724     /**
    725      * Deletes a database including its journal file and other auxiliary files
    726      * that may have been created by the database engine.
    727      *
    728      * @param file The database file path.
    729      * @return True if the database was successfully deleted.
    730      */
    731     public static boolean deleteDatabase(File file) {
    732         if (file == null) {
    733             throw new IllegalArgumentException("file must not be null");
    734         }
    735 
    736         boolean deleted = false;
    737         deleted |= file.delete();
    738         deleted |= new File(file.getPath() + "-journal").delete();
    739         deleted |= new File(file.getPath() + "-shm").delete();
    740         deleted |= new File(file.getPath() + "-wal").delete();
    741 
    742         File dir = file.getParentFile();
    743         if (dir != null) {
    744             final String prefix = file.getName() + "-mj";
    745             File[] files = dir.listFiles(new FileFilter() {
    746                 @Override
    747                 public boolean accept(File candidate) {
    748                     return candidate.getName().startsWith(prefix);
    749                 }
    750             });
    751             if (files != null) {
    752                 for (File masterJournal : files) {
    753                     deleted |= masterJournal.delete();
    754                 }
    755             }
    756         }
    757         return deleted;
    758     }
    759 
    760     /**
    761      * Reopens the database in read-write mode.
    762      * If the database is already read-write, does nothing.
    763      *
    764      * @throws SQLiteException if the database could not be reopened as requested, in which
    765      * case it remains open in read only mode.
    766      * @throws IllegalStateException if the database is not open.
    767      *
    768      * @see #isReadOnly()
    769      * @hide
    770      */
    771     public void reopenReadWrite() {
    772         synchronized (mLock) {
    773             throwIfNotOpenLocked();
    774 
    775             if (!isReadOnlyLocked()) {
    776                 return; // nothing to do
    777             }
    778 
    779             // Reopen the database in read-write mode.
    780             final int oldOpenFlags = mConfigurationLocked.openFlags;
    781             mConfigurationLocked.openFlags = (mConfigurationLocked.openFlags & ~OPEN_READ_MASK)
    782                     | OPEN_READWRITE;
    783             try {
    784                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
    785             } catch (RuntimeException ex) {
    786                 mConfigurationLocked.openFlags = oldOpenFlags;
    787                 throw ex;
    788             }
    789         }
    790     }
    791 
    792     private void open() {
    793         try {
    794             try {
    795                 openInner();
    796             } catch (SQLiteDatabaseCorruptException ex) {
    797                 onCorruption();
    798                 openInner();
    799             }
    800         } catch (SQLiteException ex) {
    801             Log.e(TAG, "Failed to open database '" + getLabel() + "'.", ex);
    802             close();
    803             throw ex;
    804         }
    805     }
    806 
    807     private void openInner() {
    808         synchronized (mLock) {
    809             assert mConnectionPoolLocked == null;
    810             mConnectionPoolLocked = SQLiteConnectionPool.open(mConfigurationLocked);
    811             mCloseGuardLocked.open("close");
    812         }
    813 
    814         synchronized (sActiveDatabases) {
    815             sActiveDatabases.put(this, null);
    816         }
    817     }
    818 
    819     /**
    820      * Create a memory backed SQLite database.  Its contents will be destroyed
    821      * when the database is closed.
    822      *
    823      * <p>Sets the locale of the database to the  the system's current locale.
    824      * Call {@link #setLocale} if you would like something else.</p>
    825      *
    826      * @param factory an optional factory class that is called to instantiate a
    827      *            cursor when query is called
    828      * @return a SQLiteDatabase object, or null if the database can't be created
    829      */
    830     public static SQLiteDatabase create(CursorFactory factory) {
    831         // This is a magic string with special meaning for SQLite.
    832         return openDatabase(SQLiteDatabaseConfiguration.MEMORY_DB_PATH,
    833                 factory, CREATE_IF_NECESSARY);
    834     }
    835 
    836     /**
    837      * Registers a CustomFunction callback as a function that can be called from
    838      * SQLite database triggers.
    839      *
    840      * @param name the name of the sqlite3 function
    841      * @param numArgs the number of arguments for the function
    842      * @param function callback to call when the function is executed
    843      * @hide
    844      */
    845     public void addCustomFunction(String name, int numArgs, CustomFunction function) {
    846         // Create wrapper (also validates arguments).
    847         SQLiteCustomFunction wrapper = new SQLiteCustomFunction(name, numArgs, function);
    848 
    849         synchronized (mLock) {
    850             throwIfNotOpenLocked();
    851 
    852             mConfigurationLocked.customFunctions.add(wrapper);
    853             try {
    854                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
    855             } catch (RuntimeException ex) {
    856                 mConfigurationLocked.customFunctions.remove(wrapper);
    857                 throw ex;
    858             }
    859         }
    860     }
    861 
    862     /**
    863      * Gets the database version.
    864      *
    865      * @return the database version
    866      */
    867     public int getVersion() {
    868         return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
    869     }
    870 
    871     /**
    872      * Sets the database version.
    873      *
    874      * @param version the new database version
    875      */
    876     public void setVersion(int version) {
    877         execSQL("PRAGMA user_version = " + version);
    878     }
    879 
    880     /**
    881      * Returns the maximum size the database may grow to.
    882      *
    883      * @return the new maximum database size
    884      */
    885     public long getMaximumSize() {
    886         long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
    887         return pageCount * getPageSize();
    888     }
    889 
    890     /**
    891      * Sets the maximum size the database will grow to. The maximum size cannot
    892      * be set below the current size.
    893      *
    894      * @param numBytes the maximum database size, in bytes
    895      * @return the new maximum database size
    896      */
    897     public long setMaximumSize(long numBytes) {
    898         long pageSize = getPageSize();
    899         long numPages = numBytes / pageSize;
    900         // If numBytes isn't a multiple of pageSize, bump up a page
    901         if ((numBytes % pageSize) != 0) {
    902             numPages++;
    903         }
    904         long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
    905                 null);
    906         return newPageCount * pageSize;
    907     }
    908 
    909     /**
    910      * Returns the current database page size, in bytes.
    911      *
    912      * @return the database page size, in bytes
    913      */
    914     public long getPageSize() {
    915         return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
    916     }
    917 
    918     /**
    919      * Sets the database page size. The page size must be a power of two. This
    920      * method does not work if any data has been written to the database file,
    921      * and must be called right after the database has been created.
    922      *
    923      * @param numBytes the database page size, in bytes
    924      */
    925     public void setPageSize(long numBytes) {
    926         execSQL("PRAGMA page_size = " + numBytes);
    927     }
    928 
    929     /**
    930      * Mark this table as syncable. When an update occurs in this table the
    931      * _sync_dirty field will be set to ensure proper syncing operation.
    932      *
    933      * @param table the table to mark as syncable
    934      * @param deletedTable The deleted table that corresponds to the
    935      *          syncable table
    936      * @deprecated This method no longer serves any useful purpose and has been deprecated.
    937      */
    938     @Deprecated
    939     public void markTableSyncable(String table, String deletedTable) {
    940     }
    941 
    942     /**
    943      * Mark this table as syncable, with the _sync_dirty residing in another
    944      * table. When an update occurs in this table the _sync_dirty field of the
    945      * row in updateTable with the _id in foreignKey will be set to
    946      * ensure proper syncing operation.
    947      *
    948      * @param table an update on this table will trigger a sync time removal
    949      * @param foreignKey this is the column in table whose value is an _id in
    950      *          updateTable
    951      * @param updateTable this is the table that will have its _sync_dirty
    952      * @deprecated This method no longer serves any useful purpose and has been deprecated.
    953      */
    954     @Deprecated
    955     public void markTableSyncable(String table, String foreignKey, String updateTable) {
    956     }
    957 
    958     /**
    959      * Finds the name of the first table, which is editable.
    960      *
    961      * @param tables a list of tables
    962      * @return the first table listed
    963      */
    964     public static String findEditTable(String tables) {
    965         if (!TextUtils.isEmpty(tables)) {
    966             // find the first word terminated by either a space or a comma
    967             int spacepos = tables.indexOf(' ');
    968             int commapos = tables.indexOf(',');
    969 
    970             if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
    971                 return tables.substring(0, spacepos);
    972             } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
    973                 return tables.substring(0, commapos);
    974             }
    975             return tables;
    976         } else {
    977             throw new IllegalStateException("Invalid tables");
    978         }
    979     }
    980 
    981     /**
    982      * Compiles an SQL statement into a reusable pre-compiled statement object.
    983      * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
    984      * statement and fill in those values with {@link SQLiteProgram#bindString}
    985      * and {@link SQLiteProgram#bindLong} each time you want to run the
    986      * statement. Statements may not return result sets larger than 1x1.
    987      *<p>
    988      * No two threads should be using the same {@link SQLiteStatement} at the same time.
    989      *
    990      * @param sql The raw SQL statement, may contain ? for unknown values to be
    991      *            bound later.
    992      * @return A pre-compiled {@link SQLiteStatement} object. Note that
    993      * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
    994      */
    995     public SQLiteStatement compileStatement(String sql) throws SQLException {
    996         acquireReference();
    997         try {
    998             return new SQLiteStatement(this, sql, null);
    999         } finally {
   1000             releaseReference();
   1001         }
   1002     }
   1003 
   1004     /**
   1005      * Query the given URL, returning a {@link Cursor} over the result set.
   1006      *
   1007      * @param distinct true if you want each row to be unique, false otherwise.
   1008      * @param table The table name to compile the query against.
   1009      * @param columns A list of which columns to return. Passing null will
   1010      *            return all columns, which is discouraged to prevent reading
   1011      *            data from storage that isn't going to be used.
   1012      * @param selection A filter declaring which rows to return, formatted as an
   1013      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1014      *            will return all rows for the given table.
   1015      * @param selectionArgs You may include ?s in selection, which will be
   1016      *         replaced by the values from selectionArgs, in order that they
   1017      *         appear in the selection. The values will be bound as Strings.
   1018      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1019      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1020      *            will cause the rows to not be grouped.
   1021      * @param having A filter declare which row groups to include in the cursor,
   1022      *            if row grouping is being used, formatted as an SQL HAVING
   1023      *            clause (excluding the HAVING itself). Passing null will cause
   1024      *            all row groups to be included, and is required when row
   1025      *            grouping is not being used.
   1026      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1027      *            (excluding the ORDER BY itself). Passing null will use the
   1028      *            default sort order, which may be unordered.
   1029      * @param limit Limits the number of rows returned by the query,
   1030      *            formatted as LIMIT clause. Passing null denotes no LIMIT clause.
   1031      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1032      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1033      * @see Cursor
   1034      */
   1035     public Cursor query(boolean distinct, String table, String[] columns,
   1036             String selection, String[] selectionArgs, String groupBy,
   1037             String having, String orderBy, String limit) {
   1038         return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
   1039                 groupBy, having, orderBy, limit, null);
   1040     }
   1041 
   1042     /**
   1043      * Query the given URL, returning a {@link Cursor} over the result set.
   1044      *
   1045      * @param distinct true if you want each row to be unique, false otherwise.
   1046      * @param table The table name to compile the query against.
   1047      * @param columns A list of which columns to return. Passing null will
   1048      *            return all columns, which is discouraged to prevent reading
   1049      *            data from storage that isn't going to be used.
   1050      * @param selection A filter declaring which rows to return, formatted as an
   1051      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1052      *            will return all rows for the given table.
   1053      * @param selectionArgs You may include ?s in selection, which will be
   1054      *         replaced by the values from selectionArgs, in order that they
   1055      *         appear in the selection. The values will be bound as Strings.
   1056      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1057      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1058      *            will cause the rows to not be grouped.
   1059      * @param having A filter declare which row groups to include in the cursor,
   1060      *            if row grouping is being used, formatted as an SQL HAVING
   1061      *            clause (excluding the HAVING itself). Passing null will cause
   1062      *            all row groups to be included, and is required when row
   1063      *            grouping is not being used.
   1064      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1065      *            (excluding the ORDER BY itself). Passing null will use the
   1066      *            default sort order, which may be unordered.
   1067      * @param limit Limits the number of rows returned by the query,
   1068      *            formatted as LIMIT clause. Passing null denotes no LIMIT clause.
   1069      * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
   1070      * If the operation is canceled, then {@link OperationCanceledException} will be thrown
   1071      * when the query is executed.
   1072      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1073      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1074      * @see Cursor
   1075      */
   1076     public Cursor query(boolean distinct, String table, String[] columns,
   1077             String selection, String[] selectionArgs, String groupBy,
   1078             String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
   1079         return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
   1080                 groupBy, having, orderBy, limit, cancellationSignal);
   1081     }
   1082 
   1083     /**
   1084      * Query the given URL, returning a {@link Cursor} over the result set.
   1085      *
   1086      * @param cursorFactory the cursor factory to use, or null for the default factory
   1087      * @param distinct true if you want each row to be unique, false otherwise.
   1088      * @param table The table name to compile the query against.
   1089      * @param columns A list of which columns to return. Passing null will
   1090      *            return all columns, which is discouraged to prevent reading
   1091      *            data from storage that isn't going to be used.
   1092      * @param selection A filter declaring which rows to return, formatted as an
   1093      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1094      *            will return all rows for the given table.
   1095      * @param selectionArgs You may include ?s in selection, which will be
   1096      *         replaced by the values from selectionArgs, in order that they
   1097      *         appear in the selection. The values will be bound as Strings.
   1098      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1099      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1100      *            will cause the rows to not be grouped.
   1101      * @param having A filter declare which row groups to include in the cursor,
   1102      *            if row grouping is being used, formatted as an SQL HAVING
   1103      *            clause (excluding the HAVING itself). Passing null will cause
   1104      *            all row groups to be included, and is required when row
   1105      *            grouping is not being used.
   1106      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1107      *            (excluding the ORDER BY itself). Passing null will use the
   1108      *            default sort order, which may be unordered.
   1109      * @param limit Limits the number of rows returned by the query,
   1110      *            formatted as LIMIT clause. Passing null denotes no LIMIT clause.
   1111      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1112      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1113      * @see Cursor
   1114      */
   1115     public Cursor queryWithFactory(CursorFactory cursorFactory,
   1116             boolean distinct, String table, String[] columns,
   1117             String selection, String[] selectionArgs, String groupBy,
   1118             String having, String orderBy, String limit) {
   1119         return queryWithFactory(cursorFactory, distinct, table, columns, selection,
   1120                 selectionArgs, groupBy, having, orderBy, limit, null);
   1121     }
   1122 
   1123     /**
   1124      * Query the given URL, returning a {@link Cursor} over the result set.
   1125      *
   1126      * @param cursorFactory the cursor factory to use, or null for the default factory
   1127      * @param distinct true if you want each row to be unique, false otherwise.
   1128      * @param table The table name to compile the query against.
   1129      * @param columns A list of which columns to return. Passing null will
   1130      *            return all columns, which is discouraged to prevent reading
   1131      *            data from storage that isn't going to be used.
   1132      * @param selection A filter declaring which rows to return, formatted as an
   1133      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1134      *            will return all rows for the given table.
   1135      * @param selectionArgs You may include ?s in selection, which will be
   1136      *         replaced by the values from selectionArgs, in order that they
   1137      *         appear in the selection. The values will be bound as Strings.
   1138      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1139      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1140      *            will cause the rows to not be grouped.
   1141      * @param having A filter declare which row groups to include in the cursor,
   1142      *            if row grouping is being used, formatted as an SQL HAVING
   1143      *            clause (excluding the HAVING itself). Passing null will cause
   1144      *            all row groups to be included, and is required when row
   1145      *            grouping is not being used.
   1146      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1147      *            (excluding the ORDER BY itself). Passing null will use the
   1148      *            default sort order, which may be unordered.
   1149      * @param limit Limits the number of rows returned by the query,
   1150      *            formatted as LIMIT clause. Passing null denotes no LIMIT clause.
   1151      * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
   1152      * If the operation is canceled, then {@link OperationCanceledException} will be thrown
   1153      * when the query is executed.
   1154      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1155      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1156      * @see Cursor
   1157      */
   1158     public Cursor queryWithFactory(CursorFactory cursorFactory,
   1159             boolean distinct, String table, String[] columns,
   1160             String selection, String[] selectionArgs, String groupBy,
   1161             String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
   1162         acquireReference();
   1163         try {
   1164             String sql = SQLiteQueryBuilder.buildQueryString(
   1165                     distinct, table, columns, selection, groupBy, having, orderBy, limit);
   1166 
   1167             return rawQueryWithFactory(cursorFactory, sql, selectionArgs,
   1168                     findEditTable(table), cancellationSignal);
   1169         } finally {
   1170             releaseReference();
   1171         }
   1172     }
   1173 
   1174     /**
   1175      * Query the given table, returning a {@link Cursor} over the result set.
   1176      *
   1177      * @param table The table name to compile the query against.
   1178      * @param columns A list of which columns to return. Passing null will
   1179      *            return all columns, which is discouraged to prevent reading
   1180      *            data from storage that isn't going to be used.
   1181      * @param selection A filter declaring which rows to return, formatted as an
   1182      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1183      *            will return all rows for the given table.
   1184      * @param selectionArgs You may include ?s in selection, which will be
   1185      *         replaced by the values from selectionArgs, in order that they
   1186      *         appear in the selection. The values will be bound as Strings.
   1187      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1188      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1189      *            will cause the rows to not be grouped.
   1190      * @param having A filter declare which row groups to include in the cursor,
   1191      *            if row grouping is being used, formatted as an SQL HAVING
   1192      *            clause (excluding the HAVING itself). Passing null will cause
   1193      *            all row groups to be included, and is required when row
   1194      *            grouping is not being used.
   1195      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1196      *            (excluding the ORDER BY itself). Passing null will use the
   1197      *            default sort order, which may be unordered.
   1198      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1199      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1200      * @see Cursor
   1201      */
   1202     public Cursor query(String table, String[] columns, String selection,
   1203             String[] selectionArgs, String groupBy, String having,
   1204             String orderBy) {
   1205 
   1206         return query(false, table, columns, selection, selectionArgs, groupBy,
   1207                 having, orderBy, null /* limit */);
   1208     }
   1209 
   1210     /**
   1211      * Query the given table, returning a {@link Cursor} over the result set.
   1212      *
   1213      * @param table The table name to compile the query against.
   1214      * @param columns A list of which columns to return. Passing null will
   1215      *            return all columns, which is discouraged to prevent reading
   1216      *            data from storage that isn't going to be used.
   1217      * @param selection A filter declaring which rows to return, formatted as an
   1218      *            SQL WHERE clause (excluding the WHERE itself). Passing null
   1219      *            will return all rows for the given table.
   1220      * @param selectionArgs You may include ?s in selection, which will be
   1221      *         replaced by the values from selectionArgs, in order that they
   1222      *         appear in the selection. The values will be bound as Strings.
   1223      * @param groupBy A filter declaring how to group rows, formatted as an SQL
   1224      *            GROUP BY clause (excluding the GROUP BY itself). Passing null
   1225      *            will cause the rows to not be grouped.
   1226      * @param having A filter declare which row groups to include in the cursor,
   1227      *            if row grouping is being used, formatted as an SQL HAVING
   1228      *            clause (excluding the HAVING itself). Passing null will cause
   1229      *            all row groups to be included, and is required when row
   1230      *            grouping is not being used.
   1231      * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
   1232      *            (excluding the ORDER BY itself). Passing null will use the
   1233      *            default sort order, which may be unordered.
   1234      * @param limit Limits the number of rows returned by the query,
   1235      *            formatted as LIMIT clause. Passing null denotes no LIMIT clause.
   1236      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1237      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1238      * @see Cursor
   1239      */
   1240     public Cursor query(String table, String[] columns, String selection,
   1241             String[] selectionArgs, String groupBy, String having,
   1242             String orderBy, String limit) {
   1243 
   1244         return query(false, table, columns, selection, selectionArgs, groupBy,
   1245                 having, orderBy, limit);
   1246     }
   1247 
   1248     /**
   1249      * Runs the provided SQL and returns a {@link Cursor} over the result set.
   1250      *
   1251      * @param sql the SQL query. The SQL string must not be ; terminated
   1252      * @param selectionArgs You may include ?s in where clause in the query,
   1253      *     which will be replaced by the values from selectionArgs. The
   1254      *     values will be bound as Strings.
   1255      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1256      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1257      */
   1258     public Cursor rawQuery(String sql, String[] selectionArgs) {
   1259         return rawQueryWithFactory(null, sql, selectionArgs, null, null);
   1260     }
   1261 
   1262     /**
   1263      * Runs the provided SQL and returns a {@link Cursor} over the result set.
   1264      *
   1265      * @param sql the SQL query. The SQL string must not be ; terminated
   1266      * @param selectionArgs You may include ?s in where clause in the query,
   1267      *     which will be replaced by the values from selectionArgs. The
   1268      *     values will be bound as Strings.
   1269      * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
   1270      * If the operation is canceled, then {@link OperationCanceledException} will be thrown
   1271      * when the query is executed.
   1272      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1273      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1274      */
   1275     public Cursor rawQuery(String sql, String[] selectionArgs,
   1276             CancellationSignal cancellationSignal) {
   1277         return rawQueryWithFactory(null, sql, selectionArgs, null, cancellationSignal);
   1278     }
   1279 
   1280     /**
   1281      * Runs the provided SQL and returns a cursor over the result set.
   1282      *
   1283      * @param cursorFactory the cursor factory to use, or null for the default factory
   1284      * @param sql the SQL query. The SQL string must not be ; terminated
   1285      * @param selectionArgs You may include ?s in where clause in the query,
   1286      *     which will be replaced by the values from selectionArgs. The
   1287      *     values will be bound as Strings.
   1288      * @param editTable the name of the first table, which is editable
   1289      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1290      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1291      */
   1292     public Cursor rawQueryWithFactory(
   1293             CursorFactory cursorFactory, String sql, String[] selectionArgs,
   1294             String editTable) {
   1295         return rawQueryWithFactory(cursorFactory, sql, selectionArgs, editTable, null);
   1296     }
   1297 
   1298     /**
   1299      * Runs the provided SQL and returns a cursor over the result set.
   1300      *
   1301      * @param cursorFactory the cursor factory to use, or null for the default factory
   1302      * @param sql the SQL query. The SQL string must not be ; terminated
   1303      * @param selectionArgs You may include ?s in where clause in the query,
   1304      *     which will be replaced by the values from selectionArgs. The
   1305      *     values will be bound as Strings.
   1306      * @param editTable the name of the first table, which is editable
   1307      * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
   1308      * If the operation is canceled, then {@link OperationCanceledException} will be thrown
   1309      * when the query is executed.
   1310      * @return A {@link Cursor} object, which is positioned before the first entry. Note that
   1311      * {@link Cursor}s are not synchronized, see the documentation for more details.
   1312      */
   1313     public Cursor rawQueryWithFactory(
   1314             CursorFactory cursorFactory, String sql, String[] selectionArgs,
   1315             String editTable, CancellationSignal cancellationSignal) {
   1316         acquireReference();
   1317         try {
   1318             SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, editTable,
   1319                     cancellationSignal);
   1320             return driver.query(cursorFactory != null ? cursorFactory : mCursorFactory,
   1321                     selectionArgs);
   1322         } finally {
   1323             releaseReference();
   1324         }
   1325     }
   1326 
   1327     /**
   1328      * Convenience method for inserting a row into the database.
   1329      *
   1330      * @param table the table to insert the row into
   1331      * @param nullColumnHack optional; may be <code>null</code>.
   1332      *            SQL doesn't allow inserting a completely empty row without
   1333      *            naming at least one column name.  If your provided <code>values</code> is
   1334      *            empty, no column names are known and an empty row can't be inserted.
   1335      *            If not set to null, the <code>nullColumnHack</code> parameter
   1336      *            provides the name of nullable column name to explicitly insert a NULL into
   1337      *            in the case where your <code>values</code> is empty.
   1338      * @param values this map contains the initial column values for the
   1339      *            row. The keys should be the column names and the values the
   1340      *            column values
   1341      * @return the row ID of the newly inserted row, or -1 if an error occurred
   1342      */
   1343     public long insert(String table, String nullColumnHack, ContentValues values) {
   1344         try {
   1345             return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
   1346         } catch (SQLException e) {
   1347             Log.e(TAG, "Error inserting " + values, e);
   1348             return -1;
   1349         }
   1350     }
   1351 
   1352     /**
   1353      * Convenience method for inserting a row into the database.
   1354      *
   1355      * @param table the table to insert the row into
   1356      * @param nullColumnHack optional; may be <code>null</code>.
   1357      *            SQL doesn't allow inserting a completely empty row without
   1358      *            naming at least one column name.  If your provided <code>values</code> is
   1359      *            empty, no column names are known and an empty row can't be inserted.
   1360      *            If not set to null, the <code>nullColumnHack</code> parameter
   1361      *            provides the name of nullable column name to explicitly insert a NULL into
   1362      *            in the case where your <code>values</code> is empty.
   1363      * @param values this map contains the initial column values for the
   1364      *            row. The keys should be the column names and the values the
   1365      *            column values
   1366      * @throws SQLException
   1367      * @return the row ID of the newly inserted row, or -1 if an error occurred
   1368      */
   1369     public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
   1370             throws SQLException {
   1371         return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
   1372     }
   1373 
   1374     /**
   1375      * Convenience method for replacing a row in the database.
   1376      * Inserts a new row if a row does not already exist.
   1377      *
   1378      * @param table the table in which to replace the row
   1379      * @param nullColumnHack optional; may be <code>null</code>.
   1380      *            SQL doesn't allow inserting a completely empty row without
   1381      *            naming at least one column name.  If your provided <code>initialValues</code> is
   1382      *            empty, no column names are known and an empty row can't be inserted.
   1383      *            If not set to null, the <code>nullColumnHack</code> parameter
   1384      *            provides the name of nullable column name to explicitly insert a NULL into
   1385      *            in the case where your <code>initialValues</code> is empty.
   1386      * @param initialValues this map contains the initial column values for
   1387      *   the row. The keys should be the column names and the values the column values.
   1388      * @return the row ID of the newly inserted row, or -1 if an error occurred
   1389      */
   1390     public long replace(String table, String nullColumnHack, ContentValues initialValues) {
   1391         try {
   1392             return insertWithOnConflict(table, nullColumnHack, initialValues,
   1393                     CONFLICT_REPLACE);
   1394         } catch (SQLException e) {
   1395             Log.e(TAG, "Error inserting " + initialValues, e);
   1396             return -1;
   1397         }
   1398     }
   1399 
   1400     /**
   1401      * Convenience method for replacing a row in the database.
   1402      * Inserts a new row if a row does not already exist.
   1403      *
   1404      * @param table the table in which to replace the row
   1405      * @param nullColumnHack optional; may be <code>null</code>.
   1406      *            SQL doesn't allow inserting a completely empty row without
   1407      *            naming at least one column name.  If your provided <code>initialValues</code> is
   1408      *            empty, no column names are known and an empty row can't be inserted.
   1409      *            If not set to null, the <code>nullColumnHack</code> parameter
   1410      *            provides the name of nullable column name to explicitly insert a NULL into
   1411      *            in the case where your <code>initialValues</code> is empty.
   1412      * @param initialValues this map contains the initial column values for
   1413      *   the row. The keys should be the column names and the values the column values.
   1414      * @throws SQLException
   1415      * @return the row ID of the newly inserted row, or -1 if an error occurred
   1416      */
   1417     public long replaceOrThrow(String table, String nullColumnHack,
   1418             ContentValues initialValues) throws SQLException {
   1419         return insertWithOnConflict(table, nullColumnHack, initialValues,
   1420                 CONFLICT_REPLACE);
   1421     }
   1422 
   1423     /**
   1424      * General method for inserting a row into the database.
   1425      *
   1426      * @param table the table to insert the row into
   1427      * @param nullColumnHack optional; may be <code>null</code>.
   1428      *            SQL doesn't allow inserting a completely empty row without
   1429      *            naming at least one column name.  If your provided <code>initialValues</code> is
   1430      *            empty, no column names are known and an empty row can't be inserted.
   1431      *            If not set to null, the <code>nullColumnHack</code> parameter
   1432      *            provides the name of nullable column name to explicitly insert a NULL into
   1433      *            in the case where your <code>initialValues</code> is empty.
   1434      * @param initialValues this map contains the initial column values for the
   1435      *            row. The keys should be the column names and the values the
   1436      *            column values
   1437      * @param conflictAlgorithm for insert conflict resolver
   1438      * @return the row ID of the newly inserted row OR <code>-1</code> if either the
   1439      *            input parameter <code>conflictAlgorithm</code> = {@link #CONFLICT_IGNORE}
   1440      *            or an error occurred.
   1441      */
   1442     public long insertWithOnConflict(String table, String nullColumnHack,
   1443             ContentValues initialValues, int conflictAlgorithm) {
   1444         acquireReference();
   1445         try {
   1446             StringBuilder sql = new StringBuilder();
   1447             sql.append("INSERT");
   1448             sql.append(CONFLICT_VALUES[conflictAlgorithm]);
   1449             sql.append(" INTO ");
   1450             sql.append(table);
   1451             sql.append('(');
   1452 
   1453             Object[] bindArgs = null;
   1454             int size = (initialValues != null && initialValues.size() > 0)
   1455                     ? initialValues.size() : 0;
   1456             if (size > 0) {
   1457                 bindArgs = new Object[size];
   1458                 int i = 0;
   1459                 for (String colName : initialValues.keySet()) {
   1460                     sql.append((i > 0) ? "," : "");
   1461                     sql.append(colName);
   1462                     bindArgs[i++] = initialValues.get(colName);
   1463                 }
   1464                 sql.append(')');
   1465                 sql.append(" VALUES (");
   1466                 for (i = 0; i < size; i++) {
   1467                     sql.append((i > 0) ? ",?" : "?");
   1468                 }
   1469             } else {
   1470                 sql.append(nullColumnHack + ") VALUES (NULL");
   1471             }
   1472             sql.append(')');
   1473 
   1474             SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
   1475             try {
   1476                 return statement.executeInsert();
   1477             } finally {
   1478                 statement.close();
   1479             }
   1480         } finally {
   1481             releaseReference();
   1482         }
   1483     }
   1484 
   1485     /**
   1486      * Convenience method for deleting rows in the database.
   1487      *
   1488      * @param table the table to delete from
   1489      * @param whereClause the optional WHERE clause to apply when deleting.
   1490      *            Passing null will delete all rows.
   1491      * @param whereArgs You may include ?s in the where clause, which
   1492      *            will be replaced by the values from whereArgs. The values
   1493      *            will be bound as Strings.
   1494      * @return the number of rows affected if a whereClause is passed in, 0
   1495      *         otherwise. To remove all rows and get a count pass "1" as the
   1496      *         whereClause.
   1497      */
   1498     public int delete(String table, String whereClause, String[] whereArgs) {
   1499         acquireReference();
   1500         try {
   1501             SQLiteStatement statement =  new SQLiteStatement(this, "DELETE FROM " + table +
   1502                     (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
   1503             try {
   1504                 return statement.executeUpdateDelete();
   1505             } finally {
   1506                 statement.close();
   1507             }
   1508         } finally {
   1509             releaseReference();
   1510         }
   1511     }
   1512 
   1513     /**
   1514      * Convenience method for updating rows in the database.
   1515      *
   1516      * @param table the table to update in
   1517      * @param values a map from column names to new column values. null is a
   1518      *            valid value that will be translated to NULL.
   1519      * @param whereClause the optional WHERE clause to apply when updating.
   1520      *            Passing null will update all rows.
   1521      * @param whereArgs You may include ?s in the where clause, which
   1522      *            will be replaced by the values from whereArgs. The values
   1523      *            will be bound as Strings.
   1524      * @return the number of rows affected
   1525      */
   1526     public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
   1527         return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
   1528     }
   1529 
   1530     /**
   1531      * Convenience method for updating rows in the database.
   1532      *
   1533      * @param table the table to update in
   1534      * @param values a map from column names to new column values. null is a
   1535      *            valid value that will be translated to NULL.
   1536      * @param whereClause the optional WHERE clause to apply when updating.
   1537      *            Passing null will update all rows.
   1538      * @param whereArgs You may include ?s in the where clause, which
   1539      *            will be replaced by the values from whereArgs. The values
   1540      *            will be bound as Strings.
   1541      * @param conflictAlgorithm for update conflict resolver
   1542      * @return the number of rows affected
   1543      */
   1544     public int updateWithOnConflict(String table, ContentValues values,
   1545             String whereClause, String[] whereArgs, int conflictAlgorithm) {
   1546         if (values == null || values.size() == 0) {
   1547             throw new IllegalArgumentException("Empty values");
   1548         }
   1549 
   1550         acquireReference();
   1551         try {
   1552             StringBuilder sql = new StringBuilder(120);
   1553             sql.append("UPDATE ");
   1554             sql.append(CONFLICT_VALUES[conflictAlgorithm]);
   1555             sql.append(table);
   1556             sql.append(" SET ");
   1557 
   1558             // move all bind args to one array
   1559             int setValuesSize = values.size();
   1560             int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
   1561             Object[] bindArgs = new Object[bindArgsSize];
   1562             int i = 0;
   1563             for (String colName : values.keySet()) {
   1564                 sql.append((i > 0) ? "," : "");
   1565                 sql.append(colName);
   1566                 bindArgs[i++] = values.get(colName);
   1567                 sql.append("=?");
   1568             }
   1569             if (whereArgs != null) {
   1570                 for (i = setValuesSize; i < bindArgsSize; i++) {
   1571                     bindArgs[i] = whereArgs[i - setValuesSize];
   1572                 }
   1573             }
   1574             if (!TextUtils.isEmpty(whereClause)) {
   1575                 sql.append(" WHERE ");
   1576                 sql.append(whereClause);
   1577             }
   1578 
   1579             SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
   1580             try {
   1581                 return statement.executeUpdateDelete();
   1582             } finally {
   1583                 statement.close();
   1584             }
   1585         } finally {
   1586             releaseReference();
   1587         }
   1588     }
   1589 
   1590     /**
   1591      * Execute a single SQL statement that is NOT a SELECT
   1592      * or any other SQL statement that returns data.
   1593      * <p>
   1594      * It has no means to return any data (such as the number of affected rows).
   1595      * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
   1596      * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
   1597      * </p>
   1598      * <p>
   1599      * When using {@link #enableWriteAheadLogging()}, journal_mode is
   1600      * automatically managed by this class. So, do not set journal_mode
   1601      * using "PRAGMA journal_mode'<value>" statement if your app is using
   1602      * {@link #enableWriteAheadLogging()}
   1603      * </p>
   1604      *
   1605      * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
   1606      * not supported.
   1607      * @throws SQLException if the SQL string is invalid
   1608      */
   1609     public void execSQL(String sql) throws SQLException {
   1610         executeSql(sql, null);
   1611     }
   1612 
   1613     /**
   1614      * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
   1615      * <p>
   1616      * For INSERT statements, use any of the following instead.
   1617      * <ul>
   1618      *   <li>{@link #insert(String, String, ContentValues)}</li>
   1619      *   <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
   1620      *   <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
   1621      * </ul>
   1622      * <p>
   1623      * For UPDATE statements, use any of the following instead.
   1624      * <ul>
   1625      *   <li>{@link #update(String, ContentValues, String, String[])}</li>
   1626      *   <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
   1627      * </ul>
   1628      * <p>
   1629      * For DELETE statements, use any of the following instead.
   1630      * <ul>
   1631      *   <li>{@link #delete(String, String, String[])}</li>
   1632      * </ul>
   1633      * <p>
   1634      * For example, the following are good candidates for using this method:
   1635      * <ul>
   1636      *   <li>ALTER TABLE</li>
   1637      *   <li>CREATE or DROP table / trigger / view / index / virtual table</li>
   1638      *   <li>REINDEX</li>
   1639      *   <li>RELEASE</li>
   1640      *   <li>SAVEPOINT</li>
   1641      *   <li>PRAGMA that returns no data</li>
   1642      * </ul>
   1643      * </p>
   1644      * <p>
   1645      * When using {@link #enableWriteAheadLogging()}, journal_mode is
   1646      * automatically managed by this class. So, do not set journal_mode
   1647      * using "PRAGMA journal_mode'<value>" statement if your app is using
   1648      * {@link #enableWriteAheadLogging()}
   1649      * </p>
   1650      *
   1651      * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
   1652      * not supported.
   1653      * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
   1654      * @throws SQLException if the SQL string is invalid
   1655      */
   1656     public void execSQL(String sql, Object[] bindArgs) throws SQLException {
   1657         if (bindArgs == null) {
   1658             throw new IllegalArgumentException("Empty bindArgs");
   1659         }
   1660         executeSql(sql, bindArgs);
   1661     }
   1662 
   1663     private int executeSql(String sql, Object[] bindArgs) throws SQLException {
   1664         acquireReference();
   1665         try {
   1666             if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
   1667                 boolean disableWal = false;
   1668                 synchronized (mLock) {
   1669                     if (!mHasAttachedDbsLocked) {
   1670                         mHasAttachedDbsLocked = true;
   1671                         disableWal = true;
   1672                     }
   1673                 }
   1674                 if (disableWal) {
   1675                     disableWriteAheadLogging();
   1676                 }
   1677             }
   1678 
   1679             SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
   1680             try {
   1681                 return statement.executeUpdateDelete();
   1682             } finally {
   1683                 statement.close();
   1684             }
   1685         } finally {
   1686             releaseReference();
   1687         }
   1688     }
   1689 
   1690     /**
   1691      * Verifies that a SQL SELECT statement is valid by compiling it.
   1692      * If the SQL statement is not valid, this method will throw a {@link SQLiteException}.
   1693      *
   1694      * @param sql SQL to be validated
   1695      * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
   1696      * If the operation is canceled, then {@link OperationCanceledException} will be thrown
   1697      * when the query is executed.
   1698      * @throws SQLiteException if {@code sql} is invalid
   1699      */
   1700     public void validateSql(String sql, CancellationSignal cancellationSignal) {
   1701         getThreadSession().prepare(sql,
   1702                 getThreadDefaultConnectionFlags(/* readOnly =*/ true), cancellationSignal, null);
   1703     }
   1704 
   1705     /**
   1706      * Returns true if the database is opened as read only.
   1707      *
   1708      * @return True if database is opened as read only.
   1709      */
   1710     public boolean isReadOnly() {
   1711         synchronized (mLock) {
   1712             return isReadOnlyLocked();
   1713         }
   1714     }
   1715 
   1716     private boolean isReadOnlyLocked() {
   1717         return (mConfigurationLocked.openFlags & OPEN_READ_MASK) == OPEN_READONLY;
   1718     }
   1719 
   1720     /**
   1721      * Returns true if the database is in-memory db.
   1722      *
   1723      * @return True if the database is in-memory.
   1724      * @hide
   1725      */
   1726     public boolean isInMemoryDatabase() {
   1727         synchronized (mLock) {
   1728             return mConfigurationLocked.isInMemoryDb();
   1729         }
   1730     }
   1731 
   1732     /**
   1733      * Returns true if the database is currently open.
   1734      *
   1735      * @return True if the database is currently open (has not been closed).
   1736      */
   1737     public boolean isOpen() {
   1738         synchronized (mLock) {
   1739             return mConnectionPoolLocked != null;
   1740         }
   1741     }
   1742 
   1743     /**
   1744      * Returns true if the new version code is greater than the current database version.
   1745      *
   1746      * @param newVersion The new version code.
   1747      * @return True if the new version code is greater than the current database version. 
   1748      */
   1749     public boolean needUpgrade(int newVersion) {
   1750         return newVersion > getVersion();
   1751     }
   1752 
   1753     /**
   1754      * Gets the path to the database file.
   1755      *
   1756      * @return The path to the database file.
   1757      */
   1758     public final String getPath() {
   1759         synchronized (mLock) {
   1760             return mConfigurationLocked.path;
   1761         }
   1762     }
   1763 
   1764     /**
   1765      * Sets the locale for this database.  Does nothing if this database has
   1766      * the {@link #NO_LOCALIZED_COLLATORS} flag set or was opened read only.
   1767      *
   1768      * @param locale The new locale.
   1769      *
   1770      * @throws SQLException if the locale could not be set.  The most common reason
   1771      * for this is that there is no collator available for the locale you requested.
   1772      * In this case the database remains unchanged.
   1773      */
   1774     public void setLocale(Locale locale) {
   1775         if (locale == null) {
   1776             throw new IllegalArgumentException("locale must not be null.");
   1777         }
   1778 
   1779         synchronized (mLock) {
   1780             throwIfNotOpenLocked();
   1781 
   1782             final Locale oldLocale = mConfigurationLocked.locale;
   1783             mConfigurationLocked.locale = locale;
   1784             try {
   1785                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
   1786             } catch (RuntimeException ex) {
   1787                 mConfigurationLocked.locale = oldLocale;
   1788                 throw ex;
   1789             }
   1790         }
   1791     }
   1792 
   1793     /**
   1794      * Sets the maximum size of the prepared-statement cache for this database.
   1795      * (size of the cache = number of compiled-sql-statements stored in the cache).
   1796      *<p>
   1797      * Maximum cache size can ONLY be increased from its current size (default = 10).
   1798      * If this method is called with smaller size than the current maximum value,
   1799      * then IllegalStateException is thrown.
   1800      *<p>
   1801      * This method is thread-safe.
   1802      *
   1803      * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
   1804      * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE}.
   1805      */
   1806     public void setMaxSqlCacheSize(int cacheSize) {
   1807         if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
   1808             throw new IllegalStateException(
   1809                     "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
   1810         }
   1811 
   1812         synchronized (mLock) {
   1813             throwIfNotOpenLocked();
   1814 
   1815             final int oldMaxSqlCacheSize = mConfigurationLocked.maxSqlCacheSize;
   1816             mConfigurationLocked.maxSqlCacheSize = cacheSize;
   1817             try {
   1818                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
   1819             } catch (RuntimeException ex) {
   1820                 mConfigurationLocked.maxSqlCacheSize = oldMaxSqlCacheSize;
   1821                 throw ex;
   1822             }
   1823         }
   1824     }
   1825 
   1826     /**
   1827      * Sets whether foreign key constraints are enabled for the database.
   1828      * <p>
   1829      * By default, foreign key constraints are not enforced by the database.
   1830      * This method allows an application to enable foreign key constraints.
   1831      * It must be called each time the database is opened to ensure that foreign
   1832      * key constraints are enabled for the session.
   1833      * </p><p>
   1834      * A good time to call this method is right after calling {@link #openOrCreateDatabase}
   1835      * or in the {@link SQLiteOpenHelper#onConfigure} callback.
   1836      * </p><p>
   1837      * When foreign key constraints are disabled, the database does not check whether
   1838      * changes to the database will violate foreign key constraints.  Likewise, when
   1839      * foreign key constraints are disabled, the database will not execute cascade
   1840      * delete or update triggers.  As a result, it is possible for the database
   1841      * state to become inconsistent.  To perform a database integrity check,
   1842      * call {@link #isDatabaseIntegrityOk}.
   1843      * </p><p>
   1844      * This method must not be called while a transaction is in progress.
   1845      * </p><p>
   1846      * See also <a href="http://sqlite.org/foreignkeys.html">SQLite Foreign Key Constraints</a>
   1847      * for more details about foreign key constraint support.
   1848      * </p>
   1849      *
   1850      * @param enable True to enable foreign key constraints, false to disable them.
   1851      *
   1852      * @throws IllegalStateException if the are transactions is in progress
   1853      * when this method is called.
   1854      */
   1855     public void setForeignKeyConstraintsEnabled(boolean enable) {
   1856         synchronized (mLock) {
   1857             throwIfNotOpenLocked();
   1858 
   1859             if (mConfigurationLocked.foreignKeyConstraintsEnabled == enable) {
   1860                 return;
   1861             }
   1862 
   1863             mConfigurationLocked.foreignKeyConstraintsEnabled = enable;
   1864             try {
   1865                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
   1866             } catch (RuntimeException ex) {
   1867                 mConfigurationLocked.foreignKeyConstraintsEnabled = !enable;
   1868                 throw ex;
   1869             }
   1870         }
   1871     }
   1872 
   1873     /**
   1874      * This method enables parallel execution of queries from multiple threads on the
   1875      * same database.  It does this by opening multiple connections to the database
   1876      * and using a different database connection for each query.  The database
   1877      * journal mode is also changed to enable writes to proceed concurrently with reads.
   1878      * <p>
   1879      * When write-ahead logging is not enabled (the default), it is not possible for
   1880      * reads and writes to occur on the database at the same time.  Before modifying the
   1881      * database, the writer implicitly acquires an exclusive lock on the database which
   1882      * prevents readers from accessing the database until the write is completed.
   1883      * </p><p>
   1884      * In contrast, when write-ahead logging is enabled (by calling this method), write
   1885      * operations occur in a separate log file which allows reads to proceed concurrently.
   1886      * While a write is in progress, readers on other threads will perceive the state
   1887      * of the database as it was before the write began.  When the write completes, readers
   1888      * on other threads will then perceive the new state of the database.
   1889      * </p><p>
   1890      * It is a good idea to enable write-ahead logging whenever a database will be
   1891      * concurrently accessed and modified by multiple threads at the same time.
   1892      * However, write-ahead logging uses significantly more memory than ordinary
   1893      * journaling because there are multiple connections to the same database.
   1894      * So if a database will only be used by a single thread, or if optimizing
   1895      * concurrency is not very important, then write-ahead logging should be disabled.
   1896      * </p><p>
   1897      * After calling this method, execution of queries in parallel is enabled as long as
   1898      * the database remains open.  To disable execution of queries in parallel, either
   1899      * call {@link #disableWriteAheadLogging} or close the database and reopen it.
   1900      * </p><p>
   1901      * The maximum number of connections used to execute queries in parallel is
   1902      * dependent upon the device memory and possibly other properties.
   1903      * </p><p>
   1904      * If a query is part of a transaction, then it is executed on the same database handle the
   1905      * transaction was begun.
   1906      * </p><p>
   1907      * Writers should use {@link #beginTransactionNonExclusive()} or
   1908      * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
   1909      * to start a transaction.  Non-exclusive mode allows database file to be in readable
   1910      * by other threads executing queries.
   1911      * </p><p>
   1912      * If the database has any attached databases, then execution of queries in parallel is NOT
   1913      * possible.  Likewise, write-ahead logging is not supported for read-only databases
   1914      * or memory databases.  In such cases, {@link #enableWriteAheadLogging} returns false.
   1915      * </p><p>
   1916      * The best way to enable write-ahead logging is to pass the
   1917      * {@link #ENABLE_WRITE_AHEAD_LOGGING} flag to {@link #openDatabase}.  This is
   1918      * more efficient than calling {@link #enableWriteAheadLogging}.
   1919      * <code><pre>
   1920      *     SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
   1921      *             SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
   1922      *             myDatabaseErrorHandler);
   1923      *     db.enableWriteAheadLogging();
   1924      * </pre></code>
   1925      * </p><p>
   1926      * Another way to enable write-ahead logging is to call {@link #enableWriteAheadLogging}
   1927      * after opening the database.
   1928      * <code><pre>
   1929      *     SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
   1930      *             SQLiteDatabase.CREATE_IF_NECESSARY, myDatabaseErrorHandler);
   1931      *     db.enableWriteAheadLogging();
   1932      * </pre></code>
   1933      * </p><p>
   1934      * See also <a href="http://sqlite.org/wal.html">SQLite Write-Ahead Logging</a> for
   1935      * more details about how write-ahead logging works.
   1936      * </p>
   1937      *
   1938      * @return True if write-ahead logging is enabled.
   1939      *
   1940      * @throws IllegalStateException if there are transactions in progress at the
   1941      * time this method is called.  WAL mode can only be changed when there are no
   1942      * transactions in progress.
   1943      *
   1944      * @see #ENABLE_WRITE_AHEAD_LOGGING
   1945      * @see #disableWriteAheadLogging
   1946      */
   1947     public boolean enableWriteAheadLogging() {
   1948         synchronized (mLock) {
   1949             throwIfNotOpenLocked();
   1950 
   1951             if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0) {
   1952                 return true;
   1953             }
   1954 
   1955             if (isReadOnlyLocked()) {
   1956                 // WAL doesn't make sense for readonly-databases.
   1957                 // TODO: True, but connection pooling does still make sense...
   1958                 return false;
   1959             }
   1960 
   1961             if (mConfigurationLocked.isInMemoryDb()) {
   1962                 Log.i(TAG, "can't enable WAL for memory databases.");
   1963                 return false;
   1964             }
   1965 
   1966             // make sure this database has NO attached databases because sqlite's write-ahead-logging
   1967             // doesn't work for databases with attached databases
   1968             if (mHasAttachedDbsLocked) {
   1969                 if (Log.isLoggable(TAG, Log.DEBUG)) {
   1970                     Log.d(TAG, "this database: " + mConfigurationLocked.label
   1971                             + " has attached databases. can't  enable WAL.");
   1972                 }
   1973                 return false;
   1974             }
   1975 
   1976             mConfigurationLocked.openFlags |= ENABLE_WRITE_AHEAD_LOGGING;
   1977             try {
   1978                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
   1979             } catch (RuntimeException ex) {
   1980                 mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
   1981                 throw ex;
   1982             }
   1983         }
   1984         return true;
   1985     }
   1986 
   1987     /**
   1988      * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
   1989      *
   1990      * @throws IllegalStateException if there are transactions in progress at the
   1991      * time this method is called.  WAL mode can only be changed when there are no
   1992      * transactions in progress.
   1993      *
   1994      * @see #enableWriteAheadLogging
   1995      */
   1996     public void disableWriteAheadLogging() {
   1997         synchronized (mLock) {
   1998             throwIfNotOpenLocked();
   1999 
   2000             if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) == 0) {
   2001                 return;
   2002             }
   2003 
   2004             mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
   2005             try {
   2006                 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
   2007             } catch (RuntimeException ex) {
   2008                 mConfigurationLocked.openFlags |= ENABLE_WRITE_AHEAD_LOGGING;
   2009                 throw ex;
   2010             }
   2011         }
   2012     }
   2013 
   2014     /**
   2015      * Returns true if write-ahead logging has been enabled for this database.
   2016      *
   2017      * @return True if write-ahead logging has been enabled for this database.
   2018      *
   2019      * @see #enableWriteAheadLogging
   2020      * @see #ENABLE_WRITE_AHEAD_LOGGING
   2021      */
   2022     public boolean isWriteAheadLoggingEnabled() {
   2023         synchronized (mLock) {
   2024             throwIfNotOpenLocked();
   2025 
   2026             return (mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0;
   2027         }
   2028     }
   2029 
   2030     /**
   2031      * Collect statistics about all open databases in the current process.
   2032      * Used by bug report.
   2033      */
   2034     static ArrayList<DbStats> getDbStats() {
   2035         ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
   2036         for (SQLiteDatabase db : getActiveDatabases()) {
   2037             db.collectDbStats(dbStatsList);
   2038         }
   2039         return dbStatsList;
   2040     }
   2041 
   2042     private void collectDbStats(ArrayList<DbStats> dbStatsList) {
   2043         synchronized (mLock) {
   2044             if (mConnectionPoolLocked != null) {
   2045                 mConnectionPoolLocked.collectDbStats(dbStatsList);
   2046             }
   2047         }
   2048     }
   2049 
   2050     private static ArrayList<SQLiteDatabase> getActiveDatabases() {
   2051         ArrayList<SQLiteDatabase> databases = new ArrayList<SQLiteDatabase>();
   2052         synchronized (sActiveDatabases) {
   2053             databases.addAll(sActiveDatabases.keySet());
   2054         }
   2055         return databases;
   2056     }
   2057 
   2058     /**
   2059      * Dump detailed information about all open databases in the current process.
   2060      * Used by bug report.
   2061      */
   2062     static void dumpAll(Printer printer, boolean verbose) {
   2063         for (SQLiteDatabase db : getActiveDatabases()) {
   2064             db.dump(printer, verbose);
   2065         }
   2066     }
   2067 
   2068     private void dump(Printer printer, boolean verbose) {
   2069         synchronized (mLock) {
   2070             if (mConnectionPoolLocked != null) {
   2071                 printer.println("");
   2072                 mConnectionPoolLocked.dump(printer, verbose);
   2073             }
   2074         }
   2075     }
   2076 
   2077     /**
   2078      * Returns list of full pathnames of all attached databases including the main database
   2079      * by executing 'pragma database_list' on the database.
   2080      *
   2081      * @return ArrayList of pairs of (database name, database file path) or null if the database
   2082      * is not open.
   2083      */
   2084     public List<Pair<String, String>> getAttachedDbs() {
   2085         ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
   2086         synchronized (mLock) {
   2087             if (mConnectionPoolLocked == null) {
   2088                 return null; // not open
   2089             }
   2090 
   2091             if (!mHasAttachedDbsLocked) {
   2092                 // No attached databases.
   2093                 // There is a small window where attached databases exist but this flag is not
   2094                 // set yet.  This can occur when this thread is in a race condition with another
   2095                 // thread that is executing the SQL statement: "attach database <blah> as <foo>"
   2096                 // If this thread is NOT ok with such a race condition (and thus possibly not
   2097                 // receivethe entire list of attached databases), then the caller should ensure
   2098                 // that no thread is executing any SQL statements while a thread is calling this
   2099                 // method.  Typically, this method is called when 'adb bugreport' is done or the
   2100                 // caller wants to collect stats on the database and all its attached databases.
   2101                 attachedDbs.add(new Pair<String, String>("main", mConfigurationLocked.path));
   2102                 return attachedDbs;
   2103             }
   2104 
   2105             acquireReference();
   2106         }
   2107 
   2108         try {
   2109             // has attached databases. query sqlite to get the list of attached databases.
   2110             Cursor c = null;
   2111             try {
   2112                 c = rawQuery("pragma database_list;", null);
   2113                 while (c.moveToNext()) {
   2114                     // sqlite returns a row for each database in the returned list of databases.
   2115                     //   in each row,
   2116                     //       1st column is the database name such as main, or the database
   2117                     //                              name specified on the "ATTACH" command
   2118                     //       2nd column is the database file path.
   2119                     attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
   2120                 }
   2121             } finally {
   2122                 if (c != null) {
   2123                     c.close();
   2124                 }
   2125             }
   2126             return attachedDbs;
   2127         } finally {
   2128             releaseReference();
   2129         }
   2130     }
   2131 
   2132     /**
   2133      * Runs 'pragma integrity_check' on the given database (and all the attached databases)
   2134      * and returns true if the given database (and all its attached databases) pass integrity_check,
   2135      * false otherwise.
   2136      *<p>
   2137      * If the result is false, then this method logs the errors reported by the integrity_check
   2138      * command execution.
   2139      *<p>
   2140      * Note that 'pragma integrity_check' on a database can take a long time.
   2141      *
   2142      * @return true if the given database (and all its attached databases) pass integrity_check,
   2143      * false otherwise.
   2144      */
   2145     public boolean isDatabaseIntegrityOk() {
   2146         acquireReference();
   2147         try {
   2148             List<Pair<String, String>> attachedDbs = null;
   2149             try {
   2150                 attachedDbs = getAttachedDbs();
   2151                 if (attachedDbs == null) {
   2152                     throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
   2153                             "be retrieved. probably because the database is closed");
   2154                 }
   2155             } catch (SQLiteException e) {
   2156                 // can't get attachedDb list. do integrity check on the main database
   2157                 attachedDbs = new ArrayList<Pair<String, String>>();
   2158                 attachedDbs.add(new Pair<String, String>("main", getPath()));
   2159             }
   2160 
   2161             for (int i = 0; i < attachedDbs.size(); i++) {
   2162                 Pair<String, String> p = attachedDbs.get(i);
   2163                 SQLiteStatement prog = null;
   2164                 try {
   2165                     prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
   2166                     String rslt = prog.simpleQueryForString();
   2167                     if (!rslt.equalsIgnoreCase("ok")) {
   2168                         // integrity_checker failed on main or attached databases
   2169                         Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
   2170                         return false;
   2171                     }
   2172                 } finally {
   2173                     if (prog != null) prog.close();
   2174                 }
   2175             }
   2176         } finally {
   2177             releaseReference();
   2178         }
   2179         return true;
   2180     }
   2181 
   2182     @Override
   2183     public String toString() {
   2184         return "SQLiteDatabase: " + getPath();
   2185     }
   2186 
   2187     private void throwIfNotOpenLocked() {
   2188         if (mConnectionPoolLocked == null) {
   2189             throw new IllegalStateException("The database '" + mConfigurationLocked.label
   2190                     + "' is not open.");
   2191         }
   2192     }
   2193 
   2194     /**
   2195      * Used to allow returning sub-classes of {@link Cursor} when calling query.
   2196      */
   2197     public interface CursorFactory {
   2198         /**
   2199          * See {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
   2200          */
   2201         public Cursor newCursor(SQLiteDatabase db,
   2202                 SQLiteCursorDriver masterQuery, String editTable,
   2203                 SQLiteQuery query);
   2204     }
   2205 
   2206     /**
   2207      * A callback interface for a custom sqlite3 function.
   2208      * This can be used to create a function that can be called from
   2209      * sqlite3 database triggers.
   2210      * @hide
   2211      */
   2212     public interface CustomFunction {
   2213         public void callback(String[] args);
   2214     }
   2215 
   2216     public static boolean hasCodec() {
   2217       return SQLiteConnection.hasCodec();
   2218     }
   2219 
   2220     public void enableLocalizedCollators() {
   2221       mConnectionPoolLocked.enableLocalizedCollators();
   2222     }
   2223 }