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