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