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