The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 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 | package android.database.sqlite; |
| 18 | |
Dianne Hackborn | 01e4cfc | 2010-06-24 15:07:24 -0700 | [diff] [blame] | 19 | import android.app.AppGlobals; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 20 | import android.content.ContentValues; |
| 21 | import android.database.Cursor; |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 22 | import android.database.DatabaseErrorHandler; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 23 | import android.database.DatabaseUtils; |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 24 | import android.database.DefaultDatabaseErrorHandler; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 25 | import android.database.SQLException; |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 26 | import android.database.sqlite.SQLiteDebug.DbStats; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 27 | import android.os.Debug; |
Vasu Nori | a8c2490 | 2010-06-01 11:30:27 -0700 | [diff] [blame] | 28 | import android.os.StatFs; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 29 | import android.os.SystemClock; |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 30 | import android.os.SystemProperties; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 31 | import android.text.TextUtils; |
| 32 | import android.util.Config; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 33 | import android.util.EventLog; |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 34 | import android.util.Log; |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 35 | import android.util.Pair; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 36 | |
Brad Fitzpatrick | cfda9f3 | 2010-06-03 12:52:54 -0700 | [diff] [blame] | 37 | import dalvik.system.BlockGuard; |
| 38 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 39 | import java.io.File; |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 40 | import java.lang.ref.WeakReference; |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 41 | import java.util.ArrayList; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 42 | import java.util.HashMap; |
| 43 | import java.util.Iterator; |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 44 | import java.util.LinkedHashMap; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 45 | import java.util.Locale; |
| 46 | import java.util.Map; |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 47 | import java.util.Random; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 48 | import java.util.WeakHashMap; |
| 49 | import java.util.concurrent.locks.ReentrantLock; |
Brad Fitzpatrick | d833023 | 2010-02-19 10:59:01 -0800 | [diff] [blame] | 50 | import java.util.regex.Pattern; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 51 | |
| 52 | /** |
| 53 | * Exposes methods to manage a SQLite database. |
| 54 | * <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and |
| 55 | * perform other common database management tasks. |
| 56 | * <p>See the Notepad sample application in the SDK for an example of creating |
| 57 | * and managing a database. |
| 58 | * <p> Database names must be unique within an application, not across all |
| 59 | * applications. |
| 60 | * |
| 61 | * <h3>Localized Collation - ORDER BY</h3> |
| 62 | * <p>In addition to SQLite's default <code>BINARY</code> collator, Android supplies |
| 63 | * two more, <code>LOCALIZED</code>, which changes with the system's current locale |
| 64 | * if you wire it up correctly (XXX a link needed!), and <code>UNICODE</code>, which |
| 65 | * is the Unicode Collation Algorithm and not tailored to the current locale. |
| 66 | */ |
| 67 | public class SQLiteDatabase extends SQLiteClosable { |
Vasu Nori | fb16cbd | 2010-07-25 16:38:48 -0700 | [diff] [blame] | 68 | private static final String TAG = "SQLiteDatabase"; |
Jeff Hamilton | 082c2af | 2009-09-29 11:49:51 -0700 | [diff] [blame] | 69 | private static final int EVENT_DB_OPERATION = 52000; |
| 70 | private static final int EVENT_DB_CORRUPT = 75004; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 71 | |
| 72 | /** |
| 73 | * Algorithms used in ON CONFLICT clause |
| 74 | * http://www.sqlite.org/lang_conflict.html |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 75 | */ |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 76 | /** |
| 77 | * When a constraint violation occurs, an immediate ROLLBACK occurs, |
| 78 | * thus ending the current transaction, and the command aborts with a |
| 79 | * return code of SQLITE_CONSTRAINT. If no transaction is active |
| 80 | * (other than the implied transaction that is created on every command) |
| 81 | * then this algorithm works the same as ABORT. |
| 82 | */ |
| 83 | public static final int CONFLICT_ROLLBACK = 1; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 84 | |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 85 | /** |
| 86 | * When a constraint violation occurs,no ROLLBACK is executed |
| 87 | * so changes from prior commands within the same transaction |
| 88 | * are preserved. This is the default behavior. |
| 89 | */ |
| 90 | public static final int CONFLICT_ABORT = 2; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 91 | |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 92 | /** |
| 93 | * When a constraint violation occurs, the command aborts with a return |
| 94 | * code SQLITE_CONSTRAINT. But any changes to the database that |
| 95 | * the command made prior to encountering the constraint violation |
| 96 | * are preserved and are not backed out. |
| 97 | */ |
| 98 | public static final int CONFLICT_FAIL = 3; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 99 | |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 100 | /** |
| 101 | * When a constraint violation occurs, the one row that contains |
| 102 | * the constraint violation is not inserted or changed. |
| 103 | * But the command continues executing normally. Other rows before and |
| 104 | * after the row that contained the constraint violation continue to be |
| 105 | * inserted or updated normally. No error is returned. |
| 106 | */ |
| 107 | public static final int CONFLICT_IGNORE = 4; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 108 | |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 109 | /** |
| 110 | * When a UNIQUE constraint violation occurs, the pre-existing rows that |
| 111 | * are causing the constraint violation are removed prior to inserting |
| 112 | * or updating the current row. Thus the insert or update always occurs. |
| 113 | * The command continues executing normally. No error is returned. |
| 114 | * If a NOT NULL constraint violation occurs, the NULL value is replaced |
| 115 | * by the default value for that column. If the column has no default |
| 116 | * value, then the ABORT algorithm is used. If a CHECK constraint |
| 117 | * violation occurs then the IGNORE algorithm is used. When this conflict |
| 118 | * resolution strategy deletes rows in order to satisfy a constraint, |
| 119 | * it does not invoke delete triggers on those rows. |
| 120 | * This behavior might change in a future release. |
| 121 | */ |
| 122 | public static final int CONFLICT_REPLACE = 5; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 123 | |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 124 | /** |
| 125 | * use the following when no conflict action is specified. |
| 126 | */ |
| 127 | public static final int CONFLICT_NONE = 0; |
| 128 | private static final String[] CONFLICT_VALUES = new String[] |
| 129 | {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "}; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 130 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 131 | /** |
| 132 | * Maximum Length Of A LIKE Or GLOB Pattern |
| 133 | * The pattern matching algorithm used in the default LIKE and GLOB implementation |
| 134 | * of SQLite can exhibit O(N^2) performance (where N is the number of characters in |
| 135 | * the pattern) for certain pathological cases. To avoid denial-of-service attacks |
| 136 | * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes. |
| 137 | * The default value of this limit is 50000. A modern workstation can evaluate |
| 138 | * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly. |
| 139 | * The denial of service problem only comes into play when the pattern length gets |
| 140 | * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns |
| 141 | * are at most a few dozen bytes in length, paranoid application developers may |
| 142 | * want to reduce this parameter to something in the range of a few hundred |
| 143 | * if they know that external users are able to generate arbitrary patterns. |
| 144 | */ |
| 145 | public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; |
| 146 | |
| 147 | /** |
| 148 | * Flag for {@link #openDatabase} to open the database for reading and writing. |
| 149 | * If the disk is full, this may fail even before you actually write anything. |
| 150 | * |
| 151 | * {@more} Note that the value of this flag is 0, so it is the default. |
| 152 | */ |
| 153 | public static final int OPEN_READWRITE = 0x00000000; // update native code if changing |
| 154 | |
| 155 | /** |
| 156 | * Flag for {@link #openDatabase} to open the database for reading only. |
| 157 | * This is the only reliable way to open a database if the disk may be full. |
| 158 | */ |
| 159 | public static final int OPEN_READONLY = 0x00000001; // update native code if changing |
| 160 | |
| 161 | private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing |
| 162 | |
| 163 | /** |
| 164 | * Flag for {@link #openDatabase} to open the database without support for localized collators. |
| 165 | * |
| 166 | * {@more} This causes the collator <code>LOCALIZED</code> not to be created. |
| 167 | * You must be consistent when using this flag to use the setting the database was |
| 168 | * created with. If this is set, {@link #setLocale} will do nothing. |
| 169 | */ |
| 170 | public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing |
| 171 | |
| 172 | /** |
| 173 | * Flag for {@link #openDatabase} to create the database file if it does not already exist. |
| 174 | */ |
| 175 | public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing |
| 176 | |
| 177 | /** |
| 178 | * Indicates whether the most-recently started transaction has been marked as successful. |
| 179 | */ |
| 180 | private boolean mInnerTransactionIsSuccessful; |
| 181 | |
| 182 | /** |
| 183 | * Valid during the life of a transaction, and indicates whether the entire transaction (the |
| 184 | * outer one and all of the inner ones) so far has been successful. |
| 185 | */ |
| 186 | private boolean mTransactionIsSuccessful; |
| 187 | |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 188 | /** |
| 189 | * Valid during the life of a transaction. |
| 190 | */ |
| 191 | private SQLiteTransactionListener mTransactionListener; |
| 192 | |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 193 | /** |
| 194 | * this member is set if {@link #execSQL(String)} is used to begin and end transactions. |
| 195 | */ |
| 196 | private boolean mTransactionUsingExecSql; |
| 197 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 198 | /** Synchronize on this when accessing the database */ |
| 199 | private final ReentrantLock mLock = new ReentrantLock(true); |
| 200 | |
| 201 | private long mLockAcquiredWallTime = 0L; |
| 202 | private long mLockAcquiredThreadTime = 0L; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 203 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 204 | // limit the frequency of complaints about each database to one within 20 sec |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 205 | // unless run command adb shell setprop log.tag.Database VERBOSE |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 206 | private static final int LOCK_WARNING_WINDOW_IN_MS = 20000; |
| 207 | /** If the lock is held this long then a warning will be printed when it is released. */ |
| 208 | private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS = 300; |
| 209 | private static final int LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS = 100; |
| 210 | private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT = 2000; |
| 211 | |
Dmitri Plotnikov | b43b58d | 2009-09-09 18:10:42 -0700 | [diff] [blame] | 212 | private static final int SLEEP_AFTER_YIELD_QUANTUM = 1000; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 213 | |
Brad Fitzpatrick | d833023 | 2010-02-19 10:59:01 -0800 | [diff] [blame] | 214 | // The pattern we remove from database filenames before |
| 215 | // potentially logging them. |
| 216 | private static final Pattern EMAIL_IN_DB_PATTERN = Pattern.compile("[\\w\\.\\-]+@[\\w\\.\\-]+"); |
| 217 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 218 | private long mLastLockMessageTime = 0L; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 219 | |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 220 | // Things related to query logging/sampling for debugging |
| 221 | // slow/frequent queries during development. Always log queries |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 222 | // which take (by default) 500ms+; shorter queries are sampled |
| 223 | // accordingly. Commit statements, which are typically slow, are |
| 224 | // logged together with the most recently executed SQL statement, |
| 225 | // for disambiguation. The 500ms value is configurable via a |
| 226 | // SystemProperty, but developers actively debugging database I/O |
| 227 | // should probably use the regular log tunable, |
| 228 | // LOG_SLOW_QUERIES_PROPERTY, defined below. |
| 229 | private static int sQueryLogTimeInMillis = 0; // lazily initialized |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 230 | private static final int QUERY_LOG_SQL_LENGTH = 64; |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 231 | private static final String COMMIT_SQL = "COMMIT;"; |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 232 | private final Random mRandom = new Random(); |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 233 | private String mLastSqlStatement = null; |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 234 | |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 235 | // String prefix for slow database query EventLog records that show |
| 236 | // lock acquistions of the database. |
| 237 | /* package */ static final String GET_LOCK_LOG_PREFIX = "GETLOCK:"; |
| 238 | |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 239 | /** Used by native code, do not rename. make it volatile, so it is thread-safe. */ |
| 240 | /* package */ volatile int mNativeHandle = 0; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 241 | |
Vasu Nori | a8c2490 | 2010-06-01 11:30:27 -0700 | [diff] [blame] | 242 | /** |
| 243 | * The size, in bytes, of a block on "/data". This corresponds to the Unix |
| 244 | * statfs.f_bsize field. note that this field is lazily initialized. |
| 245 | */ |
| 246 | private static int sBlockSize = 0; |
| 247 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 248 | /** The path for the database file */ |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 249 | private final String mPath; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 250 | |
Brad Fitzpatrick | d833023 | 2010-02-19 10:59:01 -0800 | [diff] [blame] | 251 | /** The anonymized path for the database file for logging purposes */ |
| 252 | private String mPathForLogs = null; // lazily populated |
| 253 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 254 | /** The flags passed to open/create */ |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 255 | private final int mFlags; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 256 | |
| 257 | /** The optional factory to use when creating new Cursors */ |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 258 | private final CursorFactory mFactory; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 259 | |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 260 | private final WeakHashMap<SQLiteClosable, Object> mPrograms; |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 261 | |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 262 | /** |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 263 | * for each instance of this class, a LRU cache is maintained to store |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 264 | * the compiled query statement ids returned by sqlite database. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 265 | * key = SQL statement with "?" for bind args |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 266 | * value = {@link SQLiteCompiledSql} |
| 267 | * If an application opens the database and keeps it open during its entire life, then |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 268 | * there will not be an overhead of compilation of SQL statements by sqlite. |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 269 | * |
| 270 | * why is this cache NOT static? because sqlite attaches compiledsql statements to the |
| 271 | * struct created when {@link SQLiteDatabase#openDatabase(String, CursorFactory, int)} is |
| 272 | * invoked. |
| 273 | * |
| 274 | * this cache has an upper limit of mMaxSqlCacheSize (settable by calling the method |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 275 | * (@link #setMaxSqlCacheSize(int)}). |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 276 | */ |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 277 | // default statement-cache size per database connection ( = instance of this class) |
| 278 | private int mMaxSqlCacheSize = 25; |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 279 | /* package */ final Map<String, SQLiteCompiledSql> mCompiledQueries = |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 280 | new LinkedHashMap<String, SQLiteCompiledSql>(mMaxSqlCacheSize + 1, 0.75f, true) { |
| 281 | @Override |
| 282 | public boolean removeEldestEntry(Map.Entry<String, SQLiteCompiledSql> eldest) { |
Vasu Nori | 9504c70 | 2010-04-23 01:04:31 -0700 | [diff] [blame] | 283 | // eldest = least-recently used entry |
| 284 | // if it needs to be removed to accommodate a new entry, |
| 285 | // close {@link SQLiteCompiledSql} represented by this entry, if not in use |
| 286 | // and then let it be removed from the Map. |
Vasu Nori | 9463f29 | 2010-04-30 12:22:18 -0700 | [diff] [blame] | 287 | // when this is called, the caller must be trying to add a just-compiled stmt |
| 288 | // to cache; i.e., caller should already have acquired database lock AND |
| 289 | // the lock on mCompiledQueries. do as assert of these two 2 facts. |
| 290 | verifyLockOwner(); |
| 291 | if (this.size() <= mMaxSqlCacheSize) { |
| 292 | // cache is not full. nothing needs to be removed |
| 293 | return false; |
Vasu Nori | 9504c70 | 2010-04-23 01:04:31 -0700 | [diff] [blame] | 294 | } |
Vasu Nori | 9463f29 | 2010-04-30 12:22:18 -0700 | [diff] [blame] | 295 | // cache is full. eldest will be removed. |
| 296 | SQLiteCompiledSql entry = eldest.getValue(); |
| 297 | if (!entry.isInUse()) { |
| 298 | // this {@link SQLiteCompiledSql} is not in use. release it. |
| 299 | entry.releaseSqlStatement(); |
| 300 | } |
| 301 | // return true, so that this entry is removed automatically by the caller. |
| 302 | return true; |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 303 | } |
| 304 | }; |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 305 | /** |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 306 | * absolute max value that can be set by {@link #setMaxSqlCacheSize(int)} |
Vasu Nori | 90a36726 | 2010-04-12 12:49:09 -0700 | [diff] [blame] | 307 | * size of each prepared-statement is between 1K - 6K, depending on the complexity of the |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 308 | * SQL statement & schema. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 309 | */ |
Vasu Nori | 90a36726 | 2010-04-12 12:49:09 -0700 | [diff] [blame] | 310 | public static final int MAX_SQL_CACHE_SIZE = 100; |
Vasu Nori | e9d9210 | 2010-01-20 15:07:26 -0800 | [diff] [blame] | 311 | private int mCacheFullWarnings; |
Vasu Nori | 49d02ac | 2010-03-05 21:49:30 -0800 | [diff] [blame] | 312 | private static final int MAX_WARNINGS_ON_CACHESIZE_CONDITION = 1; |
Vasu Nori | 5a03f36 | 2009-10-20 15:16:35 -0700 | [diff] [blame] | 313 | |
| 314 | /** maintain stats about number of cache hits and misses */ |
| 315 | private int mNumCacheHits; |
| 316 | private int mNumCacheMisses; |
| 317 | |
Vasu Nori | d606b4b | 2010-02-24 12:54:20 -0800 | [diff] [blame] | 318 | /** Used to find out where this object was created in case it never got closed. */ |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 319 | private final Throwable mStackTrace; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 320 | |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 321 | // System property that enables logging of slow queries. Specify the threshold in ms. |
| 322 | private static final String LOG_SLOW_QUERIES_PROPERTY = "db.log.slow_query_threshold"; |
| 323 | private final int mSlowQueryThreshold; |
| 324 | |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 325 | /** stores the list of statement ids that need to be finalized by sqlite */ |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 326 | private final ArrayList<Integer> mClosedStatementIds = new ArrayList<Integer>(); |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 327 | |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 328 | /** {@link DatabaseErrorHandler} to be used when SQLite returns any of the following errors |
| 329 | * Corruption |
| 330 | * */ |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 331 | private final DatabaseErrorHandler mErrorHandler; |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 332 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 333 | /** The Database connection pool {@link DatabaseConnectionPool}. |
| 334 | * Visibility is package-private for testing purposes. otherwise, private visibility is enough. |
| 335 | */ |
| 336 | /* package */ volatile DatabaseConnectionPool mConnectionPool = null; |
| 337 | |
| 338 | /** Each database connection handle in the pool is assigned a number 1..N, where N is the |
| 339 | * size of the connection pool. |
| 340 | * The main connection handle to which the pool is attached is assigned a value of 0. |
| 341 | */ |
| 342 | /* package */ final short mConnectionNum; |
| 343 | |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 344 | /** on pooled database connections, this member points to the parent ( = main) |
| 345 | * database connection handle. |
| 346 | * package visibility only for testing purposes |
| 347 | */ |
| 348 | /* package */ SQLiteDatabase mParentConnObj = null; |
| 349 | |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 350 | private static final String MEMORY_DB_PATH = ":memory:"; |
| 351 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 352 | /** stores reference to all databases opened in the current process. */ |
| 353 | private static ArrayList<WeakReference<SQLiteDatabase>> mActiveDatabases = |
| 354 | new ArrayList<WeakReference<SQLiteDatabase>>(); |
| 355 | |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 356 | synchronized void addSQLiteClosable(SQLiteClosable closable) { |
| 357 | // mPrograms is per instance of SQLiteDatabase and it doesn't actually touch the database |
| 358 | // itself. so, there is no need to lock(). |
| 359 | mPrograms.put(closable, null); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 360 | } |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 361 | |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 362 | synchronized void removeSQLiteClosable(SQLiteClosable closable) { |
| 363 | mPrograms.remove(closable); |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 364 | } |
| 365 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 366 | @Override |
| 367 | protected void onAllReferencesReleased() { |
| 368 | if (isOpen()) { |
Vasu Nori | ad239ab | 2010-06-14 16:58:47 -0700 | [diff] [blame] | 369 | // close the database which will close all pending statements to be finalized also |
| 370 | close(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 371 | } |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Attempts to release memory that SQLite holds but does not require to |
| 376 | * operate properly. Typically this memory will come from the page cache. |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 377 | * |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 378 | * @return the number of bytes actually released |
| 379 | */ |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 380 | static public native int releaseMemory(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 381 | |
| 382 | /** |
| 383 | * Control whether or not the SQLiteDatabase is made thread-safe by using locks |
| 384 | * around critical sections. This is pretty expensive, so if you know that your |
| 385 | * DB will only be used by a single thread then you should set this to false. |
| 386 | * The default is true. |
| 387 | * @param lockingEnabled set to true to enable locks, false otherwise |
| 388 | */ |
| 389 | public void setLockingEnabled(boolean lockingEnabled) { |
| 390 | mLockingEnabled = lockingEnabled; |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * If set then the SQLiteDatabase is made thread-safe by using locks |
| 395 | * around critical sections |
| 396 | */ |
| 397 | private boolean mLockingEnabled = true; |
| 398 | |
| 399 | /* package */ void onCorruption() { |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 400 | EventLog.writeEvent(EVENT_DB_CORRUPT, mPath); |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 401 | mErrorHandler.onCorruption(this); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 402 | } |
| 403 | |
| 404 | /** |
| 405 | * Locks the database for exclusive access. The database lock must be held when |
| 406 | * touch the native sqlite3* object since it is single threaded and uses |
| 407 | * a polling lock contention algorithm. The lock is recursive, and may be acquired |
| 408 | * multiple times by the same thread. This is a no-op if mLockingEnabled is false. |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 409 | * |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 410 | * @see #unlock() |
| 411 | */ |
| 412 | /* package */ void lock() { |
Vasu Nori | 7b04c41 | 2010-07-20 10:31:21 -0700 | [diff] [blame] | 413 | verifyDbIsOpen(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 414 | if (!mLockingEnabled) return; |
| 415 | mLock.lock(); |
| 416 | if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) { |
| 417 | if (mLock.getHoldCount() == 1) { |
| 418 | // Use elapsed real-time since the CPU may sleep when waiting for IO |
| 419 | mLockAcquiredWallTime = SystemClock.elapsedRealtime(); |
| 420 | mLockAcquiredThreadTime = Debug.threadCpuTimeNanos(); |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | /** |
| 426 | * Locks the database for exclusive access. The database lock must be held when |
| 427 | * touch the native sqlite3* object since it is single threaded and uses |
| 428 | * a polling lock contention algorithm. The lock is recursive, and may be acquired |
| 429 | * multiple times by the same thread. |
| 430 | * |
| 431 | * @see #unlockForced() |
| 432 | */ |
| 433 | private void lockForced() { |
Vasu Nori | 7b04c41 | 2010-07-20 10:31:21 -0700 | [diff] [blame] | 434 | verifyDbIsOpen(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 435 | mLock.lock(); |
| 436 | if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) { |
| 437 | if (mLock.getHoldCount() == 1) { |
| 438 | // Use elapsed real-time since the CPU may sleep when waiting for IO |
| 439 | mLockAcquiredWallTime = SystemClock.elapsedRealtime(); |
| 440 | mLockAcquiredThreadTime = Debug.threadCpuTimeNanos(); |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | /** |
| 446 | * Releases the database lock. This is a no-op if mLockingEnabled is false. |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 447 | * |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 448 | * @see #unlock() |
| 449 | */ |
| 450 | /* package */ void unlock() { |
| 451 | if (!mLockingEnabled) return; |
| 452 | if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) { |
| 453 | if (mLock.getHoldCount() == 1) { |
| 454 | checkLockHoldTime(); |
| 455 | } |
| 456 | } |
| 457 | mLock.unlock(); |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * Releases the database lock. |
| 462 | * |
| 463 | * @see #unlockForced() |
| 464 | */ |
| 465 | private void unlockForced() { |
| 466 | if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) { |
| 467 | if (mLock.getHoldCount() == 1) { |
| 468 | checkLockHoldTime(); |
| 469 | } |
| 470 | } |
| 471 | mLock.unlock(); |
| 472 | } |
| 473 | |
| 474 | private void checkLockHoldTime() { |
| 475 | // Use elapsed real-time since the CPU may sleep when waiting for IO |
| 476 | long elapsedTime = SystemClock.elapsedRealtime(); |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 477 | long lockedTime = elapsedTime - mLockAcquiredWallTime; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 478 | if (lockedTime < LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT && |
| 479 | !Log.isLoggable(TAG, Log.VERBOSE) && |
| 480 | (elapsedTime - mLastLockMessageTime) < LOCK_WARNING_WINDOW_IN_MS) { |
| 481 | return; |
| 482 | } |
| 483 | if (lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS) { |
| 484 | int threadTime = (int) |
| 485 | ((Debug.threadCpuTimeNanos() - mLockAcquiredThreadTime) / 1000000); |
| 486 | if (threadTime > LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS || |
| 487 | lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT) { |
| 488 | mLastLockMessageTime = elapsedTime; |
| 489 | String msg = "lock held on " + mPath + " for " + lockedTime + "ms. Thread time was " |
| 490 | + threadTime + "ms"; |
| 491 | if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING_STACK_TRACE) { |
| 492 | Log.d(TAG, msg, new Exception()); |
| 493 | } else { |
| 494 | Log.d(TAG, msg); |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 501 | * Begins a transaction in EXCLUSIVE mode. |
| 502 | * <p> |
| 503 | * Transactions can be nested. |
| 504 | * When the outer transaction is ended all of |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 505 | * the work done in that transaction and all of the nested transactions will be committed or |
| 506 | * rolled back. The changes will be rolled back if any transaction is ended without being |
| 507 | * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 508 | * </p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 509 | * <p>Here is the standard idiom for transactions: |
| 510 | * |
| 511 | * <pre> |
| 512 | * db.beginTransaction(); |
| 513 | * try { |
| 514 | * ... |
| 515 | * db.setTransactionSuccessful(); |
| 516 | * } finally { |
| 517 | * db.endTransaction(); |
| 518 | * } |
| 519 | * </pre> |
| 520 | */ |
| 521 | public void beginTransaction() { |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 522 | beginTransaction(null /* transactionStatusCallback */, true); |
| 523 | } |
| 524 | |
| 525 | /** |
| 526 | * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When |
| 527 | * the outer transaction is ended all of the work done in that transaction |
| 528 | * and all of the nested transactions will be committed or rolled back. The |
| 529 | * changes will be rolled back if any transaction is ended without being |
| 530 | * marked as clean (by calling setTransactionSuccessful). Otherwise they |
| 531 | * will be committed. |
| 532 | * <p> |
| 533 | * Here is the standard idiom for transactions: |
| 534 | * |
| 535 | * <pre> |
| 536 | * db.beginTransactionNonExclusive(); |
| 537 | * try { |
| 538 | * ... |
| 539 | * db.setTransactionSuccessful(); |
| 540 | * } finally { |
| 541 | * db.endTransaction(); |
| 542 | * } |
| 543 | * </pre> |
| 544 | */ |
| 545 | public void beginTransactionNonExclusive() { |
| 546 | beginTransaction(null /* transactionStatusCallback */, false); |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 547 | } |
| 548 | |
| 549 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 550 | * Begins a transaction in EXCLUSIVE mode. |
| 551 | * <p> |
| 552 | * Transactions can be nested. |
| 553 | * When the outer transaction is ended all of |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 554 | * the work done in that transaction and all of the nested transactions will be committed or |
| 555 | * rolled back. The changes will be rolled back if any transaction is ended without being |
| 556 | * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 557 | * </p> |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 558 | * <p>Here is the standard idiom for transactions: |
| 559 | * |
| 560 | * <pre> |
| 561 | * db.beginTransactionWithListener(listener); |
| 562 | * try { |
| 563 | * ... |
| 564 | * db.setTransactionSuccessful(); |
| 565 | * } finally { |
| 566 | * db.endTransaction(); |
| 567 | * } |
| 568 | * </pre> |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 569 | * |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 570 | * @param transactionListener listener that should be notified when the transaction begins, |
| 571 | * commits, or is rolled back, either explicitly or by a call to |
| 572 | * {@link #yieldIfContendedSafely}. |
| 573 | */ |
| 574 | public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) { |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 575 | beginTransaction(transactionListener, true); |
| 576 | } |
| 577 | |
| 578 | /** |
| 579 | * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When |
| 580 | * the outer transaction is ended all of the work done in that transaction |
| 581 | * and all of the nested transactions will be committed or rolled back. The |
| 582 | * changes will be rolled back if any transaction is ended without being |
| 583 | * marked as clean (by calling setTransactionSuccessful). Otherwise they |
| 584 | * will be committed. |
| 585 | * <p> |
| 586 | * Here is the standard idiom for transactions: |
| 587 | * |
| 588 | * <pre> |
| 589 | * db.beginTransactionWithListenerNonExclusive(listener); |
| 590 | * try { |
| 591 | * ... |
| 592 | * db.setTransactionSuccessful(); |
| 593 | * } finally { |
| 594 | * db.endTransaction(); |
| 595 | * } |
| 596 | * </pre> |
| 597 | * |
| 598 | * @param transactionListener listener that should be notified when the |
| 599 | * transaction begins, commits, or is rolled back, either |
| 600 | * explicitly or by a call to {@link #yieldIfContendedSafely}. |
| 601 | */ |
| 602 | public void beginTransactionWithListenerNonExclusive( |
| 603 | SQLiteTransactionListener transactionListener) { |
| 604 | beginTransaction(transactionListener, false); |
| 605 | } |
| 606 | |
| 607 | private void beginTransaction(SQLiteTransactionListener transactionListener, |
| 608 | boolean exclusive) { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 609 | verifyDbIsOpen(); |
Vasu Nori | c8e1f23 | 2010-04-13 15:05:09 -0700 | [diff] [blame] | 610 | lockForced(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 611 | boolean ok = false; |
| 612 | try { |
| 613 | // If this thread already had the lock then get out |
| 614 | if (mLock.getHoldCount() > 1) { |
| 615 | if (mInnerTransactionIsSuccessful) { |
| 616 | String msg = "Cannot call beginTransaction between " |
| 617 | + "calling setTransactionSuccessful and endTransaction"; |
| 618 | IllegalStateException e = new IllegalStateException(msg); |
| 619 | Log.e(TAG, "beginTransaction() failed", e); |
| 620 | throw e; |
| 621 | } |
| 622 | ok = true; |
| 623 | return; |
| 624 | } |
| 625 | |
| 626 | // This thread didn't already have the lock, so begin a database |
| 627 | // transaction now. |
Vasu Nori | 57feb5d | 2010-06-22 10:39:04 -0700 | [diff] [blame] | 628 | if (exclusive && mConnectionPool == null) { |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 629 | execSQL("BEGIN EXCLUSIVE;"); |
| 630 | } else { |
| 631 | execSQL("BEGIN IMMEDIATE;"); |
| 632 | } |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 633 | mTransactionListener = transactionListener; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 634 | mTransactionIsSuccessful = true; |
| 635 | mInnerTransactionIsSuccessful = false; |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 636 | if (transactionListener != null) { |
| 637 | try { |
| 638 | transactionListener.onBegin(); |
| 639 | } catch (RuntimeException e) { |
| 640 | execSQL("ROLLBACK;"); |
| 641 | throw e; |
| 642 | } |
| 643 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 644 | ok = true; |
| 645 | } finally { |
| 646 | if (!ok) { |
| 647 | // beginTransaction is called before the try block so we must release the lock in |
| 648 | // the case of failure. |
| 649 | unlockForced(); |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /** |
| 655 | * End a transaction. See beginTransaction for notes about how to use this and when transactions |
| 656 | * are committed and rolled back. |
| 657 | */ |
| 658 | public void endTransaction() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 659 | verifyLockOwner(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 660 | try { |
| 661 | if (mInnerTransactionIsSuccessful) { |
| 662 | mInnerTransactionIsSuccessful = false; |
| 663 | } else { |
| 664 | mTransactionIsSuccessful = false; |
| 665 | } |
| 666 | if (mLock.getHoldCount() != 1) { |
| 667 | return; |
| 668 | } |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 669 | RuntimeException savedException = null; |
| 670 | if (mTransactionListener != null) { |
| 671 | try { |
| 672 | if (mTransactionIsSuccessful) { |
| 673 | mTransactionListener.onCommit(); |
| 674 | } else { |
| 675 | mTransactionListener.onRollback(); |
| 676 | } |
| 677 | } catch (RuntimeException e) { |
| 678 | savedException = e; |
| 679 | mTransactionIsSuccessful = false; |
| 680 | } |
| 681 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 682 | if (mTransactionIsSuccessful) { |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 683 | execSQL(COMMIT_SQL); |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 684 | // if write-ahead logging is used, we have to take care of checkpoint. |
| 685 | // TODO: should applications be given the flexibility of choosing when to |
| 686 | // trigger checkpoint? |
| 687 | // for now, do checkpoint after every COMMIT because that is the fastest |
| 688 | // way to guarantee that readers will see latest data. |
| 689 | // but this is the slowest way to run sqlite with in write-ahead logging mode. |
| 690 | if (this.mConnectionPool != null) { |
| 691 | execSQL("PRAGMA wal_checkpoint;"); |
| 692 | if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { |
| 693 | Log.i(TAG, "PRAGMA wal_Checkpoint done"); |
| 694 | } |
| 695 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 696 | } else { |
| 697 | try { |
| 698 | execSQL("ROLLBACK;"); |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 699 | if (savedException != null) { |
| 700 | throw savedException; |
| 701 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 702 | } catch (SQLException e) { |
| 703 | if (Config.LOGD) { |
| 704 | Log.d(TAG, "exception during rollback, maybe the DB previously " |
| 705 | + "performed an auto-rollback"); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | } finally { |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 710 | mTransactionListener = null; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 711 | unlockForced(); |
| 712 | if (Config.LOGV) { |
| 713 | Log.v(TAG, "unlocked " + Thread.currentThread() |
| 714 | + ", holdCount is " + mLock.getHoldCount()); |
| 715 | } |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | /** |
| 720 | * Marks the current transaction as successful. Do not do any more database work between |
| 721 | * calling this and calling endTransaction. Do as little non-database work as possible in that |
| 722 | * situation too. If any errors are encountered between this and endTransaction the transaction |
| 723 | * will still be committed. |
| 724 | * |
| 725 | * @throws IllegalStateException if the current thread is not in a transaction or the |
| 726 | * transaction is already marked as successful. |
| 727 | */ |
| 728 | public void setTransactionSuccessful() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 729 | verifyDbIsOpen(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 730 | if (!mLock.isHeldByCurrentThread()) { |
| 731 | throw new IllegalStateException("no transaction pending"); |
| 732 | } |
| 733 | if (mInnerTransactionIsSuccessful) { |
| 734 | throw new IllegalStateException( |
| 735 | "setTransactionSuccessful may only be called once per call to beginTransaction"); |
| 736 | } |
| 737 | mInnerTransactionIsSuccessful = true; |
| 738 | } |
| 739 | |
| 740 | /** |
| 741 | * return true if there is a transaction pending |
| 742 | */ |
| 743 | public boolean inTransaction() { |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 744 | return mLock.getHoldCount() > 0 || mTransactionUsingExecSql; |
| 745 | } |
| 746 | |
| 747 | /* package */ synchronized void setTransactionUsingExecSqlFlag() { |
| 748 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 749 | Log.i(TAG, "found execSQL('begin transaction')"); |
| 750 | } |
| 751 | mTransactionUsingExecSql = true; |
| 752 | } |
| 753 | |
| 754 | /* package */ synchronized void resetTransactionUsingExecSqlFlag() { |
| 755 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 756 | if (mTransactionUsingExecSql) { |
| 757 | Log.i(TAG, "found execSQL('commit or end or rollback')"); |
| 758 | } |
| 759 | } |
| 760 | mTransactionUsingExecSql = false; |
| 761 | } |
| 762 | |
| 763 | /** |
| 764 | * Returns true if the caller is considered part of the current transaction, if any. |
| 765 | * <p> |
| 766 | * Caller is part of the current transaction if either of the following is true |
| 767 | * <ol> |
| 768 | * <li>If transaction is started by calling beginTransaction() methods AND if the caller is |
| 769 | * in the same thread as the thread that started the transaction. |
| 770 | * </li> |
| 771 | * <li>If the transaction is started by calling {@link #execSQL(String)} like this: |
| 772 | * execSQL("BEGIN transaction"). In this case, every thread in the process is considered |
| 773 | * part of the current transaction.</li> |
| 774 | * </ol> |
| 775 | * |
| 776 | * @return true if the caller is considered part of the current transaction, if any. |
| 777 | */ |
| 778 | /* package */ synchronized boolean amIInTransaction() { |
| 779 | // always do this test on the main database connection - NOT on pooled database connection |
| 780 | // since transactions always occur on the main database connections only. |
| 781 | SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this; |
| 782 | boolean b = (!db.inTransaction()) ? false : |
| 783 | db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread(); |
| 784 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 785 | Log.i(TAG, "amIinTransaction: " + b); |
| 786 | } |
| 787 | return b; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 788 | } |
| 789 | |
| 790 | /** |
| 791 | * Checks if the database lock is held by this thread. |
| 792 | * |
| 793 | * @return true, if this thread is holding the database lock. |
| 794 | */ |
| 795 | public boolean isDbLockedByCurrentThread() { |
| 796 | return mLock.isHeldByCurrentThread(); |
| 797 | } |
| 798 | |
| 799 | /** |
| 800 | * Checks if the database is locked by another thread. This is |
| 801 | * just an estimate, since this status can change at any time, |
| 802 | * including after the call is made but before the result has |
| 803 | * been acted upon. |
| 804 | * |
| 805 | * @return true, if the database is locked by another thread |
| 806 | */ |
| 807 | public boolean isDbLockedByOtherThreads() { |
| 808 | return !mLock.isHeldByCurrentThread() && mLock.isLocked(); |
| 809 | } |
| 810 | |
| 811 | /** |
| 812 | * Temporarily end the transaction to let other threads run. The transaction is assumed to be |
| 813 | * successful so far. Do not call setTransactionSuccessful before calling this. When this |
| 814 | * returns a new transaction will have been created but not marked as successful. |
| 815 | * @return true if the transaction was yielded |
| 816 | * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock |
| 817 | * will not be yielded. Use yieldIfContendedSafely instead. |
| 818 | */ |
Dianne Hackborn | 4a51c20 | 2009-08-21 15:14:02 -0700 | [diff] [blame] | 819 | @Deprecated |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 820 | public boolean yieldIfContended() { |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 821 | return yieldIfContendedHelper(false /* do not check yielding */, |
| 822 | -1 /* sleepAfterYieldDelay */); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 823 | } |
| 824 | |
| 825 | /** |
| 826 | * Temporarily end the transaction to let other threads run. The transaction is assumed to be |
| 827 | * successful so far. Do not call setTransactionSuccessful before calling this. When this |
| 828 | * returns a new transaction will have been created but not marked as successful. This assumes |
| 829 | * that there are no nested transactions (beginTransaction has only been called once) and will |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 830 | * throw an exception if that is not the case. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 831 | * @return true if the transaction was yielded |
| 832 | */ |
| 833 | public boolean yieldIfContendedSafely() { |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 834 | return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 835 | } |
| 836 | |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 837 | /** |
| 838 | * Temporarily end the transaction to let other threads run. The transaction is assumed to be |
| 839 | * successful so far. Do not call setTransactionSuccessful before calling this. When this |
| 840 | * returns a new transaction will have been created but not marked as successful. This assumes |
| 841 | * that there are no nested transactions (beginTransaction has only been called once) and will |
| 842 | * throw an exception if that is not the case. |
| 843 | * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if |
| 844 | * the lock was actually yielded. This will allow other background threads to make some |
| 845 | * more progress than they would if we started the transaction immediately. |
| 846 | * @return true if the transaction was yielded |
| 847 | */ |
| 848 | public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) { |
| 849 | return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay); |
| 850 | } |
| 851 | |
| 852 | private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 853 | if (mLock.getQueueLength() == 0) { |
| 854 | // Reset the lock acquire time since we know that the thread was willing to yield |
| 855 | // the lock at this time. |
| 856 | mLockAcquiredWallTime = SystemClock.elapsedRealtime(); |
| 857 | mLockAcquiredThreadTime = Debug.threadCpuTimeNanos(); |
| 858 | return false; |
| 859 | } |
| 860 | setTransactionSuccessful(); |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 861 | SQLiteTransactionListener transactionListener = mTransactionListener; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 862 | endTransaction(); |
| 863 | if (checkFullyYielded) { |
| 864 | if (this.isDbLockedByCurrentThread()) { |
| 865 | throw new IllegalStateException( |
| 866 | "Db locked more than once. yielfIfContended cannot yield"); |
| 867 | } |
| 868 | } |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 869 | if (sleepAfterYieldDelay > 0) { |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 870 | // Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to |
| 871 | // check if anyone is using the database. If the database is not contended, |
| 872 | // retake the lock and return. |
| 873 | long remainingDelay = sleepAfterYieldDelay; |
| 874 | while (remainingDelay > 0) { |
| 875 | try { |
| 876 | Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ? |
| 877 | remainingDelay : SLEEP_AFTER_YIELD_QUANTUM); |
| 878 | } catch (InterruptedException e) { |
| 879 | Thread.interrupted(); |
| 880 | } |
| 881 | remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM; |
| 882 | if (mLock.getQueueLength() == 0) { |
| 883 | break; |
| 884 | } |
Fred Quintana | 5c7aede | 2009-08-27 21:41:27 -0700 | [diff] [blame] | 885 | } |
| 886 | } |
Fred Quintana | c4516a7 | 2009-09-03 12:14:06 -0700 | [diff] [blame] | 887 | beginTransactionWithListener(transactionListener); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 888 | return true; |
| 889 | } |
| 890 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 891 | /** |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 892 | * @deprecated This method no longer serves any useful purpose and has been deprecated. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 893 | */ |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 894 | @Deprecated |
| 895 | public Map<String, String> getSyncedTables() { |
| 896 | return new HashMap<String, String>(0); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 897 | } |
| 898 | |
| 899 | /** |
| 900 | * Used to allow returning sub-classes of {@link Cursor} when calling query. |
| 901 | */ |
| 902 | public interface CursorFactory { |
| 903 | /** |
| 904 | * See |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 905 | * {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 906 | */ |
| 907 | public Cursor newCursor(SQLiteDatabase db, |
| 908 | SQLiteCursorDriver masterQuery, String editTable, |
| 909 | SQLiteQuery query); |
| 910 | } |
| 911 | |
| 912 | /** |
| 913 | * Open the database according to the flags {@link #OPEN_READWRITE} |
| 914 | * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}. |
| 915 | * |
| 916 | * <p>Sets the locale of the database to the the system's current locale. |
| 917 | * Call {@link #setLocale} if you would like something else.</p> |
| 918 | * |
| 919 | * @param path to database file to open and/or create |
| 920 | * @param factory an optional factory class that is called to instantiate a |
| 921 | * cursor when query is called, or null for default |
| 922 | * @param flags to control database access mode |
| 923 | * @return the newly opened database |
| 924 | * @throws SQLiteException if the database cannot be opened |
| 925 | */ |
| 926 | public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) { |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 927 | return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler()); |
| 928 | } |
| 929 | |
| 930 | /** |
Vasu Nori | 74f170f | 2010-06-01 18:06:18 -0700 | [diff] [blame] | 931 | * Open the database according to the flags {@link #OPEN_READWRITE} |
| 932 | * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}. |
| 933 | * |
| 934 | * <p>Sets the locale of the database to the the system's current locale. |
| 935 | * Call {@link #setLocale} if you would like something else.</p> |
| 936 | * |
| 937 | * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be |
| 938 | * used to handle corruption when sqlite reports database corruption.</p> |
| 939 | * |
| 940 | * @param path to database file to open and/or create |
| 941 | * @param factory an optional factory class that is called to instantiate a |
| 942 | * cursor when query is called, or null for default |
| 943 | * @param flags to control database access mode |
| 944 | * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption |
| 945 | * when sqlite reports database corruption |
| 946 | * @return the newly opened database |
| 947 | * @throws SQLiteException if the database cannot be opened |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 948 | */ |
| 949 | public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags, |
| 950 | DatabaseErrorHandler errorHandler) { |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 951 | SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler, |
| 952 | (short) 0 /* the main connection handle */); |
Vasu Nori | a8c2490 | 2010-06-01 11:30:27 -0700 | [diff] [blame] | 953 | |
| 954 | // set sqlite pagesize to mBlockSize |
| 955 | if (sBlockSize == 0) { |
| 956 | // TODO: "/data" should be a static final String constant somewhere. it is hardcoded |
| 957 | // in several places right now. |
| 958 | sBlockSize = new StatFs("/data").getBlockSize(); |
| 959 | } |
| 960 | sqliteDatabase.setPageSize(sBlockSize); |
Vasu Nori | 57feb5d | 2010-06-22 10:39:04 -0700 | [diff] [blame] | 961 | //STOPSHIP - uncomment the following line |
| 962 | //sqliteDatabase.setJournalMode(path, "TRUNCATE"); |
| 963 | // STOPSHIP remove the following lines |
Vasu Nori | 7b04c41 | 2010-07-20 10:31:21 -0700 | [diff] [blame] | 964 | if (!path.equalsIgnoreCase(MEMORY_DB_PATH)) { |
| 965 | sqliteDatabase.enableWriteAheadLogging(); |
| 966 | } |
| 967 | // END STOPSHIP |
Vasu Nori | f9e2bd0 | 2010-06-04 16:49:51 -0700 | [diff] [blame] | 968 | |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 969 | // add this database to the list of databases opened in this process |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 970 | synchronized(mActiveDatabases) { |
| 971 | mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase)); |
| 972 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 973 | return sqliteDatabase; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 974 | } |
| 975 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 976 | private static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags, |
| 977 | DatabaseErrorHandler errorHandler, short connectionNum) { |
| 978 | SQLiteDatabase db = new SQLiteDatabase(path, factory, flags, errorHandler, connectionNum); |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 979 | try { |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 980 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 981 | Log.i(TAG, "opening the db : " + path); |
| 982 | } |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 983 | // Open the database. |
| 984 | db.dbopen(path, flags); |
| 985 | db.setLocale(Locale.getDefault()); |
| 986 | if (SQLiteDebug.DEBUG_SQL_STATEMENTS) { |
| 987 | db.enableSqlTracing(path, connectionNum); |
| 988 | } |
| 989 | if (SQLiteDebug.DEBUG_SQL_TIME) { |
| 990 | db.enableSqlProfiling(path, connectionNum); |
| 991 | } |
| 992 | return db; |
| 993 | } catch (SQLiteDatabaseCorruptException e) { |
| 994 | db.mErrorHandler.onCorruption(db); |
| 995 | return SQLiteDatabase.openDatabase(path, factory, flags, errorHandler); |
| 996 | } catch (SQLiteException e) { |
| 997 | Log.e(TAG, "Failed to open the database. closing it.", e); |
| 998 | db.close(); |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 999 | throw e; |
| 1000 | } |
| 1001 | } |
| 1002 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1003 | /** |
| 1004 | * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY). |
| 1005 | */ |
| 1006 | public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) { |
| 1007 | return openOrCreateDatabase(file.getPath(), factory); |
| 1008 | } |
| 1009 | |
| 1010 | /** |
| 1011 | * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY). |
| 1012 | */ |
| 1013 | public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) { |
| 1014 | return openDatabase(path, factory, CREATE_IF_NECESSARY); |
| 1015 | } |
| 1016 | |
| 1017 | /** |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1018 | * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler). |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 1019 | */ |
| 1020 | public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory, |
| 1021 | DatabaseErrorHandler errorHandler) { |
| 1022 | return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler); |
| 1023 | } |
| 1024 | |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 1025 | private void setJournalMode(final String dbPath, final String mode) { |
| 1026 | // journal mode can be set only for non-memory databases |
| 1027 | if (!dbPath.equalsIgnoreCase(MEMORY_DB_PATH)) { |
| 1028 | String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null); |
| 1029 | if (!s.equalsIgnoreCase(mode)) { |
| 1030 | Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + dbPath + |
| 1031 | " (on pragma set journal_mode, sqlite returned:" + s); |
| 1032 | } |
| 1033 | } |
| 1034 | } |
| 1035 | |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 1036 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1037 | * Create a memory backed SQLite database. Its contents will be destroyed |
| 1038 | * when the database is closed. |
| 1039 | * |
| 1040 | * <p>Sets the locale of the database to the the system's current locale. |
| 1041 | * Call {@link #setLocale} if you would like something else.</p> |
| 1042 | * |
| 1043 | * @param factory an optional factory class that is called to instantiate a |
| 1044 | * cursor when query is called |
| 1045 | * @return a SQLiteDatabase object, or null if the database can't be created |
| 1046 | */ |
| 1047 | public static SQLiteDatabase create(CursorFactory factory) { |
| 1048 | // This is a magic string with special meaning for SQLite. |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 1049 | return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1050 | } |
| 1051 | |
| 1052 | /** |
| 1053 | * Close the database. |
| 1054 | */ |
| 1055 | public void close() { |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 1056 | if (!isOpen()) { |
| 1057 | return; // already closed |
| 1058 | } |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1059 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
Vasu Nori | 7501010 | 2010-07-01 16:23:06 -0700 | [diff] [blame] | 1060 | Log.i(TAG, "closing db: " + mPath + " (connection # " + mConnectionNum); |
| 1061 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1062 | lock(); |
| 1063 | try { |
| 1064 | closeClosable(); |
Vasu Nori | fea6f6d | 2010-05-21 15:36:06 -0700 | [diff] [blame] | 1065 | // finalize ALL statements queued up so far |
| 1066 | closePendingStatements(); |
Mike Lockwood | 9d9c1be | 2010-07-13 19:27:52 -0400 | [diff] [blame] | 1067 | releaseCustomFunctions(); |
Vasu Nori | f6373e9 | 2010-03-16 10:21:00 -0700 | [diff] [blame] | 1068 | // close this database instance - regardless of its reference count value |
Vasu Nori | ad239ab | 2010-06-14 16:58:47 -0700 | [diff] [blame] | 1069 | dbclose(); |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1070 | if (mConnectionPool != null) { |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1071 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 1072 | assert mConnectionPool != null; |
| 1073 | Log.i(TAG, mConnectionPool.toString()); |
| 1074 | } |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1075 | mConnectionPool.close(); |
| 1076 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1077 | } finally { |
| 1078 | unlock(); |
| 1079 | } |
| 1080 | } |
| 1081 | |
| 1082 | private void closeClosable() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1083 | /* deallocate all compiled SQL statement objects from mCompiledQueries cache. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 1084 | * this should be done before de-referencing all {@link SQLiteClosable} objects |
| 1085 | * from this database object because calling |
| 1086 | * {@link SQLiteClosable#onAllReferencesReleasedFromContainer()} could cause the database |
| 1087 | * to be closed. sqlite doesn't let a database close if there are |
| 1088 | * any unfinalized statements - such as the compiled-sql objects in mCompiledQueries. |
| 1089 | */ |
| 1090 | deallocCachedSqlStatements(); |
| 1091 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1092 | Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator(); |
| 1093 | while (iter.hasNext()) { |
| 1094 | Map.Entry<SQLiteClosable, Object> entry = iter.next(); |
| 1095 | SQLiteClosable program = entry.getKey(); |
| 1096 | if (program != null) { |
| 1097 | program.onAllReferencesReleasedFromContainer(); |
| 1098 | } |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1099 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1100 | } |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1101 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1102 | /** |
| 1103 | * Native call to close the database. |
| 1104 | */ |
| 1105 | private native void dbclose(); |
| 1106 | |
| 1107 | /** |
Mike Lockwood | 9d9c1be | 2010-07-13 19:27:52 -0400 | [diff] [blame] | 1108 | * A callback interface for a custom sqlite3 function. |
| 1109 | * This can be used to create a function that can be called from |
| 1110 | * sqlite3 database triggers. |
| 1111 | * @hide |
| 1112 | */ |
| 1113 | public interface CustomFunction { |
| 1114 | public void callback(String[] args); |
| 1115 | } |
| 1116 | |
| 1117 | /** |
| 1118 | * Registers a CustomFunction callback as a function that can be called from |
| 1119 | * sqlite3 database triggers. |
| 1120 | * @param name the name of the sqlite3 function |
| 1121 | * @param numArgs the number of arguments for the function |
| 1122 | * @param function callback to call when the function is executed |
| 1123 | * @hide |
| 1124 | */ |
| 1125 | public void addCustomFunction(String name, int numArgs, CustomFunction function) { |
| 1126 | verifyDbIsOpen(); |
| 1127 | synchronized (mCustomFunctions) { |
| 1128 | int ref = native_addCustomFunction(name, numArgs, function); |
| 1129 | if (ref != 0) { |
| 1130 | // save a reference to the function for cleanup later |
| 1131 | mCustomFunctions.add(new Integer(ref)); |
| 1132 | } else { |
| 1133 | throw new SQLiteException("failed to add custom function " + name); |
| 1134 | } |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | private void releaseCustomFunctions() { |
| 1139 | synchronized (mCustomFunctions) { |
| 1140 | for (int i = 0; i < mCustomFunctions.size(); i++) { |
| 1141 | Integer function = mCustomFunctions.get(i); |
| 1142 | native_releaseCustomFunction(function.intValue()); |
| 1143 | } |
| 1144 | mCustomFunctions.clear(); |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | // list of CustomFunction references so we can clean up when the database closes |
| 1149 | private final ArrayList<Integer> mCustomFunctions = |
| 1150 | new ArrayList<Integer>(); |
| 1151 | |
| 1152 | private native int native_addCustomFunction(String name, int numArgs, CustomFunction function); |
| 1153 | private native void native_releaseCustomFunction(int function); |
| 1154 | |
| 1155 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1156 | * Gets the database version. |
| 1157 | * |
| 1158 | * @return the database version |
| 1159 | */ |
| 1160 | public int getVersion() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1161 | return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1162 | } |
| 1163 | |
| 1164 | /** |
| 1165 | * Sets the database version. |
| 1166 | * |
| 1167 | * @param version the new database version |
| 1168 | */ |
| 1169 | public void setVersion(int version) { |
| 1170 | execSQL("PRAGMA user_version = " + version); |
| 1171 | } |
| 1172 | |
| 1173 | /** |
| 1174 | * Returns the maximum size the database may grow to. |
| 1175 | * |
| 1176 | * @return the new maximum database size |
| 1177 | */ |
| 1178 | public long getMaximumSize() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1179 | long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null); |
| 1180 | return pageCount * getPageSize(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1181 | } |
| 1182 | |
| 1183 | /** |
| 1184 | * Sets the maximum size the database will grow to. The maximum size cannot |
| 1185 | * be set below the current size. |
| 1186 | * |
| 1187 | * @param numBytes the maximum database size, in bytes |
| 1188 | * @return the new maximum database size |
| 1189 | */ |
| 1190 | public long setMaximumSize(long numBytes) { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1191 | long pageSize = getPageSize(); |
| 1192 | long numPages = numBytes / pageSize; |
| 1193 | // If numBytes isn't a multiple of pageSize, bump up a page |
| 1194 | if ((numBytes % pageSize) != 0) { |
| 1195 | numPages++; |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 1196 | } |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1197 | long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages, |
| 1198 | null); |
| 1199 | return newPageCount * pageSize; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1200 | } |
| 1201 | |
| 1202 | /** |
| 1203 | * Returns the current database page size, in bytes. |
| 1204 | * |
| 1205 | * @return the database page size, in bytes |
| 1206 | */ |
| 1207 | public long getPageSize() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1208 | return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1209 | } |
| 1210 | |
| 1211 | /** |
| 1212 | * Sets the database page size. The page size must be a power of two. This |
| 1213 | * method does not work if any data has been written to the database file, |
| 1214 | * and must be called right after the database has been created. |
| 1215 | * |
| 1216 | * @param numBytes the database page size, in bytes |
| 1217 | */ |
| 1218 | public void setPageSize(long numBytes) { |
| 1219 | execSQL("PRAGMA page_size = " + numBytes); |
| 1220 | } |
| 1221 | |
| 1222 | /** |
| 1223 | * Mark this table as syncable. When an update occurs in this table the |
| 1224 | * _sync_dirty field will be set to ensure proper syncing operation. |
| 1225 | * |
| 1226 | * @param table the table to mark as syncable |
| 1227 | * @param deletedTable The deleted table that corresponds to the |
| 1228 | * syncable table |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 1229 | * @deprecated This method no longer serves any useful purpose and has been deprecated. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1230 | */ |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 1231 | @Deprecated |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1232 | public void markTableSyncable(String table, String deletedTable) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1233 | } |
| 1234 | |
| 1235 | /** |
| 1236 | * Mark this table as syncable, with the _sync_dirty residing in another |
| 1237 | * table. When an update occurs in this table the _sync_dirty field of the |
| 1238 | * row in updateTable with the _id in foreignKey will be set to |
| 1239 | * ensure proper syncing operation. |
| 1240 | * |
| 1241 | * @param table an update on this table will trigger a sync time removal |
| 1242 | * @param foreignKey this is the column in table whose value is an _id in |
| 1243 | * updateTable |
| 1244 | * @param updateTable this is the table that will have its _sync_dirty |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 1245 | * @deprecated This method no longer serves any useful purpose and has been deprecated. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1246 | */ |
Vasu Nori | 9567513 | 2010-07-21 16:24:40 -0700 | [diff] [blame] | 1247 | @Deprecated |
| 1248 | public void markTableSyncable(String table, String foreignKey, String updateTable) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1249 | } |
| 1250 | |
| 1251 | /** |
| 1252 | * Finds the name of the first table, which is editable. |
| 1253 | * |
| 1254 | * @param tables a list of tables |
| 1255 | * @return the first table listed |
| 1256 | */ |
| 1257 | public static String findEditTable(String tables) { |
| 1258 | if (!TextUtils.isEmpty(tables)) { |
| 1259 | // find the first word terminated by either a space or a comma |
| 1260 | int spacepos = tables.indexOf(' '); |
| 1261 | int commapos = tables.indexOf(','); |
| 1262 | |
| 1263 | if (spacepos > 0 && (spacepos < commapos || commapos < 0)) { |
| 1264 | return tables.substring(0, spacepos); |
| 1265 | } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) { |
| 1266 | return tables.substring(0, commapos); |
| 1267 | } |
| 1268 | return tables; |
| 1269 | } else { |
| 1270 | throw new IllegalStateException("Invalid tables"); |
| 1271 | } |
| 1272 | } |
| 1273 | |
| 1274 | /** |
| 1275 | * Compiles an SQL statement into a reusable pre-compiled statement object. |
| 1276 | * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the |
| 1277 | * statement and fill in those values with {@link SQLiteProgram#bindString} |
| 1278 | * and {@link SQLiteProgram#bindLong} each time you want to run the |
| 1279 | * statement. Statements may not return result sets larger than 1x1. |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 1280 | *<p> |
| 1281 | * No two threads should be using the same {@link SQLiteStatement} at the same time. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1282 | * |
| 1283 | * @param sql The raw SQL statement, may contain ? for unknown values to be |
| 1284 | * bound later. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1285 | * @return A pre-compiled {@link SQLiteStatement} object. Note that |
| 1286 | * {@link SQLiteStatement}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1287 | */ |
| 1288 | public SQLiteStatement compileStatement(String sql) throws SQLException { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1289 | verifyDbIsOpen(); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1290 | return new SQLiteStatement(this, sql, null); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1291 | } |
| 1292 | |
| 1293 | /** |
| 1294 | * Query the given URL, returning a {@link Cursor} over the result set. |
| 1295 | * |
| 1296 | * @param distinct true if you want each row to be unique, false otherwise. |
| 1297 | * @param table The table name to compile the query against. |
| 1298 | * @param columns A list of which columns to return. Passing null will |
| 1299 | * return all columns, which is discouraged to prevent reading |
| 1300 | * data from storage that isn't going to be used. |
| 1301 | * @param selection A filter declaring which rows to return, formatted as an |
| 1302 | * SQL WHERE clause (excluding the WHERE itself). Passing null |
| 1303 | * will return all rows for the given table. |
| 1304 | * @param selectionArgs You may include ?s in selection, which will be |
| 1305 | * replaced by the values from selectionArgs, in order that they |
| 1306 | * appear in the selection. The values will be bound as Strings. |
| 1307 | * @param groupBy A filter declaring how to group rows, formatted as an SQL |
| 1308 | * GROUP BY clause (excluding the GROUP BY itself). Passing null |
| 1309 | * will cause the rows to not be grouped. |
| 1310 | * @param having A filter declare which row groups to include in the cursor, |
| 1311 | * if row grouping is being used, formatted as an SQL HAVING |
| 1312 | * clause (excluding the HAVING itself). Passing null will cause |
| 1313 | * all row groups to be included, and is required when row |
| 1314 | * grouping is not being used. |
| 1315 | * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause |
| 1316 | * (excluding the ORDER BY itself). Passing null will use the |
| 1317 | * default sort order, which may be unordered. |
| 1318 | * @param limit Limits the number of rows returned by the query, |
| 1319 | * formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1320 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1321 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1322 | * @see Cursor |
| 1323 | */ |
| 1324 | public Cursor query(boolean distinct, String table, String[] columns, |
| 1325 | String selection, String[] selectionArgs, String groupBy, |
| 1326 | String having, String orderBy, String limit) { |
| 1327 | return queryWithFactory(null, distinct, table, columns, selection, selectionArgs, |
| 1328 | groupBy, having, orderBy, limit); |
| 1329 | } |
| 1330 | |
| 1331 | /** |
| 1332 | * Query the given URL, returning a {@link Cursor} over the result set. |
| 1333 | * |
| 1334 | * @param cursorFactory the cursor factory to use, or null for the default factory |
| 1335 | * @param distinct true if you want each row to be unique, false otherwise. |
| 1336 | * @param table The table name to compile the query against. |
| 1337 | * @param columns A list of which columns to return. Passing null will |
| 1338 | * return all columns, which is discouraged to prevent reading |
| 1339 | * data from storage that isn't going to be used. |
| 1340 | * @param selection A filter declaring which rows to return, formatted as an |
| 1341 | * SQL WHERE clause (excluding the WHERE itself). Passing null |
| 1342 | * will return all rows for the given table. |
| 1343 | * @param selectionArgs You may include ?s in selection, which will be |
| 1344 | * replaced by the values from selectionArgs, in order that they |
| 1345 | * appear in the selection. The values will be bound as Strings. |
| 1346 | * @param groupBy A filter declaring how to group rows, formatted as an SQL |
| 1347 | * GROUP BY clause (excluding the GROUP BY itself). Passing null |
| 1348 | * will cause the rows to not be grouped. |
| 1349 | * @param having A filter declare which row groups to include in the cursor, |
| 1350 | * if row grouping is being used, formatted as an SQL HAVING |
| 1351 | * clause (excluding the HAVING itself). Passing null will cause |
| 1352 | * all row groups to be included, and is required when row |
| 1353 | * grouping is not being used. |
| 1354 | * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause |
| 1355 | * (excluding the ORDER BY itself). Passing null will use the |
| 1356 | * default sort order, which may be unordered. |
| 1357 | * @param limit Limits the number of rows returned by the query, |
| 1358 | * formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1359 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1360 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1361 | * @see Cursor |
| 1362 | */ |
| 1363 | public Cursor queryWithFactory(CursorFactory cursorFactory, |
| 1364 | boolean distinct, String table, String[] columns, |
| 1365 | String selection, String[] selectionArgs, String groupBy, |
| 1366 | String having, String orderBy, String limit) { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1367 | verifyDbIsOpen(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1368 | String sql = SQLiteQueryBuilder.buildQueryString( |
| 1369 | distinct, table, columns, selection, groupBy, having, orderBy, limit); |
| 1370 | |
| 1371 | return rawQueryWithFactory( |
| 1372 | cursorFactory, sql, selectionArgs, findEditTable(table)); |
| 1373 | } |
| 1374 | |
| 1375 | /** |
| 1376 | * Query the given table, returning a {@link Cursor} over the result set. |
| 1377 | * |
| 1378 | * @param table The table name to compile the query against. |
| 1379 | * @param columns A list of which columns to return. Passing null will |
| 1380 | * return all columns, which is discouraged to prevent reading |
| 1381 | * data from storage that isn't going to be used. |
| 1382 | * @param selection A filter declaring which rows to return, formatted as an |
| 1383 | * SQL WHERE clause (excluding the WHERE itself). Passing null |
| 1384 | * will return all rows for the given table. |
| 1385 | * @param selectionArgs You may include ?s in selection, which will be |
| 1386 | * replaced by the values from selectionArgs, in order that they |
| 1387 | * appear in the selection. The values will be bound as Strings. |
| 1388 | * @param groupBy A filter declaring how to group rows, formatted as an SQL |
| 1389 | * GROUP BY clause (excluding the GROUP BY itself). Passing null |
| 1390 | * will cause the rows to not be grouped. |
| 1391 | * @param having A filter declare which row groups to include in the cursor, |
| 1392 | * if row grouping is being used, formatted as an SQL HAVING |
| 1393 | * clause (excluding the HAVING itself). Passing null will cause |
| 1394 | * all row groups to be included, and is required when row |
| 1395 | * grouping is not being used. |
| 1396 | * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause |
| 1397 | * (excluding the ORDER BY itself). Passing null will use the |
| 1398 | * default sort order, which may be unordered. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1399 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1400 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1401 | * @see Cursor |
| 1402 | */ |
| 1403 | public Cursor query(String table, String[] columns, String selection, |
| 1404 | String[] selectionArgs, String groupBy, String having, |
| 1405 | String orderBy) { |
| 1406 | |
| 1407 | return query(false, table, columns, selection, selectionArgs, groupBy, |
| 1408 | having, orderBy, null /* limit */); |
| 1409 | } |
| 1410 | |
| 1411 | /** |
| 1412 | * Query the given table, returning a {@link Cursor} over the result set. |
| 1413 | * |
| 1414 | * @param table The table name to compile the query against. |
| 1415 | * @param columns A list of which columns to return. Passing null will |
| 1416 | * return all columns, which is discouraged to prevent reading |
| 1417 | * data from storage that isn't going to be used. |
| 1418 | * @param selection A filter declaring which rows to return, formatted as an |
| 1419 | * SQL WHERE clause (excluding the WHERE itself). Passing null |
| 1420 | * will return all rows for the given table. |
| 1421 | * @param selectionArgs You may include ?s in selection, which will be |
| 1422 | * replaced by the values from selectionArgs, in order that they |
| 1423 | * appear in the selection. The values will be bound as Strings. |
| 1424 | * @param groupBy A filter declaring how to group rows, formatted as an SQL |
| 1425 | * GROUP BY clause (excluding the GROUP BY itself). Passing null |
| 1426 | * will cause the rows to not be grouped. |
| 1427 | * @param having A filter declare which row groups to include in the cursor, |
| 1428 | * if row grouping is being used, formatted as an SQL HAVING |
| 1429 | * clause (excluding the HAVING itself). Passing null will cause |
| 1430 | * all row groups to be included, and is required when row |
| 1431 | * grouping is not being used. |
| 1432 | * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause |
| 1433 | * (excluding the ORDER BY itself). Passing null will use the |
| 1434 | * default sort order, which may be unordered. |
| 1435 | * @param limit Limits the number of rows returned by the query, |
| 1436 | * formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1437 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1438 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1439 | * @see Cursor |
| 1440 | */ |
| 1441 | public Cursor query(String table, String[] columns, String selection, |
| 1442 | String[] selectionArgs, String groupBy, String having, |
| 1443 | String orderBy, String limit) { |
| 1444 | |
| 1445 | return query(false, table, columns, selection, selectionArgs, groupBy, |
| 1446 | having, orderBy, limit); |
| 1447 | } |
| 1448 | |
| 1449 | /** |
| 1450 | * Runs the provided SQL and returns a {@link Cursor} over the result set. |
| 1451 | * |
| 1452 | * @param sql the SQL query. The SQL string must not be ; terminated |
| 1453 | * @param selectionArgs You may include ?s in where clause in the query, |
| 1454 | * which will be replaced by the values from selectionArgs. The |
| 1455 | * values will be bound as Strings. |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1456 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1457 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1458 | */ |
| 1459 | public Cursor rawQuery(String sql, String[] selectionArgs) { |
| 1460 | return rawQueryWithFactory(null, sql, selectionArgs, null); |
| 1461 | } |
| 1462 | |
| 1463 | /** |
| 1464 | * Runs the provided SQL and returns a cursor over the result set. |
| 1465 | * |
| 1466 | * @param cursorFactory the cursor factory to use, or null for the default factory |
| 1467 | * @param sql the SQL query. The SQL string must not be ; terminated |
| 1468 | * @param selectionArgs You may include ?s in where clause in the query, |
| 1469 | * which will be replaced by the values from selectionArgs. The |
| 1470 | * values will be bound as Strings. |
| 1471 | * @param editTable the name of the first table, which is editable |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1472 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1473 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1474 | */ |
| 1475 | public Cursor rawQueryWithFactory( |
| 1476 | CursorFactory cursorFactory, String sql, String[] selectionArgs, |
| 1477 | String editTable) { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1478 | verifyDbIsOpen(); |
Brad Fitzpatrick | cfda9f3 | 2010-06-03 12:52:54 -0700 | [diff] [blame] | 1479 | BlockGuard.getThreadPolicy().onReadFromDisk(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1480 | long timeStart = 0; |
| 1481 | |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1482 | if (Config.LOGV || mSlowQueryThreshold != -1) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1483 | timeStart = System.currentTimeMillis(); |
| 1484 | } |
| 1485 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1486 | SQLiteDatabase db = getDbConnection(sql); |
| 1487 | SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1488 | |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1489 | Cursor cursor = null; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1490 | try { |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1491 | cursor = driver.query( |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1492 | cursorFactory != null ? cursorFactory : mFactory, |
| 1493 | selectionArgs); |
| 1494 | } finally { |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1495 | if (Config.LOGV || mSlowQueryThreshold != -1) { |
| 1496 | |
Vasu Nori | 020e534 | 2010-04-28 14:22:38 -0700 | [diff] [blame] | 1497 | // Force query execution |
| 1498 | int count = -1; |
| 1499 | if (cursor != null) { |
| 1500 | count = cursor.getCount(); |
| 1501 | } |
| 1502 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1503 | long duration = System.currentTimeMillis() - timeStart; |
| 1504 | |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1505 | if (Config.LOGV || duration >= mSlowQueryThreshold) { |
| 1506 | Log.v(SQLiteCursor.TAG, |
| 1507 | "query (" + duration + " ms): " + driver.toString() + ", args are " |
| 1508 | + (selectionArgs != null |
| 1509 | ? TextUtils.join(",", selectionArgs) |
Vasu Nori | 020e534 | 2010-04-28 14:22:38 -0700 | [diff] [blame] | 1510 | : "<null>") + ", count is " + count); |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1511 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1512 | } |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1513 | releaseDbConnection(db); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1514 | } |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1515 | return cursor; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1516 | } |
| 1517 | |
| 1518 | /** |
| 1519 | * Runs the provided SQL and returns a cursor over the result set. |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1520 | * The cursor will read an initial set of rows and the return to the caller. |
| 1521 | * It will continue to read in batches and send data changed notifications |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1522 | * when the later batches are ready. |
| 1523 | * @param sql the SQL query. The SQL string must not be ; terminated |
| 1524 | * @param selectionArgs You may include ?s in where clause in the query, |
| 1525 | * which will be replaced by the values from selectionArgs. The |
| 1526 | * values will be bound as Strings. |
| 1527 | * @param initialRead set the initial count of items to read from the cursor |
| 1528 | * @param maxRead set the count of items to read on each iteration after the first |
Jeff Hamilton | f3ca9a5 | 2010-05-12 15:04:33 -0700 | [diff] [blame] | 1529 | * @return A {@link Cursor} object, which is positioned before the first entry. Note that |
| 1530 | * {@link Cursor}s are not synchronized, see the documentation for more details. |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1531 | * |
Andy Stadler | f8a7cea | 2009-04-10 16:24:47 -0700 | [diff] [blame] | 1532 | * This work is incomplete and not fully tested or reviewed, so currently |
| 1533 | * hidden. |
| 1534 | * @hide |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1535 | */ |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1536 | public Cursor rawQuery(String sql, String[] selectionArgs, |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1537 | int initialRead, int maxRead) { |
| 1538 | SQLiteCursor c = (SQLiteCursor)rawQueryWithFactory( |
| 1539 | null, sql, selectionArgs, null); |
| 1540 | c.setLoadStyle(initialRead, maxRead); |
| 1541 | return c; |
| 1542 | } |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1543 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1544 | /** |
| 1545 | * Convenience method for inserting a row into the database. |
| 1546 | * |
| 1547 | * @param table the table to insert the row into |
| 1548 | * @param nullColumnHack SQL doesn't allow inserting a completely empty row, |
| 1549 | * so if initialValues is empty this column will explicitly be |
| 1550 | * assigned a NULL value |
| 1551 | * @param values this map contains the initial column values for the |
| 1552 | * row. The keys should be the column names and the values the |
| 1553 | * column values |
| 1554 | * @return the row ID of the newly inserted row, or -1 if an error occurred |
| 1555 | */ |
| 1556 | public long insert(String table, String nullColumnHack, ContentValues values) { |
| 1557 | try { |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1558 | return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1559 | } catch (SQLException e) { |
| 1560 | Log.e(TAG, "Error inserting " + values, e); |
| 1561 | return -1; |
| 1562 | } |
| 1563 | } |
| 1564 | |
| 1565 | /** |
| 1566 | * Convenience method for inserting a row into the database. |
| 1567 | * |
| 1568 | * @param table the table to insert the row into |
| 1569 | * @param nullColumnHack SQL doesn't allow inserting a completely empty row, |
| 1570 | * so if initialValues is empty this column will explicitly be |
| 1571 | * assigned a NULL value |
| 1572 | * @param values this map contains the initial column values for the |
| 1573 | * row. The keys should be the column names and the values the |
| 1574 | * column values |
| 1575 | * @throws SQLException |
| 1576 | * @return the row ID of the newly inserted row, or -1 if an error occurred |
| 1577 | */ |
| 1578 | public long insertOrThrow(String table, String nullColumnHack, ContentValues values) |
| 1579 | throws SQLException { |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1580 | return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1581 | } |
| 1582 | |
| 1583 | /** |
| 1584 | * Convenience method for replacing a row in the database. |
| 1585 | * |
| 1586 | * @param table the table in which to replace the row |
| 1587 | * @param nullColumnHack SQL doesn't allow inserting a completely empty row, |
| 1588 | * so if initialValues is empty this row will explicitly be |
| 1589 | * assigned a NULL value |
| 1590 | * @param initialValues this map contains the initial column values for |
| 1591 | * the row. The key |
| 1592 | * @return the row ID of the newly inserted row, or -1 if an error occurred |
| 1593 | */ |
| 1594 | public long replace(String table, String nullColumnHack, ContentValues initialValues) { |
| 1595 | try { |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1596 | return insertWithOnConflict(table, nullColumnHack, initialValues, |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1597 | CONFLICT_REPLACE); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1598 | } catch (SQLException e) { |
| 1599 | Log.e(TAG, "Error inserting " + initialValues, e); |
| 1600 | return -1; |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | /** |
| 1605 | * Convenience method for replacing a row in the database. |
| 1606 | * |
| 1607 | * @param table the table in which to replace the row |
| 1608 | * @param nullColumnHack SQL doesn't allow inserting a completely empty row, |
| 1609 | * so if initialValues is empty this row will explicitly be |
| 1610 | * assigned a NULL value |
| 1611 | * @param initialValues this map contains the initial column values for |
| 1612 | * the row. The key |
| 1613 | * @throws SQLException |
| 1614 | * @return the row ID of the newly inserted row, or -1 if an error occurred |
| 1615 | */ |
| 1616 | public long replaceOrThrow(String table, String nullColumnHack, |
| 1617 | ContentValues initialValues) throws SQLException { |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1618 | return insertWithOnConflict(table, nullColumnHack, initialValues, |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1619 | CONFLICT_REPLACE); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1620 | } |
| 1621 | |
| 1622 | /** |
| 1623 | * General method for inserting a row into the database. |
| 1624 | * |
| 1625 | * @param table the table to insert the row into |
| 1626 | * @param nullColumnHack SQL doesn't allow inserting a completely empty row, |
| 1627 | * so if initialValues is empty this column will explicitly be |
| 1628 | * assigned a NULL value |
| 1629 | * @param initialValues this map contains the initial column values for the |
| 1630 | * row. The keys should be the column names and the values the |
| 1631 | * column values |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1632 | * @param conflictAlgorithm for insert conflict resolver |
Vasu Nori | 6eb7c45 | 2010-01-27 14:31:24 -0800 | [diff] [blame] | 1633 | * @return the row ID of the newly inserted row |
| 1634 | * OR the primary key of the existing row if the input param 'conflictAlgorithm' = |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1635 | * {@link #CONFLICT_IGNORE} |
Vasu Nori | 6eb7c45 | 2010-01-27 14:31:24 -0800 | [diff] [blame] | 1636 | * OR -1 if any error |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1637 | */ |
| 1638 | public long insertWithOnConflict(String table, String nullColumnHack, |
Vasu Nori | 6eb7c45 | 2010-01-27 14:31:24 -0800 | [diff] [blame] | 1639 | ContentValues initialValues, int conflictAlgorithm) { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1640 | StringBuilder sql = new StringBuilder(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1641 | sql.append("INSERT"); |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1642 | sql.append(CONFLICT_VALUES[conflictAlgorithm]); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1643 | sql.append(" INTO "); |
| 1644 | sql.append(table); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1645 | sql.append('('); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1646 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1647 | Object[] bindArgs = null; |
| 1648 | int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0; |
| 1649 | if (size > 0) { |
| 1650 | bindArgs = new Object[size]; |
| 1651 | int i = 0; |
| 1652 | for (String colName : initialValues.keySet()) { |
| 1653 | sql.append((i > 0) ? "," : ""); |
| 1654 | sql.append(colName); |
| 1655 | bindArgs[i++] = initialValues.get(colName); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1656 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1657 | sql.append(')'); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1658 | sql.append(" VALUES ("); |
| 1659 | for (i = 0; i < size; i++) { |
| 1660 | sql.append((i > 0) ? ",?" : "?"); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1661 | } |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1662 | } else { |
| 1663 | sql.append(nullColumnHack + ") VALUES (NULL"); |
| 1664 | } |
| 1665 | sql.append(')'); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1666 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1667 | SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); |
| 1668 | try { |
Vasu Nori | fb16cbd | 2010-07-25 16:38:48 -0700 | [diff] [blame] | 1669 | return statement.executeInsert(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1670 | } catch (SQLiteDatabaseCorruptException e) { |
| 1671 | onCorruption(); |
| 1672 | throw e; |
| 1673 | } finally { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1674 | statement.close(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1675 | } |
| 1676 | } |
| 1677 | |
| 1678 | /** |
| 1679 | * Convenience method for deleting rows in the database. |
| 1680 | * |
| 1681 | * @param table the table to delete from |
| 1682 | * @param whereClause the optional WHERE clause to apply when deleting. |
| 1683 | * Passing null will delete all rows. |
| 1684 | * @return the number of rows affected if a whereClause is passed in, 0 |
| 1685 | * otherwise. To remove all rows and get a count pass "1" as the |
| 1686 | * whereClause. |
| 1687 | */ |
| 1688 | public int delete(String table, String whereClause, String[] whereArgs) { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1689 | SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table + |
| 1690 | (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1691 | try { |
Vasu Nori | fb16cbd | 2010-07-25 16:38:48 -0700 | [diff] [blame] | 1692 | return statement.executeUpdateDelete(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1693 | } catch (SQLiteDatabaseCorruptException e) { |
| 1694 | onCorruption(); |
| 1695 | throw e; |
| 1696 | } finally { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1697 | statement.close(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1698 | } |
| 1699 | } |
| 1700 | |
| 1701 | /** |
| 1702 | * Convenience method for updating rows in the database. |
| 1703 | * |
| 1704 | * @param table the table to update in |
| 1705 | * @param values a map from column names to new column values. null is a |
| 1706 | * valid value that will be translated to NULL. |
| 1707 | * @param whereClause the optional WHERE clause to apply when updating. |
| 1708 | * Passing null will update all rows. |
| 1709 | * @return the number of rows affected |
| 1710 | */ |
| 1711 | public int update(String table, ContentValues values, String whereClause, String[] whereArgs) { |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1712 | return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1713 | } |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1714 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1715 | /** |
| 1716 | * Convenience method for updating rows in the database. |
| 1717 | * |
| 1718 | * @param table the table to update in |
| 1719 | * @param values a map from column names to new column values. null is a |
| 1720 | * valid value that will be translated to NULL. |
| 1721 | * @param whereClause the optional WHERE clause to apply when updating. |
| 1722 | * Passing null will update all rows. |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1723 | * @param conflictAlgorithm for update conflict resolver |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1724 | * @return the number of rows affected |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1725 | */ |
Dmitri Plotnikov | 600bdd8 | 2009-09-01 12:12:20 -0700 | [diff] [blame] | 1726 | public int updateWithOnConflict(String table, ContentValues values, |
Vasu Nori | 6eb7c45 | 2010-01-27 14:31:24 -0800 | [diff] [blame] | 1727 | String whereClause, String[] whereArgs, int conflictAlgorithm) { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1728 | int setValuesSize = values.size(); |
| 1729 | if (values == null || setValuesSize == 0) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1730 | throw new IllegalArgumentException("Empty values"); |
| 1731 | } |
| 1732 | |
| 1733 | StringBuilder sql = new StringBuilder(120); |
| 1734 | sql.append("UPDATE "); |
Vasu Nori | 8d45e4e | 2010-02-05 22:35:47 -0800 | [diff] [blame] | 1735 | sql.append(CONFLICT_VALUES[conflictAlgorithm]); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1736 | sql.append(table); |
| 1737 | sql.append(" SET "); |
| 1738 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1739 | // move all bind args to one array |
| 1740 | int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length); |
| 1741 | Object[] bindArgs = new Object[bindArgsSize]; |
| 1742 | int i = 0; |
| 1743 | for (String colName : values.keySet()) { |
| 1744 | sql.append((i > 0) ? "," : ""); |
| 1745 | sql.append(colName); |
| 1746 | bindArgs[i++] = values.get(colName); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1747 | sql.append("=?"); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1748 | } |
| 1749 | if (whereArgs != null) { |
| 1750 | for (i = setValuesSize; i < bindArgsSize; i++) { |
| 1751 | bindArgs[i] = whereArgs[i - setValuesSize]; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1752 | } |
| 1753 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1754 | if (!TextUtils.isEmpty(whereClause)) { |
| 1755 | sql.append(" WHERE "); |
| 1756 | sql.append(whereClause); |
| 1757 | } |
| 1758 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1759 | SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1760 | try { |
Vasu Nori | fb16cbd | 2010-07-25 16:38:48 -0700 | [diff] [blame] | 1761 | return statement.executeUpdateDelete(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1762 | } catch (SQLiteDatabaseCorruptException e) { |
| 1763 | onCorruption(); |
| 1764 | throw e; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1765 | } finally { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1766 | statement.close(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1767 | } |
| 1768 | } |
| 1769 | |
| 1770 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1771 | * Execute a single SQL statement that is NOT a SELECT |
| 1772 | * or any other SQL statement that returns data. |
| 1773 | * <p> |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1774 | * It has no means to return any data (such as the number of affected rows). |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1775 | * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)}, |
| 1776 | * {@link #update(String, ContentValues, String, String[])}, et al, when possible. |
| 1777 | * </p> |
Vasu Nori | 9bf225e | 2010-07-07 16:38:28 -0700 | [diff] [blame] | 1778 | * <p> |
| 1779 | * When using {@link #enableWriteAheadLogging()}, journal_mode is |
| 1780 | * automatically managed by this class. So, do not set journal_mode |
| 1781 | * using "PRAGMA journal_mode'<value>" statement if your app is using |
| 1782 | * {@link #enableWriteAheadLogging()} |
| 1783 | * </p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1784 | * |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1785 | * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are |
| 1786 | * not supported. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1787 | * @throws SQLException If the SQL string is invalid for some reason |
| 1788 | */ |
| 1789 | public void execSQL(String sql) throws SQLException { |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1790 | int stmtType = DatabaseUtils.getSqlStatementType(sql); |
| 1791 | if (stmtType == DatabaseUtils.STATEMENT_ATTACH) { |
Vasu Nori | 8d11103 | 2010-06-22 18:34:21 -0700 | [diff] [blame] | 1792 | disableWriteAheadLogging(); |
| 1793 | } |
Vasu Nori | c8e1f23 | 2010-04-13 15:05:09 -0700 | [diff] [blame] | 1794 | long timeStart = SystemClock.uptimeMillis(); |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1795 | logTimeStat(mLastSqlStatement, timeStart, GET_LOCK_LOG_PREFIX); |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1796 | executeSql(sql, null); |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 1797 | |
| 1798 | // Log commit statements along with the most recently executed |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1799 | // SQL statement for disambiguation. |
| 1800 | if (stmtType == DatabaseUtils.STATEMENT_COMMIT) { |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1801 | logTimeStat(mLastSqlStatement, timeStart, COMMIT_SQL); |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 1802 | } else { |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1803 | logTimeStat(sql, timeStart, null); |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 1804 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1805 | } |
| 1806 | |
| 1807 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1808 | * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. |
| 1809 | * <p> |
| 1810 | * For INSERT statements, use any of the following instead. |
| 1811 | * <ul> |
| 1812 | * <li>{@link #insert(String, String, ContentValues)}</li> |
| 1813 | * <li>{@link #insertOrThrow(String, String, ContentValues)}</li> |
| 1814 | * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li> |
| 1815 | * </ul> |
| 1816 | * <p> |
| 1817 | * For UPDATE statements, use any of the following instead. |
| 1818 | * <ul> |
| 1819 | * <li>{@link #update(String, ContentValues, String, String[])}</li> |
| 1820 | * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li> |
| 1821 | * </ul> |
| 1822 | * <p> |
| 1823 | * For DELETE statements, use any of the following instead. |
| 1824 | * <ul> |
| 1825 | * <li>{@link #delete(String, String, String[])}</li> |
| 1826 | * </ul> |
| 1827 | * <p> |
| 1828 | * For example, the following are good candidates for using this method: |
| 1829 | * <ul> |
| 1830 | * <li>ALTER TABLE</li> |
| 1831 | * <li>CREATE or DROP table / trigger / view / index / virtual table</li> |
| 1832 | * <li>REINDEX</li> |
| 1833 | * <li>RELEASE</li> |
| 1834 | * <li>SAVEPOINT</li> |
| 1835 | * <li>PRAGMA that returns no data</li> |
| 1836 | * </ul> |
| 1837 | * </p> |
Vasu Nori | 9bf225e | 2010-07-07 16:38:28 -0700 | [diff] [blame] | 1838 | * <p> |
| 1839 | * When using {@link #enableWriteAheadLogging()}, journal_mode is |
| 1840 | * automatically managed by this class. So, do not set journal_mode |
| 1841 | * using "PRAGMA journal_mode'<value>" statement if your app is using |
| 1842 | * {@link #enableWriteAheadLogging()} |
| 1843 | * </p> |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1844 | * |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 1845 | * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are |
| 1846 | * not supported. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1847 | * @param bindArgs only byte[], String, Long and Double are supported in bindArgs. |
| 1848 | * @throws SQLException If the SQL string is invalid for some reason |
| 1849 | */ |
| 1850 | public void execSQL(String sql, Object[] bindArgs) throws SQLException { |
| 1851 | if (bindArgs == null) { |
| 1852 | throw new IllegalArgumentException("Empty bindArgs"); |
| 1853 | } |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 1854 | executeSql(sql, bindArgs); |
| 1855 | } |
| 1856 | |
| 1857 | private void executeSql(String sql, Object[] bindArgs) throws SQLException { |
Brad Fitzpatrick | d72f718 | 2010-02-11 17:07:51 -0800 | [diff] [blame] | 1858 | long timeStart = SystemClock.uptimeMillis(); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1859 | SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1860 | try { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1861 | statement.executeUpdateDelete(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1862 | } catch (SQLiteDatabaseCorruptException e) { |
| 1863 | onCorruption(); |
| 1864 | throw e; |
| 1865 | } finally { |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 1866 | statement.close(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1867 | } |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1868 | logTimeStat(sql, timeStart); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1869 | } |
| 1870 | |
| 1871 | @Override |
Mike Lockwood | 9d9c1be | 2010-07-13 19:27:52 -0400 | [diff] [blame] | 1872 | protected void finalize() throws Throwable { |
| 1873 | try { |
| 1874 | if (isOpen()) { |
| 1875 | Log.e(TAG, "close() was never explicitly called on database '" + |
| 1876 | mPath + "' ", mStackTrace); |
| 1877 | closeClosable(); |
| 1878 | onAllReferencesReleased(); |
| 1879 | releaseCustomFunctions(); |
| 1880 | } |
| 1881 | } finally { |
| 1882 | super.finalize(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1883 | } |
| 1884 | } |
| 1885 | |
| 1886 | /** |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 1887 | * Private constructor. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1888 | * |
| 1889 | * @param path The full path to the database |
| 1890 | * @param factory The factory to use when creating cursors, may be NULL. |
| 1891 | * @param flags 0 or {@link #NO_LOCALIZED_COLLATORS}. If the database file already |
| 1892 | * exists, mFlags will be updated appropriately. |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 1893 | * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite reports database |
| 1894 | * corruption. may be NULL. |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1895 | * @param connectionNum 0 for main database connection handle. 1..N for pooled database |
| 1896 | * connection handles. |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1897 | */ |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 1898 | private SQLiteDatabase(String path, CursorFactory factory, int flags, |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1899 | DatabaseErrorHandler errorHandler, short connectionNum) { |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1900 | if (path == null) { |
| 1901 | throw new IllegalArgumentException("path should not be null"); |
| 1902 | } |
| 1903 | mFlags = flags; |
| 1904 | mPath = path; |
Dmitri Plotnikov | 90142c9 | 2009-09-15 10:52:17 -0700 | [diff] [blame] | 1905 | mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1); |
Vasu Nori | 08b448e | 2010-03-03 10:05:16 -0800 | [diff] [blame] | 1906 | mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace(); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1907 | mFactory = factory; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1908 | mPrograms = new WeakHashMap<SQLiteClosable,Object>(); |
Vasu Nori | 2134369 | 2010-06-03 16:01:39 -0700 | [diff] [blame] | 1909 | // Set the DatabaseErrorHandler to be used when SQLite reports corruption. |
| 1910 | // If the caller sets errorHandler = null, then use default errorhandler. |
| 1911 | mErrorHandler = (errorHandler == null) ? new DefaultDatabaseErrorHandler() : errorHandler; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 1912 | mConnectionNum = connectionNum; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1913 | } |
| 1914 | |
| 1915 | /** |
| 1916 | * return whether the DB is opened as read only. |
| 1917 | * @return true if DB is opened as read only |
| 1918 | */ |
| 1919 | public boolean isReadOnly() { |
| 1920 | return (mFlags & OPEN_READ_MASK) == OPEN_READONLY; |
| 1921 | } |
| 1922 | |
| 1923 | /** |
| 1924 | * @return true if the DB is currently open (has not been closed) |
| 1925 | */ |
| 1926 | public boolean isOpen() { |
| 1927 | return mNativeHandle != 0; |
| 1928 | } |
| 1929 | |
| 1930 | public boolean needUpgrade(int newVersion) { |
| 1931 | return newVersion > getVersion(); |
| 1932 | } |
| 1933 | |
| 1934 | /** |
| 1935 | * Getter for the path to the database file. |
| 1936 | * |
| 1937 | * @return the path to our database file. |
| 1938 | */ |
| 1939 | public final String getPath() { |
| 1940 | return mPath; |
| 1941 | } |
| 1942 | |
Brad Fitzpatrick | d72f718 | 2010-02-11 17:07:51 -0800 | [diff] [blame] | 1943 | /* package */ void logTimeStat(String sql, long beginMillis) { |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1944 | logTimeStat(sql, beginMillis, null); |
| 1945 | } |
| 1946 | |
| 1947 | /* package */ void logTimeStat(String sql, long beginMillis, String prefix) { |
Brad Fitzpatrick | b28c797 | 2010-02-12 12:49:41 -0800 | [diff] [blame] | 1948 | // Keep track of the last statement executed here, as this is |
| 1949 | // the common funnel through which all methods of hitting |
| 1950 | // libsqlite eventually flow. |
| 1951 | mLastSqlStatement = sql; |
| 1952 | |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1953 | // Sample fast queries in proportion to the time taken. |
| 1954 | // Quantize the % first, so the logged sampling probability |
| 1955 | // exactly equals the actual sampling rate for this query. |
| 1956 | |
| 1957 | int samplePercent; |
Brad Fitzpatrick | d72f718 | 2010-02-11 17:07:51 -0800 | [diff] [blame] | 1958 | long durationMillis = SystemClock.uptimeMillis() - beginMillis; |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1959 | if (durationMillis == 0 && prefix == GET_LOCK_LOG_PREFIX) { |
| 1960 | // The common case is locks being uncontended. Don't log those, |
| 1961 | // even at 1%, which is our default below. |
| 1962 | return; |
| 1963 | } |
| 1964 | if (sQueryLogTimeInMillis == 0) { |
| 1965 | sQueryLogTimeInMillis = SystemProperties.getInt("db.db_operation.threshold_ms", 500); |
| 1966 | } |
| 1967 | if (durationMillis >= sQueryLogTimeInMillis) { |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1968 | samplePercent = 100; |
Vasu Nori | fb16cbd | 2010-07-25 16:38:48 -0700 | [diff] [blame] | 1969 | } else { |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1970 | samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1; |
Dan Egnor | 799f721 | 2009-11-24 16:24:44 -0800 | [diff] [blame] | 1971 | if (mRandom.nextInt(100) >= samplePercent) return; |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1972 | } |
| 1973 | |
Brad Fitzpatrick | 722802e | 2010-03-23 22:22:16 -0700 | [diff] [blame] | 1974 | // Note: the prefix will be "COMMIT;" or "GETLOCK:" when non-null. We wait to do |
| 1975 | // it here so we avoid allocating in the common case. |
| 1976 | if (prefix != null) { |
| 1977 | sql = prefix + sql; |
| 1978 | } |
| 1979 | |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1980 | if (sql.length() > QUERY_LOG_SQL_LENGTH) sql = sql.substring(0, QUERY_LOG_SQL_LENGTH); |
| 1981 | |
| 1982 | // ActivityThread.currentPackageName() only returns non-null if the |
| 1983 | // current thread is an application main thread. This parameter tells |
| 1984 | // us whether an event loop is blocked, and if so, which app it is. |
| 1985 | // |
| 1986 | // Sadly, there's no fast way to determine app name if this is *not* a |
| 1987 | // main thread, or when we are invoked via Binder (e.g. ContentProvider). |
| 1988 | // Hopefully the full path to the database will be informative enough. |
| 1989 | |
Dianne Hackborn | 01e4cfc | 2010-06-24 15:07:24 -0700 | [diff] [blame] | 1990 | String blockingPackage = AppGlobals.getInitialPackage(); |
Dan Egnor | 1231195 | 2009-11-23 14:47:45 -0800 | [diff] [blame] | 1991 | if (blockingPackage == null) blockingPackage = ""; |
| 1992 | |
Brad Fitzpatrick | d72f718 | 2010-02-11 17:07:51 -0800 | [diff] [blame] | 1993 | EventLog.writeEvent( |
Brad Fitzpatrick | d833023 | 2010-02-19 10:59:01 -0800 | [diff] [blame] | 1994 | EVENT_DB_OPERATION, |
| 1995 | getPathForLogs(), |
| 1996 | sql, |
| 1997 | durationMillis, |
| 1998 | blockingPackage, |
| 1999 | samplePercent); |
| 2000 | } |
| 2001 | |
| 2002 | /** |
| 2003 | * Removes email addresses from database filenames before they're |
| 2004 | * logged to the EventLog where otherwise apps could potentially |
| 2005 | * read them. |
| 2006 | */ |
| 2007 | private String getPathForLogs() { |
| 2008 | if (mPathForLogs != null) { |
| 2009 | return mPathForLogs; |
| 2010 | } |
| 2011 | if (mPath == null) { |
| 2012 | return null; |
| 2013 | } |
| 2014 | if (mPath.indexOf('@') == -1) { |
| 2015 | mPathForLogs = mPath; |
| 2016 | } else { |
| 2017 | mPathForLogs = EMAIL_IN_DB_PATTERN.matcher(mPath).replaceAll("XX@YY"); |
| 2018 | } |
| 2019 | return mPathForLogs; |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2020 | } |
| 2021 | |
| 2022 | /** |
| 2023 | * Sets the locale for this database. Does nothing if this database has |
| 2024 | * the NO_LOCALIZED_COLLATORS flag set or was opened read only. |
| 2025 | * @throws SQLException if the locale could not be set. The most common reason |
| 2026 | * for this is that there is no collator available for the locale you requested. |
| 2027 | * In this case the database remains unchanged. |
| 2028 | */ |
| 2029 | public void setLocale(Locale locale) { |
| 2030 | lock(); |
| 2031 | try { |
| 2032 | native_setLocale(locale.toString(), mFlags); |
| 2033 | } finally { |
| 2034 | unlock(); |
| 2035 | } |
| 2036 | } |
| 2037 | |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2038 | /* package */ void verifyDbIsOpen() { |
Vasu Nori | 9463f29 | 2010-04-30 12:22:18 -0700 | [diff] [blame] | 2039 | if (!isOpen()) { |
Vasu Nori | 7501010 | 2010-07-01 16:23:06 -0700 | [diff] [blame] | 2040 | throw new IllegalStateException("database " + getPath() + " (conn# " + |
| 2041 | mConnectionNum + ") already closed"); |
Vasu Nori | 9463f29 | 2010-04-30 12:22:18 -0700 | [diff] [blame] | 2042 | } |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2043 | } |
| 2044 | |
| 2045 | /* package */ void verifyLockOwner() { |
| 2046 | verifyDbIsOpen(); |
| 2047 | if (mLockingEnabled && !isDbLockedByCurrentThread()) { |
Vasu Nori | 9463f29 | 2010-04-30 12:22:18 -0700 | [diff] [blame] | 2048 | throw new IllegalStateException("Don't have database lock!"); |
| 2049 | } |
| 2050 | } |
| 2051 | |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2052 | /* |
| 2053 | * ============================================================================ |
| 2054 | * |
| 2055 | * The following methods deal with compiled-sql cache |
| 2056 | * ============================================================================ |
| 2057 | */ |
| 2058 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2059 | * Adds the given SQL and its compiled-statement-id-returned-by-sqlite to the |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2060 | * cache of compiledQueries attached to 'this'. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2061 | * <p> |
| 2062 | * If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL, |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2063 | * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current |
| 2064 | * mapping is NOT replaced with the new mapping). |
| 2065 | */ |
| 2066 | /* package */ void addToCompiledQueries(String sql, SQLiteCompiledSql compiledStatement) { |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2067 | synchronized(mCompiledQueries) { |
| 2068 | // don't insert the new mapping if a mapping already exists |
Vasu Nori | cc6f549 | 2010-08-23 17:05:25 -0700 | [diff] [blame] | 2069 | if (mCompiledQueries.containsKey(sql)) { |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2070 | return; |
| 2071 | } |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 2072 | |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2073 | if (mCompiledQueries.size() == mMaxSqlCacheSize) { |
Vasu Nori | 49d02ac | 2010-03-05 21:49:30 -0800 | [diff] [blame] | 2074 | /* |
| 2075 | * cache size of {@link #mMaxSqlCacheSize} is not enough for this app. |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 2076 | * log a warning. |
| 2077 | * chances are it is NOT using ? for bindargs - or cachesize is too small. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2078 | */ |
Vasu Nori | 49d02ac | 2010-03-05 21:49:30 -0800 | [diff] [blame] | 2079 | if (++mCacheFullWarnings == MAX_WARNINGS_ON_CACHESIZE_CONDITION) { |
| 2080 | Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " + |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2081 | getPath() + ". Use setMaxSqlCacheSize() to increase cachesize. "); |
Vasu Nori | 49d02ac | 2010-03-05 21:49:30 -0800 | [diff] [blame] | 2082 | } |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 2083 | } |
| 2084 | /* add the given SQLiteCompiledSql compiledStatement to cache. |
| 2085 | * no need to worry about the cache size - because {@link #mCompiledQueries} |
| 2086 | * self-limits its size to {@link #mMaxSqlCacheSize}. |
| 2087 | */ |
| 2088 | mCompiledQueries.put(sql, compiledStatement); |
| 2089 | if (SQLiteDebug.DEBUG_SQL_CACHE) { |
| 2090 | Log.v(TAG, "|adding_sql_to_cache|" + getPath() + "|" + |
| 2091 | mCompiledQueries.size() + "|" + sql); |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2092 | } |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2093 | } |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2094 | } |
| 2095 | |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2096 | /** package-level access for testing purposes */ |
| 2097 | /* package */ void deallocCachedSqlStatements() { |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2098 | synchronized (mCompiledQueries) { |
| 2099 | for (SQLiteCompiledSql compiledSql : mCompiledQueries.values()) { |
| 2100 | compiledSql.releaseSqlStatement(); |
| 2101 | } |
| 2102 | mCompiledQueries.clear(); |
| 2103 | } |
| 2104 | } |
| 2105 | |
| 2106 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2107 | * From the compiledQueries cache, returns the compiled-statement-id for the given SQL. |
| 2108 | * Returns null, if not found in the cache. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2109 | */ |
| 2110 | /* package */ SQLiteCompiledSql getCompiledStatementForSql(String sql) { |
| 2111 | SQLiteCompiledSql compiledStatement = null; |
| 2112 | boolean cacheHit; |
| 2113 | synchronized(mCompiledQueries) { |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2114 | cacheHit = (compiledStatement = mCompiledQueries.get(sql)) != null; |
| 2115 | } |
| 2116 | if (cacheHit) { |
| 2117 | mNumCacheHits++; |
| 2118 | } else { |
| 2119 | mNumCacheMisses++; |
| 2120 | } |
| 2121 | |
| 2122 | if (SQLiteDebug.DEBUG_SQL_CACHE) { |
| 2123 | Log.v(TAG, "|cache_stats|" + |
| 2124 | getPath() + "|" + mCompiledQueries.size() + |
| 2125 | "|" + mNumCacheHits + "|" + mNumCacheMisses + |
Vasu Nori | 20f549f | 2010-04-15 11:25:51 -0700 | [diff] [blame] | 2126 | "|" + cacheHit + "|" + sql); |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2127 | } |
| 2128 | return compiledStatement; |
| 2129 | } |
| 2130 | |
| 2131 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2132 | * Sets the maximum size of the prepared-statement cache for this database. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2133 | * (size of the cache = number of compiled-sql-statements stored in the cache). |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2134 | *<p> |
| 2135 | * Maximum cache size can ONLY be increased from its current size (default = 10). |
| 2136 | * If this method is called with smaller size than the current maximum value, |
| 2137 | * then IllegalStateException is thrown. |
| 2138 | *<p> |
| 2139 | * This method is thread-safe. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2140 | * |
Vasu Nori | 90a36726 | 2010-04-12 12:49:09 -0700 | [diff] [blame] | 2141 | * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE}) |
| 2142 | * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2143 | * the value set with previous setMaxSqlCacheSize() call. |
Vasu Nori | e495d1f | 2010-01-06 16:34:19 -0800 | [diff] [blame] | 2144 | */ |
| 2145 | public synchronized void setMaxSqlCacheSize(int cacheSize) { |
| 2146 | if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) { |
| 2147 | throw new IllegalStateException("expected value between 0 and " + MAX_SQL_CACHE_SIZE); |
| 2148 | } else if (cacheSize < mMaxSqlCacheSize) { |
| 2149 | throw new IllegalStateException("cannot set cacheSize to a value less than the value " + |
| 2150 | "set with previous setMaxSqlCacheSize() call."); |
| 2151 | } |
| 2152 | mMaxSqlCacheSize = cacheSize; |
| 2153 | } |
| 2154 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2155 | /* package */ boolean isSqlInStatementCache(String sql) { |
| 2156 | synchronized (mCompiledQueries) { |
| 2157 | return mCompiledQueries.containsKey(sql); |
| 2158 | } |
| 2159 | } |
| 2160 | |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 2161 | /* package */ void finalizeStatementLater(int id) { |
| 2162 | if (!isOpen()) { |
| 2163 | // database already closed. this statement will already have been finalized. |
| 2164 | return; |
| 2165 | } |
| 2166 | synchronized(mClosedStatementIds) { |
| 2167 | if (mClosedStatementIds.contains(id)) { |
| 2168 | // this statement id is already queued up for finalization. |
| 2169 | return; |
| 2170 | } |
| 2171 | mClosedStatementIds.add(id); |
| 2172 | } |
| 2173 | } |
| 2174 | |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2175 | /* package */ void closePendingStatements() { |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 2176 | if (!isOpen()) { |
| 2177 | // since this database is already closed, no need to finalize anything. |
| 2178 | mClosedStatementIds.clear(); |
| 2179 | return; |
| 2180 | } |
| 2181 | verifyLockOwner(); |
| 2182 | /* to minimize synchronization on mClosedStatementIds, make a copy of the list */ |
| 2183 | ArrayList<Integer> list = new ArrayList<Integer>(mClosedStatementIds.size()); |
| 2184 | synchronized(mClosedStatementIds) { |
| 2185 | list.addAll(mClosedStatementIds); |
| 2186 | mClosedStatementIds.clear(); |
| 2187 | } |
| 2188 | // finalize all the statements from the copied list |
| 2189 | int size = list.size(); |
| 2190 | for (int i = 0; i < size; i++) { |
| 2191 | native_finalize(list.get(i)); |
| 2192 | } |
| 2193 | } |
| 2194 | |
| 2195 | /** |
| 2196 | * for testing only |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 2197 | */ |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2198 | /* package */ ArrayList<Integer> getQueuedUpStmtList() { |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 2199 | return mClosedStatementIds; |
| 2200 | } |
| 2201 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2202 | /** |
| 2203 | * This method enables parallel execution of queries from multiple threads on the same database. |
| 2204 | * It does this by opening multiple handles to the database and using a different |
| 2205 | * database handle for each query. |
| 2206 | * <p> |
| 2207 | * If a transaction is in progress on one connection handle and say, a table is updated in the |
| 2208 | * transaction, then query on the same table on another connection handle will block for the |
| 2209 | * transaction to complete. But this method enables such queries to execute by having them |
| 2210 | * return old version of the data from the table. Most often it is the data that existed in the |
| 2211 | * table prior to the above transaction updates on that table. |
| 2212 | * <p> |
| 2213 | * Maximum number of simultaneous handles used to execute queries in parallel is |
| 2214 | * dependent upon the device memory and possibly other properties. |
| 2215 | * <p> |
| 2216 | * After calling this method, execution of queries in parallel is enabled as long as this |
| 2217 | * database handle is open. To disable execution of queries in parallel, database should |
| 2218 | * be closed and reopened. |
| 2219 | * <p> |
| 2220 | * If a query is part of a transaction, then it is executed on the same database handle the |
| 2221 | * transaction was begun. |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2222 | * <p> |
| 2223 | * If the database has any attached databases, then execution of queries in paralel is NOT |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2224 | * possible. In such cases, a message is printed to logcat and false is returned. |
| 2225 | * <p> |
| 2226 | * This feature is not available for :memory: databases. In such cases, |
| 2227 | * a message is printed to logcat and false is returned. |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2228 | * <p> |
| 2229 | * A typical way to use this method is the following: |
| 2230 | * <pre> |
| 2231 | * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory, |
| 2232 | * CREATE_IF_NECESSARY, myDatabaseErrorHandler); |
| 2233 | * db.enableWriteAheadLogging(); |
| 2234 | * </pre> |
| 2235 | * <p> |
| 2236 | * Writers should use {@link #beginTransactionNonExclusive()} or |
| 2237 | * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)} |
| 2238 | * to start a trsnsaction. |
| 2239 | * Non-exclusive mode allows database file to be in readable by threads executing queries. |
| 2240 | * </p> |
| 2241 | * |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2242 | * @return true if write-ahead-logging is set. false otherwise |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2243 | */ |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2244 | public synchronized boolean enableWriteAheadLogging() { |
| 2245 | if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) { |
| 2246 | Log.i(TAG, "can't enable WAL for memory databases."); |
| 2247 | return false; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2248 | } |
| 2249 | |
| 2250 | // make sure this database has NO attached databases because sqlite's write-ahead-logging |
| 2251 | // doesn't work for databases with attached databases |
| 2252 | if (getAttachedDbs().size() > 1) { |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2253 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 2254 | Log.d(TAG, |
| 2255 | "this database: " + mPath + " has attached databases. can't enable WAL."); |
| 2256 | } |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2257 | return false; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2258 | } |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2259 | if (mConnectionPool == null) { |
| 2260 | mConnectionPool = new DatabaseConnectionPool(this); |
| 2261 | setJournalMode(mPath, "WAL"); |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2262 | } |
Vasu Nori | a98cb26 | 2010-06-22 13:16:35 -0700 | [diff] [blame] | 2263 | return true; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2264 | } |
| 2265 | |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 2266 | /** |
Vasu Nori | 7b04c41 | 2010-07-20 10:31:21 -0700 | [diff] [blame] | 2267 | * This method disables the features enabled by {@link #enableWriteAheadLogging()}. |
| 2268 | * @hide |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 2269 | */ |
Vasu Nori | 7b04c41 | 2010-07-20 10:31:21 -0700 | [diff] [blame] | 2270 | public void disableWriteAheadLogging() { |
| 2271 | synchronized (this) { |
| 2272 | if (mConnectionPool == null) { |
| 2273 | return; |
| 2274 | } |
| 2275 | mConnectionPool.close(); |
| 2276 | mConnectionPool = null; |
| 2277 | setJournalMode(mPath, "TRUNCATE"); |
Vasu Nori | 8d11103 | 2010-06-22 18:34:21 -0700 | [diff] [blame] | 2278 | } |
Vasu Nori | 8d11103 | 2010-06-22 18:34:21 -0700 | [diff] [blame] | 2279 | } |
| 2280 | |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2281 | /* package */ SQLiteDatabase getDatabaseHandle(String sql) { |
| 2282 | if (isPooledConnection()) { |
| 2283 | // this is a pooled database connection |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2284 | // use it if it is open AND if I am not currently part of a transaction |
| 2285 | if (isOpen() && !amIInTransaction()) { |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2286 | // TODO: use another connection from the pool |
| 2287 | // if this connection is currently in use by some other thread |
| 2288 | // AND if there are free connections in the pool |
| 2289 | return this; |
| 2290 | } else { |
| 2291 | // the pooled connection is not open! could have been closed either due |
| 2292 | // to corruption on this or some other connection to the database |
| 2293 | // OR, maybe the connection pool is disabled after this connection has been |
| 2294 | // allocated to me. try to get some other pooled or main database connection |
| 2295 | return getParentDbConnObj().getDbConnection(sql); |
| 2296 | } |
| 2297 | } else { |
| 2298 | // this is NOT a pooled connection. can we get one? |
| 2299 | return getDbConnection(sql); |
| 2300 | } |
| 2301 | } |
| 2302 | |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2303 | /** |
| 2304 | * Sets the database connection handle pool size to the given value. |
| 2305 | * Database connection handle pool is enabled when the app calls |
| 2306 | * {@link #enableWriteAheadLogging()}. |
| 2307 | * <p> |
| 2308 | * The default connection handle pool is set by the system by taking into account various |
| 2309 | * aspects of the device, such as memory, number of cores etc. It is recommended that |
| 2310 | * applications use the default pool size set by the system. |
| 2311 | * |
| 2312 | * @param size the value the connection handle pool size should be set to. |
| 2313 | */ |
| 2314 | public synchronized void setConnectionPoolSize(int size) { |
| 2315 | if (mConnectionPool == null) { |
| 2316 | throw new IllegalStateException("connection pool not enabled"); |
| 2317 | } |
| 2318 | int i = mConnectionPool.getMaxPoolSize(); |
| 2319 | if (size < i) { |
Vasu Nori | daa4e4f | 2010-06-15 11:32:27 -0700 | [diff] [blame] | 2320 | throw new IllegalArgumentException( |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2321 | "cannot set max pool size to a value less than the current max value(=" + |
| 2322 | i + ")"); |
| 2323 | } |
| 2324 | mConnectionPool.setMaxPoolSize(size); |
| 2325 | } |
| 2326 | |
| 2327 | /* package */ SQLiteDatabase createPoolConnection(short connectionNum) { |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2328 | SQLiteDatabase db = openDatabase(mPath, mFactory, mFlags, mErrorHandler, connectionNum); |
| 2329 | db.mParentConnObj = this; |
| 2330 | return db; |
| 2331 | } |
| 2332 | |
| 2333 | private synchronized SQLiteDatabase getParentDbConnObj() { |
| 2334 | return mParentConnObj; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2335 | } |
| 2336 | |
| 2337 | private boolean isPooledConnection() { |
| 2338 | return this.mConnectionNum > 0; |
| 2339 | } |
| 2340 | |
Vasu Nori | 2827d6d | 2010-07-04 00:26:18 -0700 | [diff] [blame] | 2341 | /* package */ SQLiteDatabase getDbConnection(String sql) { |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2342 | verifyDbIsOpen(); |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2343 | // this method should always be called with main database connection handle. |
| 2344 | // the only time when it is called with pooled database connection handle is |
| 2345 | // corruption occurs while trying to open a pooled database connection handle. |
| 2346 | // in that case, simply return 'this' handle |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2347 | if (isPooledConnection()) { |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2348 | return this; |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2349 | } |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2350 | |
| 2351 | // use the current connection handle if |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2352 | // 1. if the caller is part of the ongoing transaction, if any |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2353 | // 2. OR, if there is NO connection handle pool setup |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2354 | if (amIInTransaction() || mConnectionPool == null) { |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2355 | return this; |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2356 | } else { |
| 2357 | // get a connection handle from the pool |
| 2358 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 2359 | assert mConnectionPool != null; |
Vasu Nori | ce38b98 | 2010-07-22 13:57:13 -0700 | [diff] [blame] | 2360 | Log.i(TAG, mConnectionPool.toString()); |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2361 | } |
Vasu Nori | 65a8883 | 2010-07-16 15:14:08 -0700 | [diff] [blame] | 2362 | return mConnectionPool.get(sql); |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2363 | } |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2364 | } |
| 2365 | |
| 2366 | private void releaseDbConnection(SQLiteDatabase db) { |
| 2367 | // ignore this release call if |
| 2368 | // 1. the database is closed |
| 2369 | // 2. OR, if db is NOT a pooled connection handle |
| 2370 | // 3. OR, if the database being released is same as 'this' (this condition means |
| 2371 | // that we should always be releasing a pooled connection handle by calling this method |
| 2372 | // from the 'main' connection handle |
| 2373 | if (!isOpen() || !db.isPooledConnection() || (db == this)) { |
| 2374 | return; |
| 2375 | } |
| 2376 | if (Log.isLoggable(TAG, Log.DEBUG)) { |
| 2377 | assert isPooledConnection(); |
| 2378 | assert mConnectionPool != null; |
| 2379 | Log.d(TAG, "releaseDbConnection threadid = " + Thread.currentThread().getId() + |
| 2380 | ", releasing # " + db.mConnectionNum + ", " + getPath()); |
| 2381 | } |
| 2382 | mConnectionPool.release(db); |
| 2383 | } |
| 2384 | |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 2385 | /** |
| 2386 | * this method is used to collect data about ALL open databases in the current process. |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2387 | * bugreport is a user of this data. |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 2388 | */ |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2389 | /* package */ static ArrayList<DbStats> getDbStats() { |
| 2390 | ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>(); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2391 | // make a local copy of mActiveDatabases - so that this method is not competing |
| 2392 | // for synchronization lock on mActiveDatabases |
Vasu Nori | 9a8bc78 | 2010-08-23 12:07:00 -0700 | [diff] [blame] | 2393 | ArrayList<WeakReference<SQLiteDatabase>> tempList; |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2394 | synchronized(mActiveDatabases) { |
Vasu Nori | 9a8bc78 | 2010-08-23 12:07:00 -0700 | [diff] [blame] | 2395 | tempList = (ArrayList<WeakReference<SQLiteDatabase>>)mActiveDatabases.clone(); |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2396 | } |
| 2397 | for (WeakReference<SQLiteDatabase> w : tempList) { |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2398 | SQLiteDatabase db = w.get(); |
| 2399 | if (db == null || !db.isOpen()) { |
| 2400 | continue; |
| 2401 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2402 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2403 | synchronized (db) { |
| 2404 | try { |
| 2405 | // get SQLITE_DBSTATUS_LOOKASIDE_USED for the db |
| 2406 | int lookasideUsed = db.native_getDbLookaside(); |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2407 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2408 | // get the lastnode of the dbname |
| 2409 | String path = db.getPath(); |
| 2410 | int indx = path.lastIndexOf("/"); |
| 2411 | String lastnode = path.substring((indx != -1) ? ++indx : 0); |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2412 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2413 | // get list of attached dbs and for each db, get its size and pagesize |
| 2414 | ArrayList<Pair<String, String>> attachedDbs = db.getAttachedDbs(); |
| 2415 | if (attachedDbs == null) { |
| 2416 | continue; |
| 2417 | } |
| 2418 | for (int i = 0; i < attachedDbs.size(); i++) { |
| 2419 | Pair<String, String> p = attachedDbs.get(i); |
| 2420 | long pageCount = DatabaseUtils.longForQuery(db, "PRAGMA " + p.first |
| 2421 | + ".page_count;", null); |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2422 | |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2423 | // first entry in the attached db list is always the main database |
| 2424 | // don't worry about prefixing the dbname with "main" |
| 2425 | String dbName; |
| 2426 | if (i == 0) { |
| 2427 | dbName = lastnode; |
| 2428 | } else { |
| 2429 | // lookaside is only relevant for the main db |
| 2430 | lookasideUsed = 0; |
| 2431 | dbName = " (attached) " + p.first; |
| 2432 | // if the attached db has a path, attach the lastnode from the path to above |
| 2433 | if (p.second.trim().length() > 0) { |
| 2434 | int idx = p.second.lastIndexOf("/"); |
| 2435 | dbName += " : " + p.second.substring((idx != -1) ? ++idx : 0); |
| 2436 | } |
| 2437 | } |
| 2438 | if (pageCount > 0) { |
| 2439 | dbStatsList.add(new DbStats(dbName, pageCount, db.getPageSize(), |
| 2440 | lookasideUsed, db.mNumCacheHits, db.mNumCacheMisses, |
| 2441 | db.mCompiledQueries.size())); |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2442 | } |
| 2443 | } |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2444 | // if there are pooled connections, return the cache stats for them also. |
| 2445 | if (db.mConnectionPool != null) { |
| 2446 | for (SQLiteDatabase pDb : db.mConnectionPool.getConnectionList()) { |
| 2447 | dbStatsList.add(new DbStats("(pooled # " + pDb.mConnectionNum + ") " |
| 2448 | + lastnode, 0, 0, 0, pDb.mNumCacheHits, pDb.mNumCacheMisses, |
| 2449 | pDb.mCompiledQueries.size())); |
| 2450 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2451 | } |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2452 | } catch (SQLiteException e) { |
| 2453 | // ignore. we don't care about exceptions when we are taking adb |
| 2454 | // bugreport! |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2455 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2456 | } |
| 2457 | } |
| 2458 | return dbStatsList; |
| 2459 | } |
| 2460 | |
| 2461 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2462 | * Returns list of full pathnames of all attached databases including the main database |
| 2463 | * by executing 'pragma database_list' on the database. |
| 2464 | * |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2465 | * @return ArrayList of pairs of (database name, database file path) or null if the database |
| 2466 | * is not open. |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2467 | */ |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2468 | public ArrayList<Pair<String, String>> getAttachedDbs() { |
| 2469 | if (!isOpen()) { |
Vasu Nori | f3cf8a4 | 2010-03-23 11:41:44 -0700 | [diff] [blame] | 2470 | return null; |
| 2471 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2472 | ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>(); |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2473 | Cursor c = null; |
| 2474 | try { |
| 2475 | c = rawQuery("pragma database_list;", null); |
| 2476 | while (c.moveToNext()) { |
| 2477 | // sqlite returns a row for each database in the returned list of databases. |
| 2478 | // in each row, |
| 2479 | // 1st column is the database name such as main, or the database |
| 2480 | // name specified on the "ATTACH" command |
| 2481 | // 2nd column is the database file path. |
| 2482 | attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2))); |
| 2483 | } |
| 2484 | } finally { |
| 2485 | if (c != null) { |
| 2486 | c.close(); |
| 2487 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2488 | } |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2489 | return attachedDbs; |
| 2490 | } |
| 2491 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2492 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2493 | * Runs 'pragma integrity_check' on the given database (and all the attached databases) |
| 2494 | * and returns true if the given database (and all its attached databases) pass integrity_check, |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2495 | * false otherwise. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2496 | *<p> |
| 2497 | * If the result is false, then this method logs the errors reported by the integrity_check |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2498 | * command execution. |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2499 | *<p> |
| 2500 | * Note that 'pragma integrity_check' on a database can take a long time. |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2501 | * |
| 2502 | * @return true if the given database (and all its attached databases) pass integrity_check, |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2503 | * false otherwise. |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2504 | */ |
| 2505 | public boolean isDatabaseIntegrityOk() { |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2506 | verifyDbIsOpen(); |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2507 | ArrayList<Pair<String, String>> attachedDbs = null; |
| 2508 | try { |
| 2509 | attachedDbs = getAttachedDbs(); |
| 2510 | if (attachedDbs == null) { |
| 2511 | throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " + |
| 2512 | "be retrieved. probably because the database is closed"); |
| 2513 | } |
| 2514 | } catch (SQLiteException e) { |
| 2515 | // can't get attachedDb list. do integrity check on the main database |
| 2516 | attachedDbs = new ArrayList<Pair<String, String>>(); |
| 2517 | attachedDbs.add(new Pair<String, String>("main", this.mPath)); |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2518 | } |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2519 | for (int i = 0; i < attachedDbs.size(); i++) { |
| 2520 | Pair<String, String> p = attachedDbs.get(i); |
| 2521 | SQLiteStatement prog = null; |
| 2522 | try { |
| 2523 | prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);"); |
| 2524 | String rslt = prog.simpleQueryForString(); |
| 2525 | if (!rslt.equalsIgnoreCase("ok")) { |
| 2526 | // integrity_checker failed on main or attached databases |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2527 | Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt); |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2528 | return false; |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2529 | } |
| 2530 | } finally { |
| 2531 | if (prog != null) prog.close(); |
| 2532 | } |
| 2533 | } |
Vasu Nori | bfe1dc2 | 2010-08-25 16:29:02 -0700 | [diff] [blame^] | 2534 | return true; |
Vasu Nori | 062fc7ce | 2010-03-31 16:13:05 -0700 | [diff] [blame] | 2535 | } |
| 2536 | |
| 2537 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2538 | * Native call to open the database. |
| 2539 | * |
| 2540 | * @param path The full path to the database |
| 2541 | */ |
| 2542 | private native void dbopen(String path, int flags); |
| 2543 | |
| 2544 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2545 | * Native call to setup tracing of all SQL statements |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2546 | * |
| 2547 | * @param path the full path to the database |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2548 | * @param connectionNum connection number: 0 - N, where the main database |
| 2549 | * connection handle is numbered 0 and the connection handles in the connection |
| 2550 | * pool are numbered 1..N. |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2551 | */ |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2552 | private native void enableSqlTracing(String path, short connectionNum); |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2553 | |
| 2554 | /** |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2555 | * Native call to setup profiling of all SQL statements. |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2556 | * currently, sqlite's profiling = printing of execution-time |
Vasu Nori | ccd9544 | 2010-05-28 17:04:16 -0700 | [diff] [blame] | 2557 | * (wall-clock time) of each of the SQL statements, as they |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2558 | * are executed. |
| 2559 | * |
| 2560 | * @param path the full path to the database |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2561 | * @param connectionNum connection number: 0 - N, where the main database |
| 2562 | * connection handle is numbered 0 and the connection handles in the connection |
| 2563 | * pool are numbered 1..N. |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2564 | */ |
Vasu Nori | 6c354da | 2010-04-26 23:33:39 -0700 | [diff] [blame] | 2565 | private native void enableSqlProfiling(String path, short connectionNum); |
Vasu Nori | 3ef94e2 | 2010-02-05 14:49:04 -0800 | [diff] [blame] | 2566 | |
| 2567 | /** |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2568 | * Native call to set the locale. {@link #lock} must be held when calling |
| 2569 | * this method. |
| 2570 | * @throws SQLException |
| 2571 | */ |
Vasu Nori | 0732f79 | 2010-07-29 17:24:12 -0700 | [diff] [blame] | 2572 | private native void native_setLocale(String loc, int flags); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2573 | |
| 2574 | /** |
Vasu Nori | c384920 | 2010-03-09 10:47:25 -0800 | [diff] [blame] | 2575 | * return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here |
| 2576 | * http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html |
| 2577 | * @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED |
| 2578 | */ |
| 2579 | private native int native_getDbLookaside(); |
Vasu Nori | 6f37f83 | 2010-05-19 11:53:25 -0700 | [diff] [blame] | 2580 | |
| 2581 | /** |
| 2582 | * finalizes the given statement id. |
| 2583 | * |
| 2584 | * @param statementId statement to be finzlied by sqlite |
| 2585 | */ |
| 2586 | private final native void native_finalize(int statementId); |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 2587 | } |