/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.database.sqlite; import android.app.AppGlobals; import android.content.ContentValues; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseErrorHandler; import android.database.DatabaseUtils; import android.database.DefaultDatabaseErrorHandler; import android.database.SQLException; import android.database.sqlite.SQLiteDebug.DbStats; import android.os.Debug; import android.os.StatFs; import android.os.SystemClock; import android.os.SystemProperties; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; import android.util.LruCache; import android.util.Pair; import dalvik.system.BlockGuard; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; /** * Exposes methods to manage a SQLite database. *
SQLiteDatabase has methods to create, delete, execute SQL commands, and * perform other common database management tasks. *
See the Notepad sample application in the SDK for an example of creating * and managing a database. *
Database names must be unique within an application, not across all * applications. * *
In addition to SQLite's default
* Transactions can be nested.
* When the outer transaction is ended all of
* the work done in that transaction and all of the nested transactions will be committed or
* rolled back. The changes will be rolled back if any transaction is ended without being
* marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
* Here is the standard idiom for transactions:
*
*
* Here is the standard idiom for transactions:
*
*
* Transactions can be nested.
* When the outer transaction is ended all of
* the work done in that transaction and all of the nested transactions will be committed or
* rolled back. The changes will be rolled back if any transaction is ended without being
* marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
* Here is the standard idiom for transactions:
*
*
* Here is the standard idiom for transactions:
*
*
* Caller is part of the current transaction if either of the following is true
* Sets the locale of the database to the the system's current locale.
* Call {@link #setLocale} if you would like something else. Sets the locale of the database to the the system's current locale.
* Call {@link #setLocale} if you would like something else. Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
* used to handle corruption when sqlite reports database corruption. Sets the locale of the database to the the system's current locale.
* Call {@link #setLocale} if you would like something else.
* No two threads should be using the same {@link SQLiteStatement} at the same time.
*
* @param sql The raw SQL statement, may contain ? for unknown values to be
* bound later.
* @return A pre-compiled {@link SQLiteStatement} object. Note that
* {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
*/
public SQLiteStatement compileStatement(String sql) throws SQLException {
verifyDbIsOpen();
return new SQLiteStatement(this, sql, null);
}
/**
* Query the given URL, returning a {@link Cursor} over the result set.
*
* @param distinct true if you want each row to be unique, false otherwise.
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading
* data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they
* appear in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the cursor,
* if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause
* all row groups to be included, and is required when row
* grouping is not being used.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @param limit Limits the number of rows returned by the query,
* formatted as LIMIT clause. Passing null denotes no LIMIT clause.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
* @see Cursor
*/
public Cursor query(boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit) {
return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
}
/**
* Query the given URL, returning a {@link Cursor} over the result set.
*
* @param cursorFactory the cursor factory to use, or null for the default factory
* @param distinct true if you want each row to be unique, false otherwise.
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading
* data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they
* appear in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the cursor,
* if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause
* all row groups to be included, and is required when row
* grouping is not being used.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @param limit Limits the number of rows returned by the query,
* formatted as LIMIT clause. Passing null denotes no LIMIT clause.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
* @see Cursor
*/
public Cursor queryWithFactory(CursorFactory cursorFactory,
boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit) {
verifyDbIsOpen();
String sql = SQLiteQueryBuilder.buildQueryString(
distinct, table, columns, selection, groupBy, having, orderBy, limit);
return rawQueryWithFactory(
cursorFactory, sql, selectionArgs, findEditTable(table));
}
/**
* Query the given table, returning a {@link Cursor} over the result set.
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading
* data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they
* appear in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the cursor,
* if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause
* all row groups to be included, and is required when row
* grouping is not being used.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
* @see Cursor
*/
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy) {
return query(false, table, columns, selection, selectionArgs, groupBy,
having, orderBy, null /* limit */);
}
/**
* Query the given table, returning a {@link Cursor} over the result set.
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading
* data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they
* appear in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the cursor,
* if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause
* all row groups to be included, and is required when row
* grouping is not being used.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @param limit Limits the number of rows returned by the query,
* formatted as LIMIT clause. Passing null denotes no LIMIT clause.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
* @see Cursor
*/
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) {
return query(false, table, columns, selection, selectionArgs, groupBy,
having, orderBy, limit);
}
/**
* Runs the provided SQL and returns a {@link Cursor} over the result set.
*
* @param sql the SQL query. The SQL string must not be ; terminated
* @param selectionArgs You may include ?s in where clause in the query,
* which will be replaced by the values from selectionArgs. The
* values will be bound as Strings.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
*/
public Cursor rawQuery(String sql, String[] selectionArgs) {
return rawQueryWithFactory(null, sql, selectionArgs, null);
}
/**
* Runs the provided SQL and returns a cursor over the result set.
*
* @param cursorFactory the cursor factory to use, or null for the default factory
* @param sql the SQL query. The SQL string must not be ; terminated
* @param selectionArgs You may include ?s in where clause in the query,
* which will be replaced by the values from selectionArgs. The
* values will be bound as Strings.
* @param editTable the name of the first table, which is editable
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
*/
public Cursor rawQueryWithFactory(
CursorFactory cursorFactory, String sql, String[] selectionArgs,
String editTable) {
verifyDbIsOpen();
BlockGuard.getThreadPolicy().onReadFromDisk();
SQLiteDatabase db = getDbConnection(sql);
SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable);
Cursor cursor = null;
try {
cursor = driver.query(
cursorFactory != null ? cursorFactory : mFactory,
selectionArgs);
} finally {
releaseDbConnection(db);
}
return cursor;
}
/**
* Convenience method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be
* It has no means to return any data (such as the number of affected rows).
* Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
* {@link #update(String, ContentValues, String, String[])}, et al, when possible.
*
* When using {@link #enableWriteAheadLogging()}, journal_mode is
* automatically managed by this class. So, do not set journal_mode
* using "PRAGMA journal_mode'
* For INSERT statements, use any of the following instead.
*
* For UPDATE statements, use any of the following instead.
*
* For DELETE statements, use any of the following instead.
*
* For example, the following are good candidates for using this method:
* BINARY
collator, Android supplies
* two more, LOCALIZED
, which changes with the system's current locale
* if you wire it up correctly (XXX a link needed!), and UNICODE
, which
* is the Unicode Collation Algorithm and not tailored to the current locale.
*/
public class SQLiteDatabase extends SQLiteClosable {
private static final String TAG = "SQLiteDatabase";
private static final boolean ENABLE_DB_SAMPLE = false; // true to enable stats in event log
private static final int EVENT_DB_OPERATION = 52000;
private static final int EVENT_DB_CORRUPT = 75004;
/**
* Algorithms used in ON CONFLICT clause
* http://www.sqlite.org/lang_conflict.html
*/
/**
* When a constraint violation occurs, an immediate ROLLBACK occurs,
* thus ending the current transaction, and the command aborts with a
* return code of SQLITE_CONSTRAINT. If no transaction is active
* (other than the implied transaction that is created on every command)
* then this algorithm works the same as ABORT.
*/
public static final int CONFLICT_ROLLBACK = 1;
/**
* When a constraint violation occurs,no ROLLBACK is executed
* so changes from prior commands within the same transaction
* are preserved. This is the default behavior.
*/
public static final int CONFLICT_ABORT = 2;
/**
* When a constraint violation occurs, the command aborts with a return
* code SQLITE_CONSTRAINT. But any changes to the database that
* the command made prior to encountering the constraint violation
* are preserved and are not backed out.
*/
public static final int CONFLICT_FAIL = 3;
/**
* When a constraint violation occurs, the one row that contains
* the constraint violation is not inserted or changed.
* But the command continues executing normally. Other rows before and
* after the row that contained the constraint violation continue to be
* inserted or updated normally. No error is returned.
*/
public static final int CONFLICT_IGNORE = 4;
/**
* When a UNIQUE constraint violation occurs, the pre-existing rows that
* are causing the constraint violation are removed prior to inserting
* or updating the current row. Thus the insert or update always occurs.
* The command continues executing normally. No error is returned.
* If a NOT NULL constraint violation occurs, the NULL value is replaced
* by the default value for that column. If the column has no default
* value, then the ABORT algorithm is used. If a CHECK constraint
* violation occurs then the IGNORE algorithm is used. When this conflict
* resolution strategy deletes rows in order to satisfy a constraint,
* it does not invoke delete triggers on those rows.
* This behavior might change in a future release.
*/
public static final int CONFLICT_REPLACE = 5;
/**
* use the following when no conflict action is specified.
*/
public static final int CONFLICT_NONE = 0;
private static final String[] CONFLICT_VALUES = new String[]
{"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
/**
* Maximum Length Of A LIKE Or GLOB Pattern
* The pattern matching algorithm used in the default LIKE and GLOB implementation
* of SQLite can exhibit O(N^2) performance (where N is the number of characters in
* the pattern) for certain pathological cases. To avoid denial-of-service attacks
* the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
* The default value of this limit is 50000. A modern workstation can evaluate
* even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
* The denial of service problem only comes into play when the pattern length gets
* into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
* are at most a few dozen bytes in length, paranoid application developers may
* want to reduce this parameter to something in the range of a few hundred
* if they know that external users are able to generate arbitrary patterns.
*/
public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
/**
* Flag for {@link #openDatabase} to open the database for reading and writing.
* If the disk is full, this may fail even before you actually write anything.
*
* {@more} Note that the value of this flag is 0, so it is the default.
*/
public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
/**
* Flag for {@link #openDatabase} to open the database for reading only.
* This is the only reliable way to open a database if the disk may be full.
*/
public static final int OPEN_READONLY = 0x00000001; // update native code if changing
private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
/**
* Flag for {@link #openDatabase} to open the database without support for localized collators.
*
* {@more} This causes the collator LOCALIZED
not to be created.
* You must be consistent when using this flag to use the setting the database was
* created with. If this is set, {@link #setLocale} will do nothing.
*/
public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
/**
* Flag for {@link #openDatabase} to create the database file if it does not already exist.
*/
public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
/**
* Indicates whether the most-recently started transaction has been marked as successful.
*/
private boolean mInnerTransactionIsSuccessful;
/**
* Valid during the life of a transaction, and indicates whether the entire transaction (the
* outer one and all of the inner ones) so far has been successful.
*/
private boolean mTransactionIsSuccessful;
/**
* Valid during the life of a transaction.
*/
private SQLiteTransactionListener mTransactionListener;
/**
* this member is set if {@link #execSQL(String)} is used to begin and end transactions.
*/
private boolean mTransactionUsingExecSql;
/** Synchronize on this when accessing the database */
private final DatabaseReentrantLock mLock = new DatabaseReentrantLock(true);
private long mLockAcquiredWallTime = 0L;
private long mLockAcquiredThreadTime = 0L;
// limit the frequency of complaints about each database to one within 20 sec
// unless run command adb shell setprop log.tag.Database VERBOSE
private static final int LOCK_WARNING_WINDOW_IN_MS = 20000;
/** If the lock is held this long then a warning will be printed when it is released. */
private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS = 300;
private static final int LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS = 100;
private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT = 2000;
private static final int SLEEP_AFTER_YIELD_QUANTUM = 1000;
// The pattern we remove from database filenames before
// potentially logging them.
private static final Pattern EMAIL_IN_DB_PATTERN = Pattern.compile("[\\w\\.\\-]+@[\\w\\.\\-]+");
private long mLastLockMessageTime = 0L;
// Things related to query logging/sampling for debugging
// slow/frequent queries during development. Always log queries
// which take (by default) 500ms+; shorter queries are sampled
// accordingly. Commit statements, which are typically slow, are
// logged together with the most recently executed SQL statement,
// for disambiguation. The 500ms value is configurable via a
// SystemProperty, but developers actively debugging database I/O
// should probably use the regular log tunable,
// LOG_SLOW_QUERIES_PROPERTY, defined below.
private static int sQueryLogTimeInMillis = 0; // lazily initialized
private static final int QUERY_LOG_SQL_LENGTH = 64;
private static final String COMMIT_SQL = "COMMIT;";
private static final String BEGIN_SQL = "BEGIN;";
private final Random mRandom = new Random();
/** the last non-commit/rollback sql statement in a transaction */
// guarded by 'this'
private String mLastSqlStatement = null;
synchronized String getLastSqlStatement() {
return mLastSqlStatement;
}
synchronized void setLastSqlStatement(String sql) {
mLastSqlStatement = sql;
}
/** guarded by {@link #mLock} */
private long mTransStartTime;
// String prefix for slow database query EventLog records that show
// lock acquistions of the database.
/* package */ static final String GET_LOCK_LOG_PREFIX = "GETLOCK:";
/** Used by native code, do not rename. make it volatile, so it is thread-safe. */
/* package */ volatile int mNativeHandle = 0;
/**
* The size, in bytes, of a block on "/data". This corresponds to the Unix
* statfs.f_bsize field. note that this field is lazily initialized.
*/
private static int sBlockSize = 0;
/** The path for the database file */
private final String mPath;
/** The anonymized path for the database file for logging purposes */
private String mPathForLogs = null; // lazily populated
/** The flags passed to open/create */
private final int mFlags;
/** The optional factory to use when creating new Cursors */
private final CursorFactory mFactory;
private final WeakHashMap
* db.beginTransaction();
* try {
* ...
* db.setTransactionSuccessful();
* } finally {
* db.endTransaction();
* }
*
*/
public void beginTransaction() {
beginTransaction(null /* transactionStatusCallback */, true);
}
/**
* Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
* the outer transaction is ended all of the work done in that transaction
* and all of the nested transactions will be committed or rolled back. The
* changes will be rolled back if any transaction is ended without being
* marked as clean (by calling setTransactionSuccessful). Otherwise they
* will be committed.
*
* db.beginTransactionNonExclusive();
* try {
* ...
* db.setTransactionSuccessful();
* } finally {
* db.endTransaction();
* }
*
*/
public void beginTransactionNonExclusive() {
beginTransaction(null /* transactionStatusCallback */, false);
}
/**
* Begins a transaction in EXCLUSIVE mode.
*
* db.beginTransactionWithListener(listener);
* try {
* ...
* db.setTransactionSuccessful();
* } finally {
* db.endTransaction();
* }
*
*
* @param transactionListener listener that should be notified when the transaction begins,
* commits, or is rolled back, either explicitly or by a call to
* {@link #yieldIfContendedSafely}.
*/
public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
beginTransaction(transactionListener, true);
}
/**
* Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
* the outer transaction is ended all of the work done in that transaction
* and all of the nested transactions will be committed or rolled back. The
* changes will be rolled back if any transaction is ended without being
* marked as clean (by calling setTransactionSuccessful). Otherwise they
* will be committed.
*
* db.beginTransactionWithListenerNonExclusive(listener);
* try {
* ...
* db.setTransactionSuccessful();
* } finally {
* db.endTransaction();
* }
*
*
* @param transactionListener listener that should be notified when the
* transaction begins, commits, or is rolled back, either
* explicitly or by a call to {@link #yieldIfContendedSafely}.
*/
public void beginTransactionWithListenerNonExclusive(
SQLiteTransactionListener transactionListener) {
beginTransaction(transactionListener, false);
}
private void beginTransaction(SQLiteTransactionListener transactionListener,
boolean exclusive) {
verifyDbIsOpen();
lockForced(BEGIN_SQL);
boolean ok = false;
try {
// If this thread already had the lock then get out
if (mLock.getHoldCount() > 1) {
if (mInnerTransactionIsSuccessful) {
String msg = "Cannot call beginTransaction between "
+ "calling setTransactionSuccessful and endTransaction";
IllegalStateException e = new IllegalStateException(msg);
Log.e(TAG, "beginTransaction() failed", e);
throw e;
}
ok = true;
return;
}
// This thread didn't already have the lock, so begin a database
// transaction now.
if (exclusive && mConnectionPool == null) {
execSQL("BEGIN EXCLUSIVE;");
} else {
execSQL("BEGIN IMMEDIATE;");
}
mTransStartTime = SystemClock.uptimeMillis();
mTransactionListener = transactionListener;
mTransactionIsSuccessful = true;
mInnerTransactionIsSuccessful = false;
if (transactionListener != null) {
try {
transactionListener.onBegin();
} catch (RuntimeException e) {
execSQL("ROLLBACK;");
throw e;
}
}
ok = true;
} finally {
if (!ok) {
// beginTransaction is called before the try block so we must release the lock in
// the case of failure.
unlockForced();
}
}
}
/**
* End a transaction. See beginTransaction for notes about how to use this and when transactions
* are committed and rolled back.
*/
public void endTransaction() {
verifyLockOwner();
try {
if (mInnerTransactionIsSuccessful) {
mInnerTransactionIsSuccessful = false;
} else {
mTransactionIsSuccessful = false;
}
if (mLock.getHoldCount() != 1) {
return;
}
RuntimeException savedException = null;
if (mTransactionListener != null) {
try {
if (mTransactionIsSuccessful) {
mTransactionListener.onCommit();
} else {
mTransactionListener.onRollback();
}
} catch (RuntimeException e) {
savedException = e;
mTransactionIsSuccessful = false;
}
}
if (mTransactionIsSuccessful) {
execSQL(COMMIT_SQL);
// if write-ahead logging is used, we have to take care of checkpoint.
// TODO: should applications be given the flexibility of choosing when to
// trigger checkpoint?
// for now, do checkpoint after every COMMIT because that is the fastest
// way to guarantee that readers will see latest data.
// but this is the slowest way to run sqlite with in write-ahead logging mode.
if (this.mConnectionPool != null) {
execSQL("PRAGMA wal_checkpoint;");
if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
Log.i(TAG, "PRAGMA wal_Checkpoint done");
}
}
// log the transaction time to the Eventlog.
if (ENABLE_DB_SAMPLE) {
logTimeStat(getLastSqlStatement(), mTransStartTime, COMMIT_SQL);
}
} else {
try {
execSQL("ROLLBACK;");
if (savedException != null) {
throw savedException;
}
} catch (SQLException e) {
if (false) {
Log.d(TAG, "exception during rollback, maybe the DB previously "
+ "performed an auto-rollback");
}
}
}
} finally {
mTransactionListener = null;
unlockForced();
if (false) {
Log.v(TAG, "unlocked " + Thread.currentThread()
+ ", holdCount is " + mLock.getHoldCount());
}
}
}
/**
* Marks the current transaction as successful. Do not do any more database work between
* calling this and calling endTransaction. Do as little non-database work as possible in that
* situation too. If any errors are encountered between this and endTransaction the transaction
* will still be committed.
*
* @throws IllegalStateException if the current thread is not in a transaction or the
* transaction is already marked as successful.
*/
public void setTransactionSuccessful() {
verifyDbIsOpen();
if (!mLock.isHeldByCurrentThread()) {
throw new IllegalStateException("no transaction pending");
}
if (mInnerTransactionIsSuccessful) {
throw new IllegalStateException(
"setTransactionSuccessful may only be called once per call to beginTransaction");
}
mInnerTransactionIsSuccessful = true;
}
/**
* return true if there is a transaction pending
*/
public boolean inTransaction() {
return mLock.getHoldCount() > 0 || mTransactionUsingExecSql;
}
/* package */ synchronized void setTransactionUsingExecSqlFlag() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.i(TAG, "found execSQL('begin transaction')");
}
mTransactionUsingExecSql = true;
}
/* package */ synchronized void resetTransactionUsingExecSqlFlag() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
if (mTransactionUsingExecSql) {
Log.i(TAG, "found execSQL('commit or end or rollback')");
}
}
mTransactionUsingExecSql = false;
}
/**
* Returns true if the caller is considered part of the current transaction, if any.
*
*
*
* @return true if the caller is considered part of the current transaction, if any.
*/
/* package */ synchronized boolean amIInTransaction() {
// always do this test on the main database connection - NOT on pooled database connection
// since transactions always occur on the main database connections only.
SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this;
boolean b = (!db.inTransaction()) ? false :
db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.i(TAG, "amIinTransaction: " + b);
}
return b;
}
/**
* Checks if the database lock is held by this thread.
*
* @return true, if this thread is holding the database lock.
*/
public boolean isDbLockedByCurrentThread() {
return mLock.isHeldByCurrentThread();
}
/**
* Checks if the database is locked by another thread. This is
* just an estimate, since this status can change at any time,
* including after the call is made but before the result has
* been acted upon.
*
* @return true, if the database is locked by another thread
*/
public boolean isDbLockedByOtherThreads() {
return !mLock.isHeldByCurrentThread() && mLock.isLocked();
}
/**
* Temporarily end the transaction to let other threads run. The transaction is assumed to be
* successful so far. Do not call setTransactionSuccessful before calling this. When this
* returns a new transaction will have been created but not marked as successful.
* @return true if the transaction was yielded
* @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
* will not be yielded. Use yieldIfContendedSafely instead.
*/
@Deprecated
public boolean yieldIfContended() {
return yieldIfContendedHelper(false /* do not check yielding */,
-1 /* sleepAfterYieldDelay */);
}
/**
* Temporarily end the transaction to let other threads run. The transaction is assumed to be
* successful so far. Do not call setTransactionSuccessful before calling this. When this
* returns a new transaction will have been created but not marked as successful. This assumes
* that there are no nested transactions (beginTransaction has only been called once) and will
* throw an exception if that is not the case.
* @return true if the transaction was yielded
*/
public boolean yieldIfContendedSafely() {
return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
}
/**
* Temporarily end the transaction to let other threads run. The transaction is assumed to be
* successful so far. Do not call setTransactionSuccessful before calling this. When this
* returns a new transaction will have been created but not marked as successful. This assumes
* that there are no nested transactions (beginTransaction has only been called once) and will
* throw an exception if that is not the case.
* @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
* the lock was actually yielded. This will allow other background threads to make some
* more progress than they would if we started the transaction immediately.
* @return true if the transaction was yielded
*/
public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
}
private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) {
if (mLock.getQueueLength() == 0) {
// Reset the lock acquire time since we know that the thread was willing to yield
// the lock at this time.
mLockAcquiredWallTime = SystemClock.elapsedRealtime();
mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
return false;
}
setTransactionSuccessful();
SQLiteTransactionListener transactionListener = mTransactionListener;
endTransaction();
if (checkFullyYielded) {
if (this.isDbLockedByCurrentThread()) {
throw new IllegalStateException(
"Db locked more than once. yielfIfContended cannot yield");
}
}
if (sleepAfterYieldDelay > 0) {
// Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to
// check if anyone is using the database. If the database is not contended,
// retake the lock and return.
long remainingDelay = sleepAfterYieldDelay;
while (remainingDelay > 0) {
try {
Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ?
remainingDelay : SLEEP_AFTER_YIELD_QUANTUM);
} catch (InterruptedException e) {
Thread.interrupted();
}
remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM;
if (mLock.getQueueLength() == 0) {
break;
}
}
}
beginTransactionWithListener(transactionListener);
return true;
}
/**
* @deprecated This method no longer serves any useful purpose and has been deprecated.
*/
@Deprecated
public Mapnull
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided values
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your values
is empty.
* @param values this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert(String table, String nullColumnHack, ContentValues values) {
try {
return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
} catch (SQLException e) {
Log.e(TAG, "Error inserting " + values, e);
return -1;
}
}
/**
* Convenience method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be null
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided values
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your values
is empty.
* @param values this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @throws SQLException
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
throws SQLException {
return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
}
/**
* Convenience method for replacing a row in the database.
*
* @param table the table in which to replace the row
* @param nullColumnHack optional; may be null
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided initialValues
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your initialValues
is empty.
* @param initialValues this map contains the initial column values for
* the row.
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long replace(String table, String nullColumnHack, ContentValues initialValues) {
try {
return insertWithOnConflict(table, nullColumnHack, initialValues,
CONFLICT_REPLACE);
} catch (SQLException e) {
Log.e(TAG, "Error inserting " + initialValues, e);
return -1;
}
}
/**
* Convenience method for replacing a row in the database.
*
* @param table the table in which to replace the row
* @param nullColumnHack optional; may be null
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided initialValues
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your initialValues
is empty.
* @param initialValues this map contains the initial column values for
* the row. The key
* @throws SQLException
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long replaceOrThrow(String table, String nullColumnHack,
ContentValues initialValues) throws SQLException {
return insertWithOnConflict(table, nullColumnHack, initialValues,
CONFLICT_REPLACE);
}
/**
* General method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be null
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided initialValues
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your initialValues
is empty.
* @param initialValues this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @param conflictAlgorithm for insert conflict resolver
* @return the row ID of the newly inserted row
* OR the primary key of the existing row if the input param 'conflictAlgorithm' =
* {@link #CONFLICT_IGNORE}
* OR -1 if any error
*/
public long insertWithOnConflict(String table, String nullColumnHack,
ContentValues initialValues, int conflictAlgorithm) {
StringBuilder sql = new StringBuilder();
sql.append("INSERT");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(" INTO ");
sql.append(table);
sql.append('(');
Object[] bindArgs = null;
int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
if (size > 0) {
bindArgs = new Object[size];
int i = 0;
for (String colName : initialValues.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = initialValues.get(colName);
}
sql.append(')');
sql.append(" VALUES (");
for (i = 0; i < size; i++) {
sql.append((i > 0) ? ",?" : "?");
}
} else {
sql.append(nullColumnHack + ") VALUES (NULL");
}
sql.append(')');
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeInsert();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
} finally {
statement.close();
}
}
/**
* Convenience method for deleting rows in the database.
*
* @param table the table to delete from
* @param whereClause the optional WHERE clause to apply when deleting.
* Passing null will delete all rows.
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete(String table, String whereClause, String[] whereArgs) {
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
(!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
try {
return statement.executeUpdateDelete();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
} finally {
statement.close();
}
}
/**
* Convenience method for updating rows in the database.
*
* @param table the table to update in
* @param values a map from column names to new column values. null is a
* valid value that will be translated to NULL.
* @param whereClause the optional WHERE clause to apply when updating.
* Passing null will update all rows.
* @return the number of rows affected
*/
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
}
/**
* Convenience method for updating rows in the database.
*
* @param table the table to update in
* @param values a map from column names to new column values. null is a
* valid value that will be translated to NULL.
* @param whereClause the optional WHERE clause to apply when updating.
* Passing null will update all rows.
* @param conflictAlgorithm for update conflict resolver
* @return the number of rows affected
*/
public int updateWithOnConflict(String table, ContentValues values,
String whereClause, String[] whereArgs, int conflictAlgorithm) {
if (values == null || values.size() == 0) {
throw new IllegalArgumentException("Empty values");
}
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(table);
sql.append(" SET ");
// move all bind args to one array
int setValuesSize = values.size();
int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
Object[] bindArgs = new Object[bindArgsSize];
int i = 0;
for (String colName : values.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = values.get(colName);
sql.append("=?");
}
if (whereArgs != null) {
for (i = setValuesSize; i < bindArgsSize; i++) {
bindArgs[i] = whereArgs[i - setValuesSize];
}
}
if (!TextUtils.isEmpty(whereClause)) {
sql.append(" WHERE ");
sql.append(whereClause);
}
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeUpdateDelete();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
} finally {
statement.close();
}
}
/**
* Execute a single SQL statement that is NOT a SELECT
* or any other SQL statement that returns data.
*
*
*
*
*
*
*
*
*
* When using {@link #enableWriteAheadLogging()}, journal_mode is
* automatically managed by this class. So, do not set journal_mode
* using "PRAGMA journal_mode'
* If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL, * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current * mapping is NOT replaced with the new mapping). */ /* package */ synchronized void addToCompiledQueries( String sql, SQLiteCompiledSql compiledStatement) { // don't insert the new mapping if a mapping already exists if (mCompiledQueries.get(sql) != null) { return; } int maxCacheSz = (mConnectionNum == 0) ? mCompiledQueries.maxSize() : mParentConnObj.mCompiledQueries.maxSize(); if (SQLiteDebug.DEBUG_SQL_CACHE) { boolean printWarning = (mConnectionNum == 0) ? (!mCacheFullWarning && mCompiledQueries.size() == maxCacheSz) : (!mParentConnObj.mCacheFullWarning && mParentConnObj.mCompiledQueries.size() == maxCacheSz); if (printWarning) { /* * cache size is not enough for this app. log a warning. * chances are it is NOT using ? for bindargs - or cachesize is too small. */ Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " + getPath() + ". Use setMaxSqlCacheSize() to increase cachesize. "); mCacheFullWarning = true; Log.d(TAG, "Here are the SQL statements in Cache of database: " + mPath); for (String s : mCompiledQueries.snapshot().keySet()) { Log.d(TAG, "Sql statement in Cache: " + s); } } } /* add the given SQLiteCompiledSql compiledStatement to cache. * no need to worry about the cache size - because {@link #mCompiledQueries} * self-limits its size. */ mCompiledQueries.put(sql, compiledStatement); } /** package-level access for testing purposes */ /* package */ synchronized void deallocCachedSqlStatements() { for (SQLiteCompiledSql compiledSql : mCompiledQueries.snapshot().values()) { compiledSql.releaseSqlStatement(); } mCompiledQueries.evictAll(); } /** * From the compiledQueries cache, returns the compiled-statement-id for the given SQL. * Returns null, if not found in the cache. */ /* package */ synchronized SQLiteCompiledSql getCompiledStatementForSql(String sql) { return mCompiledQueries.get(sql); } /** * Sets the maximum size of the prepared-statement cache for this database. * (size of the cache = number of compiled-sql-statements stored in the cache). *
* Maximum cache size can ONLY be increased from its current size (default = 10). * If this method is called with smaller size than the current maximum value, * then IllegalStateException is thrown. *
* This method is thread-safe.
*
* @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
* @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or
* the value set with previous setMaxSqlCacheSize() call.
*/
public void setMaxSqlCacheSize(int cacheSize) {
synchronized (this) {
LruCache
* If a transaction is in progress on one connection handle and say, a table is updated in the
* transaction, then query on the same table on another connection handle will block for the
* transaction to complete. But this method enables such queries to execute by having them
* return old version of the data from the table. Most often it is the data that existed in the
* table prior to the above transaction updates on that table.
*
* Maximum number of simultaneous handles used to execute queries in parallel is
* dependent upon the device memory and possibly other properties.
*
* After calling this method, execution of queries in parallel is enabled as long as this
* database handle is open. To disable execution of queries in parallel, database should
* be closed and reopened.
*
* If a query is part of a transaction, then it is executed on the same database handle the
* transaction was begun.
*
* If the database has any attached databases, then execution of queries in paralel is NOT
* possible. In such cases, a message is printed to logcat and false is returned.
*
* This feature is not available for :memory: databases. In such cases,
* a message is printed to logcat and false is returned.
*
* A typical way to use this method is the following:
*
* Writers should use {@link #beginTransactionNonExclusive()} or
* {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
* to start a trsnsaction.
* Non-exclusive mode allows database file to be in readable by threads executing queries.
*
* If the result is false, then this method logs the errors reported by the integrity_check
* command execution.
*
* Note that 'pragma integrity_check' on a database can take a long time.
*
* @return true if the given database (and all its attached databases) pass integrity_check,
* false otherwise.
*/
public boolean isDatabaseIntegrityOk() {
verifyDbIsOpen();
List
* SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
* CREATE_IF_NECESSARY, myDatabaseErrorHandler);
* db.enableWriteAheadLogging();
*
*