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