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