blob: c6051e1c753e69fdde571652c0ac8be65e231902 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
17package android.database.sqlite;
18
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070019import android.app.AppGlobals;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentValues;
Vasu Nori34ad57f02010-12-21 09:32:36 -080021import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.database.Cursor;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070023import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.database.DatabaseUtils;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070025import android.database.DefaultDatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.database.SQLException;
Vasu Noric3849202010-03-09 10:47:25 -080027import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.os.Debug;
Vasu Noria8c24902010-06-01 11:30:27 -070029import android.os.StatFs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.SystemClock;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070031import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.text.TextUtils;
33import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070035import android.util.Log;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080036import android.util.LruCache;
Vasu Noric3849202010-03-09 10:47:25 -080037import android.util.Pair;
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -070038import dalvik.system.BlockGuard;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import java.io.File;
Vasu Noric3849202010-03-09 10:47:25 -080040import java.lang.ref.WeakReference;
Vasu Noric3849202010-03-09 10:47:25 -080041import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.util.HashMap;
43import java.util.Iterator;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080044import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.util.Locale;
46import java.util.Map;
Dan Egnor12311952009-11-23 14:47:45 -080047import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.util.WeakHashMap;
Vasu Norid4608a32011-02-03 16:24:06 -080049import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.concurrent.locks.ReentrantLock;
Brad Fitzpatrickd8330232010-02-19 10:59:01 -080051import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
53/**
54 * Exposes methods to manage a SQLite database.
55 * <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and
56 * perform other common database management tasks.
57 * <p>See the Notepad sample application in the SDK for an example of creating
58 * and managing a database.
59 * <p> Database names must be unique within an application, not across all
60 * applications.
61 *
62 * <h3>Localized Collation - ORDER BY</h3>
63 * <p>In addition to SQLite's default <code>BINARY</code> collator, Android supplies
64 * two more, <code>LOCALIZED</code>, which changes with the system's current locale
65 * if you wire it up correctly (XXX a link needed!), and <code>UNICODE</code>, which
66 * is the Unicode Collation Algorithm and not tailored to the current locale.
67 */
68public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070069 private static final String TAG = "SQLiteDatabase";
Jeff Hamilton082c2af2009-09-29 11:49:51 -070070 private static final int EVENT_DB_OPERATION = 52000;
71 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73 /**
74 * Algorithms used in ON CONFLICT clause
75 * http://www.sqlite.org/lang_conflict.html
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 */
Vasu Nori8d45e4e2010-02-05 22:35:47 -080077 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -070085
Vasu Nori8d45e4e2010-02-05 22:35:47 -080086 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -070092
Vasu Nori8d45e4e2010-02-05 22:35:47 -080093 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -0700100
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800101 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -0700109
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800110 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -0700124
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800125 /**
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 Plotnikov600bdd82009-09-01 12:12:20 -0700131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 /**
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 Quintanac4516a72009-09-03 12:14:06 -0700189 /**
190 * Valid during the life of a transaction.
191 */
192 private SQLiteTransactionListener mTransactionListener;
193
Vasu Norice38b982010-07-22 13:57:13 -0700194 /**
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 Project9066cfe2009-03-03 19:31:44 -0800199 /** Synchronize on this when accessing the database */
Vasu Norid4608a32011-02-03 16:24:06 -0800200 private final DatabaseReentrantLock mLock = new DatabaseReentrantLock(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
202 private long mLockAcquiredWallTime = 0L;
203 private long mLockAcquiredThreadTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // limit the frequency of complaints about each database to one within 20 sec
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700206 // unless run command adb shell setprop log.tag.Database VERBOSE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 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 Plotnikovb43b58d2009-09-09 18:10:42 -0700213 private static final int SLEEP_AFTER_YIELD_QUANTUM = 1000;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700214
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800215 // 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 Project9066cfe2009-03-03 19:31:44 -0800219 private long mLastLockMessageTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700220
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800221 // Things related to query logging/sampling for debugging
222 // slow/frequent queries during development. Always log queries
Brad Fitzpatrick722802e2010-03-23 22:22:16 -0700223 // 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 Egnor12311952009-11-23 14:47:45 -0800231 private static final int QUERY_LOG_SQL_LENGTH = 64;
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800232 private static final String COMMIT_SQL = "COMMIT;";
Vasu Nori16057fa2011-03-18 11:40:37 -0700233 private static final String BEGIN_SQL = "BEGIN;";
Dan Egnor12311952009-11-23 14:47:45 -0800234 private final Random mRandom = new Random();
Vasu Nori16057fa2011-03-18 11:40:37 -0700235 /** the last non-commit/rollback sql statement in a transaction */
236 // guarded by 'this'
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800237 private String mLastSqlStatement = null;
Dan Egnor12311952009-11-23 14:47:45 -0800238
Vasu Nori16057fa2011-03-18 11:40:37 -0700239 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 Fitzpatrick722802e2010-03-23 22:22:16 -0700250 // 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 Nori6f37f832010-05-19 11:53:25 -0700254 /** 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 Project9066cfe2009-03-03 19:31:44 -0800256
Vasu Noria8c24902010-06-01 11:30:27 -0700257 /**
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 Project9066cfe2009-03-03 19:31:44 -0800263 /** The path for the database file */
Vasu Noriccd95442010-05-28 17:04:16 -0700264 private final String mPath;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800266 /** The anonymized path for the database file for logging purposes */
267 private String mPathForLogs = null; // lazily populated
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 /** The flags passed to open/create */
Vasu Noriccd95442010-05-28 17:04:16 -0700270 private final int mFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
272 /** The optional factory to use when creating new Cursors */
Vasu Noriccd95442010-05-28 17:04:16 -0700273 private final CursorFactory mFactory;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700274
Vasu Nori21343692010-06-03 16:01:39 -0700275 private final WeakHashMap<SQLiteClosable, Object> mPrograms;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700276
Jesse Wilson9b5a9352011-02-10 11:19:09 -0800277 /** Default statement-cache size per database connection ( = instance of this class) */
Jesse Wilsonc2c9a242011-02-10 19:19:02 -0800278 private static final int DEFAULT_SQL_CACHE_SIZE = 25;
Jesse Wilson9b5a9352011-02-10 11:19:09 -0800279
Vasu Nori5a03f362009-10-20 15:16:35 -0700280 /**
Vasu Norib729dcc2010-09-14 11:35:49 -0700281 * 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 Wilson9b5a9352011-02-10 11:19:09 -0800292 * this cache's max size is settable by calling the method
Jesse Wilsondfe515e2011-02-10 19:06:09 -0800293 * (@link #setMaxSqlCacheSize(int)}.
Vasu Norib729dcc2010-09-14 11:35:49 -0700294 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -0800295 // guarded by this
296 private LruCache<String, SQLiteCompiledSql> mCompiledQueries;
297
Vasu Norib729dcc2010-09-14 11:35:49 -0700298 /**
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 Noriccd95442010-05-28 17:04:16 -0700301 * SQL statement & schema.
Vasu Norie495d1f2010-01-06 16:34:19 -0800302 */
Vasu Nori90a367262010-04-12 12:49:09 -0700303 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Nori5e89ae22010-09-15 14:23:29 -0700304 private boolean mCacheFullWarning;
Vasu Norib729dcc2010-09-14 11:35:49 -0700305
Vasu Norid606b4b2010-02-24 12:54:20 -0800306 /** Used to find out where this object was created in case it never got closed. */
Vasu Nori21343692010-06-03 16:01:39 -0700307 private final Throwable mStackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308
Dmitri Plotnikov90142c92009-09-15 10:52:17 -0700309 // 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 Nori6f37f832010-05-19 11:53:25 -0700313 /** stores the list of statement ids that need to be finalized by sqlite */
Vasu Nori21343692010-06-03 16:01:39 -0700314 private final ArrayList<Integer> mClosedStatementIds = new ArrayList<Integer>();
Vasu Nori6f37f832010-05-19 11:53:25 -0700315
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700316 /** {@link DatabaseErrorHandler} to be used when SQLite returns any of the following errors
317 * Corruption
318 * */
Vasu Nori21343692010-06-03 16:01:39 -0700319 private final DatabaseErrorHandler mErrorHandler;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700320
Vasu Nori6c354da2010-04-26 23:33:39 -0700321 /** 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 Nori65a88832010-07-16 15:14:08 -0700332 /** 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 Noria98cb262010-06-22 13:16:35 -0700338 private static final String MEMORY_DB_PATH = ":memory:";
339
Vasu Nori24675612010-09-27 14:54:19 -0700340 /** set to true if the database has attached databases */
341 private volatile boolean mHasAttachedDbs = false;
342
Vasu Nori0732f792010-07-29 17:24:12 -0700343 /** stores reference to all databases opened in the current process. */
344 private static ArrayList<WeakReference<SQLiteDatabase>> mActiveDatabases =
345 new ArrayList<WeakReference<SQLiteDatabase>>();
346
Vasu Nori2827d6d2010-07-04 00:26:18 -0700347 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 Project9066cfe2009-03-03 19:31:44 -0800351 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700352
Vasu Nori2827d6d2010-07-04 00:26:18 -0700353 synchronized void removeSQLiteClosable(SQLiteClosable closable) {
354 mPrograms.remove(closable);
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700355 }
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 @Override
358 protected void onAllReferencesReleased() {
359 if (isOpen()) {
Vasu Noriad239ab2010-06-14 16:58:47 -0700360 // close the database which will close all pending statements to be finalized also
361 close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
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 Plotnikov600bdd82009-09-01 12:12:20 -0700368 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 * @return the number of bytes actually released
370 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700371 static public native int releaseMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372
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 Norif3cf8a42010-03-23 11:41:44 -0700391 EventLog.writeEvent(EVENT_DB_CORRUPT, mPath);
Vasu Noriccd95442010-05-28 17:04:16 -0700392 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 }
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 Plotnikov600bdd82009-09-01 12:12:20 -0700400 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 * @see #unlock()
402 */
Vasu Nori16057fa2011-03-18 11:40:37 -0700403 /* package */ void lock(String sql) {
404 lock(sql, false);
Vasu Nori6d970252010-10-05 10:48:49 -0700405 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700406
407 /* pachage */ void lock() {
408 lock(null, false);
409 }
410
Vasu Norid4608a32011-02-03 16:24:06 -0800411 private static final long LOCK_WAIT_PERIOD = 30L;
Vasu Nori16057fa2011-03-18 11:40:37 -0700412 private void lock(String sql, boolean forced) {
Vasu Nori6d970252010-10-05 10:48:49 -0700413 // make sure this method is NOT being called from a 'synchronized' method
414 if (Thread.holdsLock(this)) {
Vasu Nori4b92aee2011-01-26 23:22:34 -0800415 Log.w(TAG, "don't lock() while in a synchronized method");
Vasu Nori6d970252010-10-05 10:48:49 -0700416 }
Vasu Nori7b04c412010-07-20 10:31:21 -0700417 verifyDbIsOpen();
Vasu Nori6d970252010-10-05 10:48:49 -0700418 if (!forced && !mLockingEnabled) return;
Vasu Norid4608a32011-02-03 16:24:06 -0800419 boolean done = false;
Vasu Nori16057fa2011-03-18 11:40:37 -0700420 long timeStart = SystemClock.uptimeMillis();
Vasu Norid4608a32011-02-03 16:24:06 -0800421 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 Norie9714e62011-02-11 16:50:51 -0800430 ". Continuing to wait in thread: " + Thread.currentThread().getId());
Vasu Norid4608a32011-02-03 16:24:06 -0800431 }
432 } catch (InterruptedException e) {
433 // ignore the interruption
434 }
435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 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 Nori16057fa2011-03-18 11:40:37 -0700443 if (sql != null) {
444 logTimeStat(sql, timeStart, GET_LOCK_LOG_PREFIX);
445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 }
Vasu Norid4608a32011-02-03 16:24:06 -0800447 private static class DatabaseReentrantLock extends ReentrantLock {
448 DatabaseReentrantLock(boolean fair) {
449 super(fair);
450 }
451 @Override
452 public Thread getOwner() {
453 return super.getOwner();
454 }
455 public String getOwnerDescription() {
456 Thread t = getOwner();
457 return (t== null) ? "none" : String.valueOf(t.getId());
458 }
459 }
460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 /**
462 * Locks the database for exclusive access. The database lock must be held when
463 * touch the native sqlite3* object since it is single threaded and uses
464 * a polling lock contention algorithm. The lock is recursive, and may be acquired
465 * multiple times by the same thread.
466 *
467 * @see #unlockForced()
468 */
469 private void lockForced() {
Vasu Nori16057fa2011-03-18 11:40:37 -0700470 lock(null, true);
471 }
472
473 private void lockForced(String sql) {
474 lock(sql, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 }
476
477 /**
478 * Releases the database lock. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700479 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 * @see #unlock()
481 */
482 /* package */ void unlock() {
483 if (!mLockingEnabled) return;
484 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
485 if (mLock.getHoldCount() == 1) {
486 checkLockHoldTime();
487 }
488 }
489 mLock.unlock();
490 }
491
492 /**
493 * Releases the database lock.
494 *
495 * @see #unlockForced()
496 */
497 private void unlockForced() {
498 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
499 if (mLock.getHoldCount() == 1) {
500 checkLockHoldTime();
501 }
502 }
503 mLock.unlock();
504 }
505
506 private void checkLockHoldTime() {
507 // Use elapsed real-time since the CPU may sleep when waiting for IO
508 long elapsedTime = SystemClock.elapsedRealtime();
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700509 long lockedTime = elapsedTime - mLockAcquiredWallTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 if (lockedTime < LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT &&
511 !Log.isLoggable(TAG, Log.VERBOSE) &&
512 (elapsedTime - mLastLockMessageTime) < LOCK_WARNING_WINDOW_IN_MS) {
513 return;
514 }
515 if (lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS) {
516 int threadTime = (int)
517 ((Debug.threadCpuTimeNanos() - mLockAcquiredThreadTime) / 1000000);
518 if (threadTime > LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS ||
519 lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT) {
520 mLastLockMessageTime = elapsedTime;
521 String msg = "lock held on " + mPath + " for " + lockedTime + "ms. Thread time was "
522 + threadTime + "ms";
523 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING_STACK_TRACE) {
524 Log.d(TAG, msg, new Exception());
525 } else {
526 Log.d(TAG, msg);
527 }
528 }
529 }
530 }
531
532 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700533 * Begins a transaction in EXCLUSIVE mode.
534 * <p>
535 * Transactions can be nested.
536 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 * the work done in that transaction and all of the nested transactions will be committed or
538 * rolled back. The changes will be rolled back if any transaction is ended without being
539 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700540 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 * <p>Here is the standard idiom for transactions:
542 *
543 * <pre>
544 * db.beginTransaction();
545 * try {
546 * ...
547 * db.setTransactionSuccessful();
548 * } finally {
549 * db.endTransaction();
550 * }
551 * </pre>
552 */
553 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700554 beginTransaction(null /* transactionStatusCallback */, true);
555 }
556
557 /**
558 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
559 * the outer transaction is ended all of the work done in that transaction
560 * and all of the nested transactions will be committed or rolled back. The
561 * changes will be rolled back if any transaction is ended without being
562 * marked as clean (by calling setTransactionSuccessful). Otherwise they
563 * will be committed.
564 * <p>
565 * Here is the standard idiom for transactions:
566 *
567 * <pre>
568 * db.beginTransactionNonExclusive();
569 * try {
570 * ...
571 * db.setTransactionSuccessful();
572 * } finally {
573 * db.endTransaction();
574 * }
575 * </pre>
576 */
577 public void beginTransactionNonExclusive() {
578 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700579 }
580
581 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700582 * Begins a transaction in EXCLUSIVE mode.
583 * <p>
584 * Transactions can be nested.
585 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700586 * the work done in that transaction and all of the nested transactions will be committed or
587 * rolled back. The changes will be rolled back if any transaction is ended without being
588 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700589 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700590 * <p>Here is the standard idiom for transactions:
591 *
592 * <pre>
593 * db.beginTransactionWithListener(listener);
594 * try {
595 * ...
596 * db.setTransactionSuccessful();
597 * } finally {
598 * db.endTransaction();
599 * }
600 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700601 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700602 * @param transactionListener listener that should be notified when the transaction begins,
603 * commits, or is rolled back, either explicitly or by a call to
604 * {@link #yieldIfContendedSafely}.
605 */
606 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700607 beginTransaction(transactionListener, true);
608 }
609
610 /**
611 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
612 * the outer transaction is ended all of the work done in that transaction
613 * and all of the nested transactions will be committed or rolled back. The
614 * changes will be rolled back if any transaction is ended without being
615 * marked as clean (by calling setTransactionSuccessful). Otherwise they
616 * will be committed.
617 * <p>
618 * Here is the standard idiom for transactions:
619 *
620 * <pre>
621 * db.beginTransactionWithListenerNonExclusive(listener);
622 * try {
623 * ...
624 * db.setTransactionSuccessful();
625 * } finally {
626 * db.endTransaction();
627 * }
628 * </pre>
629 *
630 * @param transactionListener listener that should be notified when the
631 * transaction begins, commits, or is rolled back, either
632 * explicitly or by a call to {@link #yieldIfContendedSafely}.
633 */
634 public void beginTransactionWithListenerNonExclusive(
635 SQLiteTransactionListener transactionListener) {
636 beginTransaction(transactionListener, false);
637 }
638
639 private void beginTransaction(SQLiteTransactionListener transactionListener,
640 boolean exclusive) {
Vasu Noriccd95442010-05-28 17:04:16 -0700641 verifyDbIsOpen();
Vasu Nori16057fa2011-03-18 11:40:37 -0700642 lockForced(BEGIN_SQL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 boolean ok = false;
644 try {
645 // If this thread already had the lock then get out
646 if (mLock.getHoldCount() > 1) {
647 if (mInnerTransactionIsSuccessful) {
648 String msg = "Cannot call beginTransaction between "
649 + "calling setTransactionSuccessful and endTransaction";
650 IllegalStateException e = new IllegalStateException(msg);
651 Log.e(TAG, "beginTransaction() failed", e);
652 throw e;
653 }
654 ok = true;
655 return;
656 }
657
658 // This thread didn't already have the lock, so begin a database
659 // transaction now.
Vasu Nori57feb5d2010-06-22 10:39:04 -0700660 if (exclusive && mConnectionPool == null) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700661 execSQL("BEGIN EXCLUSIVE;");
662 } else {
663 execSQL("BEGIN IMMEDIATE;");
664 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700665 mTransStartTime = SystemClock.uptimeMillis();
Fred Quintanac4516a72009-09-03 12:14:06 -0700666 mTransactionListener = transactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 mTransactionIsSuccessful = true;
668 mInnerTransactionIsSuccessful = false;
Fred Quintanac4516a72009-09-03 12:14:06 -0700669 if (transactionListener != null) {
670 try {
671 transactionListener.onBegin();
672 } catch (RuntimeException e) {
673 execSQL("ROLLBACK;");
674 throw e;
675 }
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 ok = true;
678 } finally {
679 if (!ok) {
680 // beginTransaction is called before the try block so we must release the lock in
681 // the case of failure.
682 unlockForced();
683 }
684 }
685 }
686
687 /**
688 * End a transaction. See beginTransaction for notes about how to use this and when transactions
689 * are committed and rolled back.
690 */
691 public void endTransaction() {
Vasu Noriccd95442010-05-28 17:04:16 -0700692 verifyLockOwner();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 try {
694 if (mInnerTransactionIsSuccessful) {
695 mInnerTransactionIsSuccessful = false;
696 } else {
697 mTransactionIsSuccessful = false;
698 }
699 if (mLock.getHoldCount() != 1) {
700 return;
701 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700702 RuntimeException savedException = null;
703 if (mTransactionListener != null) {
704 try {
705 if (mTransactionIsSuccessful) {
706 mTransactionListener.onCommit();
707 } else {
708 mTransactionListener.onRollback();
709 }
710 } catch (RuntimeException e) {
711 savedException = e;
712 mTransactionIsSuccessful = false;
713 }
714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 if (mTransactionIsSuccessful) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800716 execSQL(COMMIT_SQL);
Vasu Nori6c354da2010-04-26 23:33:39 -0700717 // if write-ahead logging is used, we have to take care of checkpoint.
718 // TODO: should applications be given the flexibility of choosing when to
719 // trigger checkpoint?
720 // for now, do checkpoint after every COMMIT because that is the fastest
721 // way to guarantee that readers will see latest data.
722 // but this is the slowest way to run sqlite with in write-ahead logging mode.
723 if (this.mConnectionPool != null) {
724 execSQL("PRAGMA wal_checkpoint;");
725 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
726 Log.i(TAG, "PRAGMA wal_Checkpoint done");
727 }
728 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700729 // log the transaction time to the Eventlog.
730 logTimeStat(getLastSqlStatement(), mTransStartTime, COMMIT_SQL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 } else {
732 try {
733 execSQL("ROLLBACK;");
Fred Quintanac4516a72009-09-03 12:14:06 -0700734 if (savedException != null) {
735 throw savedException;
736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 } catch (SQLException e) {
738 if (Config.LOGD) {
739 Log.d(TAG, "exception during rollback, maybe the DB previously "
740 + "performed an auto-rollback");
741 }
742 }
743 }
744 } finally {
Fred Quintanac4516a72009-09-03 12:14:06 -0700745 mTransactionListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 unlockForced();
747 if (Config.LOGV) {
748 Log.v(TAG, "unlocked " + Thread.currentThread()
749 + ", holdCount is " + mLock.getHoldCount());
750 }
751 }
752 }
753
754 /**
755 * Marks the current transaction as successful. Do not do any more database work between
756 * calling this and calling endTransaction. Do as little non-database work as possible in that
757 * situation too. If any errors are encountered between this and endTransaction the transaction
758 * will still be committed.
759 *
760 * @throws IllegalStateException if the current thread is not in a transaction or the
761 * transaction is already marked as successful.
762 */
763 public void setTransactionSuccessful() {
Vasu Noriccd95442010-05-28 17:04:16 -0700764 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (!mLock.isHeldByCurrentThread()) {
766 throw new IllegalStateException("no transaction pending");
767 }
768 if (mInnerTransactionIsSuccessful) {
769 throw new IllegalStateException(
770 "setTransactionSuccessful may only be called once per call to beginTransaction");
771 }
772 mInnerTransactionIsSuccessful = true;
773 }
774
775 /**
776 * return true if there is a transaction pending
777 */
778 public boolean inTransaction() {
Vasu Norice38b982010-07-22 13:57:13 -0700779 return mLock.getHoldCount() > 0 || mTransactionUsingExecSql;
780 }
781
782 /* package */ synchronized void setTransactionUsingExecSqlFlag() {
783 if (Log.isLoggable(TAG, Log.DEBUG)) {
784 Log.i(TAG, "found execSQL('begin transaction')");
785 }
786 mTransactionUsingExecSql = true;
787 }
788
789 /* package */ synchronized void resetTransactionUsingExecSqlFlag() {
790 if (Log.isLoggable(TAG, Log.DEBUG)) {
791 if (mTransactionUsingExecSql) {
792 Log.i(TAG, "found execSQL('commit or end or rollback')");
793 }
794 }
795 mTransactionUsingExecSql = false;
796 }
797
798 /**
799 * Returns true if the caller is considered part of the current transaction, if any.
800 * <p>
801 * Caller is part of the current transaction if either of the following is true
802 * <ol>
803 * <li>If transaction is started by calling beginTransaction() methods AND if the caller is
804 * in the same thread as the thread that started the transaction.
805 * </li>
806 * <li>If the transaction is started by calling {@link #execSQL(String)} like this:
807 * execSQL("BEGIN transaction"). In this case, every thread in the process is considered
808 * part of the current transaction.</li>
809 * </ol>
810 *
811 * @return true if the caller is considered part of the current transaction, if any.
812 */
813 /* package */ synchronized boolean amIInTransaction() {
814 // always do this test on the main database connection - NOT on pooled database connection
815 // since transactions always occur on the main database connections only.
816 SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this;
817 boolean b = (!db.inTransaction()) ? false :
818 db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread();
819 if (Log.isLoggable(TAG, Log.DEBUG)) {
820 Log.i(TAG, "amIinTransaction: " + b);
821 }
822 return b;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824
825 /**
826 * Checks if the database lock is held by this thread.
827 *
828 * @return true, if this thread is holding the database lock.
829 */
830 public boolean isDbLockedByCurrentThread() {
831 return mLock.isHeldByCurrentThread();
832 }
833
834 /**
835 * Checks if the database is locked by another thread. This is
836 * just an estimate, since this status can change at any time,
837 * including after the call is made but before the result has
838 * been acted upon.
839 *
840 * @return true, if the database is locked by another thread
841 */
842 public boolean isDbLockedByOtherThreads() {
843 return !mLock.isHeldByCurrentThread() && mLock.isLocked();
844 }
845
846 /**
847 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
848 * successful so far. Do not call setTransactionSuccessful before calling this. When this
849 * returns a new transaction will have been created but not marked as successful.
850 * @return true if the transaction was yielded
851 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
852 * will not be yielded. Use yieldIfContendedSafely instead.
853 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700854 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700856 return yieldIfContendedHelper(false /* do not check yielding */,
857 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859
860 /**
861 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
862 * successful so far. Do not call setTransactionSuccessful before calling this. When this
863 * returns a new transaction will have been created but not marked as successful. This assumes
864 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700865 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 * @return true if the transaction was yielded
867 */
868 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700869 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
Fred Quintana5c7aede2009-08-27 21:41:27 -0700872 /**
873 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
874 * successful so far. Do not call setTransactionSuccessful before calling this. When this
875 * returns a new transaction will have been created but not marked as successful. This assumes
876 * that there are no nested transactions (beginTransaction has only been called once) and will
877 * throw an exception if that is not the case.
878 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
879 * the lock was actually yielded. This will allow other background threads to make some
880 * more progress than they would if we started the transaction immediately.
881 * @return true if the transaction was yielded
882 */
883 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
884 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
885 }
886
887 private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 if (mLock.getQueueLength() == 0) {
889 // Reset the lock acquire time since we know that the thread was willing to yield
890 // the lock at this time.
891 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
892 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
893 return false;
894 }
895 setTransactionSuccessful();
Fred Quintanac4516a72009-09-03 12:14:06 -0700896 SQLiteTransactionListener transactionListener = mTransactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 endTransaction();
898 if (checkFullyYielded) {
899 if (this.isDbLockedByCurrentThread()) {
900 throw new IllegalStateException(
901 "Db locked more than once. yielfIfContended cannot yield");
902 }
903 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700904 if (sleepAfterYieldDelay > 0) {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700905 // Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to
906 // check if anyone is using the database. If the database is not contended,
907 // retake the lock and return.
908 long remainingDelay = sleepAfterYieldDelay;
909 while (remainingDelay > 0) {
910 try {
911 Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ?
912 remainingDelay : SLEEP_AFTER_YIELD_QUANTUM);
913 } catch (InterruptedException e) {
914 Thread.interrupted();
915 }
916 remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM;
917 if (mLock.getQueueLength() == 0) {
918 break;
919 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700920 }
921 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700922 beginTransactionWithListener(transactionListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 return true;
924 }
925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 /**
Vasu Nori95675132010-07-21 16:24:40 -0700927 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 */
Vasu Nori95675132010-07-21 16:24:40 -0700929 @Deprecated
930 public Map<String, String> getSyncedTables() {
931 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933
934 /**
935 * Used to allow returning sub-classes of {@link Cursor} when calling query.
936 */
937 public interface CursorFactory {
938 /**
939 * See
Vasu Noribfe1dc22010-08-25 16:29:02 -0700940 * {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 */
942 public Cursor newCursor(SQLiteDatabase db,
943 SQLiteCursorDriver masterQuery, String editTable,
944 SQLiteQuery query);
945 }
946
947 /**
948 * Open the database according to the flags {@link #OPEN_READWRITE}
949 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
950 *
951 * <p>Sets the locale of the database to the the system's current locale.
952 * Call {@link #setLocale} if you would like something else.</p>
953 *
954 * @param path to database file to open and/or create
955 * @param factory an optional factory class that is called to instantiate a
956 * cursor when query is called, or null for default
957 * @param flags to control database access mode
958 * @return the newly opened database
959 * @throws SQLiteException if the database cannot be opened
960 */
961 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700962 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
963 }
964
965 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700966 * Open the database according to the flags {@link #OPEN_READWRITE}
967 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
968 *
969 * <p>Sets the locale of the database to the the system's current locale.
970 * Call {@link #setLocale} if you would like something else.</p>
971 *
972 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
973 * used to handle corruption when sqlite reports database corruption.</p>
974 *
975 * @param path to database file to open and/or create
976 * @param factory an optional factory class that is called to instantiate a
977 * cursor when query is called, or null for default
978 * @param flags to control database access mode
979 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
980 * when sqlite reports database corruption
981 * @return the newly opened database
982 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700983 */
984 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
985 DatabaseErrorHandler errorHandler) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700986 SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler,
987 (short) 0 /* the main connection handle */);
Vasu Noria8c24902010-06-01 11:30:27 -0700988
989 // set sqlite pagesize to mBlockSize
990 if (sBlockSize == 0) {
991 // TODO: "/data" should be a static final String constant somewhere. it is hardcoded
992 // in several places right now.
993 sBlockSize = new StatFs("/data").getBlockSize();
994 }
995 sqliteDatabase.setPageSize(sBlockSize);
Vasu Noria22d8842011-01-06 08:30:29 -0800996 sqliteDatabase.setJournalMode(path, "TRUNCATE");
Vasu Norif9e2bd02010-06-04 16:49:51 -0700997
Vasu Noriccd95442010-05-28 17:04:16 -0700998 // add this database to the list of databases opened in this process
Vasu Nori0732f792010-07-29 17:24:12 -0700999 synchronized(mActiveDatabases) {
1000 mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase));
1001 }
Vasu Noric3849202010-03-09 10:47:25 -08001002 return sqliteDatabase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004
Vasu Nori6c354da2010-04-26 23:33:39 -07001005 private static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
1006 DatabaseErrorHandler errorHandler, short connectionNum) {
1007 SQLiteDatabase db = new SQLiteDatabase(path, factory, flags, errorHandler, connectionNum);
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001008 try {
Vasu Norice38b982010-07-22 13:57:13 -07001009 if (Log.isLoggable(TAG, Log.DEBUG)) {
1010 Log.i(TAG, "opening the db : " + path);
1011 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001012 // Open the database.
1013 db.dbopen(path, flags);
1014 db.setLocale(Locale.getDefault());
1015 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
1016 db.enableSqlTracing(path, connectionNum);
1017 }
1018 if (SQLiteDebug.DEBUG_SQL_TIME) {
1019 db.enableSqlProfiling(path, connectionNum);
1020 }
1021 return db;
1022 } catch (SQLiteDatabaseCorruptException e) {
Vasu Nori6a904bc2011-01-05 18:35:40 -08001023 db.mErrorHandler.onCorruption(db);
1024 return SQLiteDatabase.openDatabase(path, factory, flags, errorHandler);
Vasu Nori6c354da2010-04-26 23:33:39 -07001025 } catch (SQLiteException e) {
1026 Log.e(TAG, "Failed to open the database. closing it.", e);
1027 db.close();
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001028 throw e;
1029 }
1030 }
1031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 /**
1033 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
1034 */
1035 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
1036 return openOrCreateDatabase(file.getPath(), factory);
1037 }
1038
1039 /**
1040 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
1041 */
1042 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
1043 return openDatabase(path, factory, CREATE_IF_NECESSARY);
1044 }
1045
1046 /**
Vasu Nori6c354da2010-04-26 23:33:39 -07001047 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001048 */
1049 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
1050 DatabaseErrorHandler errorHandler) {
1051 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
1052 }
1053
Vasu Noria98cb262010-06-22 13:16:35 -07001054 private void setJournalMode(final String dbPath, final String mode) {
1055 // journal mode can be set only for non-memory databases
Vasu Nori8fcda302010-11-08 13:46:40 -08001056 // AND can't be set for readonly databases
1057 if (dbPath.equalsIgnoreCase(MEMORY_DB_PATH) || isReadOnly()) {
1058 return;
1059 }
1060 String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null);
1061 if (!s.equalsIgnoreCase(mode)) {
1062 Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + dbPath +
1063 " (on pragma set journal_mode, sqlite returned:" + s);
Vasu Noria98cb262010-06-22 13:16:35 -07001064 }
1065 }
1066
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001067 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 * Create a memory backed SQLite database. Its contents will be destroyed
1069 * when the database is closed.
1070 *
1071 * <p>Sets the locale of the database to the the system's current locale.
1072 * Call {@link #setLocale} if you would like something else.</p>
1073 *
1074 * @param factory an optional factory class that is called to instantiate a
1075 * cursor when query is called
1076 * @return a SQLiteDatabase object, or null if the database can't be created
1077 */
1078 public static SQLiteDatabase create(CursorFactory factory) {
1079 // This is a magic string with special meaning for SQLite.
Vasu Noria98cb262010-06-22 13:16:35 -07001080 return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082
1083 /**
1084 * Close the database.
1085 */
1086 public void close() {
Vasu Nori587423a2010-09-27 18:18:34 -07001087 if (!isOpen()) {
1088 return;
1089 }
Vasu Norice38b982010-07-22 13:57:13 -07001090 if (Log.isLoggable(TAG, Log.DEBUG)) {
Vasu Nori75010102010-07-01 16:23:06 -07001091 Log.i(TAG, "closing db: " + mPath + " (connection # " + mConnectionNum);
1092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 lock();
1094 try {
Vasu Noriffe06122010-09-27 12:32:57 -07001095 // some other thread could have closed this database while I was waiting for lock.
1096 // check the database state
1097 if (!isOpen()) {
1098 return;
1099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 closeClosable();
Vasu Norifea6f6d2010-05-21 15:36:06 -07001101 // finalize ALL statements queued up so far
1102 closePendingStatements();
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001103 releaseCustomFunctions();
Vasu Norif6373e92010-03-16 10:21:00 -07001104 // close this database instance - regardless of its reference count value
Vasu Nori422dad02010-09-03 16:03:08 -07001105 closeDatabase();
Vasu Nori6c354da2010-04-26 23:33:39 -07001106 if (mConnectionPool != null) {
Vasu Norice38b982010-07-22 13:57:13 -07001107 if (Log.isLoggable(TAG, Log.DEBUG)) {
1108 assert mConnectionPool != null;
1109 Log.i(TAG, mConnectionPool.toString());
1110 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001111 mConnectionPool.close();
1112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 } finally {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001114 unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116 }
1117
1118 private void closeClosable() {
Vasu Noriccd95442010-05-28 17:04:16 -07001119 /* deallocate all compiled SQL statement objects from mCompiledQueries cache.
Vasu Norie495d1f2010-01-06 16:34:19 -08001120 * this should be done before de-referencing all {@link SQLiteClosable} objects
1121 * from this database object because calling
1122 * {@link SQLiteClosable#onAllReferencesReleasedFromContainer()} could cause the database
1123 * to be closed. sqlite doesn't let a database close if there are
1124 * any unfinalized statements - such as the compiled-sql objects in mCompiledQueries.
1125 */
Vasu Norib729dcc2010-09-14 11:35:49 -07001126 deallocCachedSqlStatements();
Vasu Norie495d1f2010-01-06 16:34:19 -08001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1129 while (iter.hasNext()) {
1130 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1131 SQLiteClosable program = entry.getKey();
1132 if (program != null) {
1133 program.onAllReferencesReleasedFromContainer();
1134 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 /**
Vasu Nori422dad02010-09-03 16:03:08 -07001139 * package level access for testing purposes
1140 */
1141 /* package */ void closeDatabase() throws SQLiteException {
1142 try {
1143 dbclose();
1144 } catch (SQLiteUnfinalizedObjectsException e) {
1145 String msg = e.getMessage();
1146 String[] tokens = msg.split(",", 2);
1147 int stmtId = Integer.parseInt(tokens[0]);
1148 // get extra info about this statement, if it is still to be released by closeClosable()
1149 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1150 boolean found = false;
1151 while (iter.hasNext()) {
1152 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1153 SQLiteClosable program = entry.getKey();
1154 if (program != null && program instanceof SQLiteProgram) {
Vasu Norib4389022010-11-29 14:10:46 -08001155 SQLiteCompiledSql compiledSql = ((SQLiteProgram)program).mCompiledSql;
1156 if (compiledSql.nStatement == stmtId) {
1157 msg = compiledSql.toString();
1158 found = true;
1159 }
Vasu Nori422dad02010-09-03 16:03:08 -07001160 }
1161 }
1162 if (!found) {
1163 // the statement is already released by closeClosable(). is it waiting to be
1164 // finalized?
1165 if (mClosedStatementIds.contains(stmtId)) {
1166 Log.w(TAG, "this shouldn't happen. finalizing the statement now: ");
1167 closePendingStatements();
1168 // try to close the database again
1169 closeDatabase();
1170 }
1171 } else {
1172 // the statement is not yet closed. most probably programming error in the app.
Vasu Norib4389022010-11-29 14:10:46 -08001173 throw new SQLiteUnfinalizedObjectsException(
1174 "close() on database: " + getPath() +
1175 " failed due to un-close()d SQL statements: " + msg);
Vasu Nori422dad02010-09-03 16:03:08 -07001176 }
1177 }
1178 }
1179
1180 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 * Native call to close the database.
1182 */
1183 private native void dbclose();
1184
1185 /**
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001186 * A callback interface for a custom sqlite3 function.
1187 * This can be used to create a function that can be called from
1188 * sqlite3 database triggers.
1189 * @hide
1190 */
1191 public interface CustomFunction {
1192 public void callback(String[] args);
1193 }
1194
1195 /**
1196 * Registers a CustomFunction callback as a function that can be called from
1197 * sqlite3 database triggers.
1198 * @param name the name of the sqlite3 function
1199 * @param numArgs the number of arguments for the function
1200 * @param function callback to call when the function is executed
1201 * @hide
1202 */
1203 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
1204 verifyDbIsOpen();
1205 synchronized (mCustomFunctions) {
1206 int ref = native_addCustomFunction(name, numArgs, function);
1207 if (ref != 0) {
1208 // save a reference to the function for cleanup later
1209 mCustomFunctions.add(new Integer(ref));
1210 } else {
1211 throw new SQLiteException("failed to add custom function " + name);
1212 }
1213 }
1214 }
1215
1216 private void releaseCustomFunctions() {
1217 synchronized (mCustomFunctions) {
1218 for (int i = 0; i < mCustomFunctions.size(); i++) {
1219 Integer function = mCustomFunctions.get(i);
1220 native_releaseCustomFunction(function.intValue());
1221 }
1222 mCustomFunctions.clear();
1223 }
1224 }
1225
1226 // list of CustomFunction references so we can clean up when the database closes
1227 private final ArrayList<Integer> mCustomFunctions =
1228 new ArrayList<Integer>();
1229
1230 private native int native_addCustomFunction(String name, int numArgs, CustomFunction function);
1231 private native void native_releaseCustomFunction(int function);
1232
1233 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 * Gets the database version.
1235 *
1236 * @return the database version
1237 */
1238 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -07001239 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 }
1241
1242 /**
1243 * Sets the database version.
1244 *
1245 * @param version the new database version
1246 */
1247 public void setVersion(int version) {
1248 execSQL("PRAGMA user_version = " + version);
1249 }
1250
1251 /**
1252 * Returns the maximum size the database may grow to.
1253 *
1254 * @return the new maximum database size
1255 */
1256 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001257 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
1258 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
1260
1261 /**
1262 * Sets the maximum size the database will grow to. The maximum size cannot
1263 * be set below the current size.
1264 *
1265 * @param numBytes the maximum database size, in bytes
1266 * @return the new maximum database size
1267 */
1268 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -07001269 long pageSize = getPageSize();
1270 long numPages = numBytes / pageSize;
1271 // If numBytes isn't a multiple of pageSize, bump up a page
1272 if ((numBytes % pageSize) != 0) {
1273 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -07001274 }
Vasu Noriccd95442010-05-28 17:04:16 -07001275 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
1276 null);
1277 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
1279
1280 /**
1281 * Returns the current database page size, in bytes.
1282 *
1283 * @return the database page size, in bytes
1284 */
1285 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001286 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
1288
1289 /**
1290 * Sets the database page size. The page size must be a power of two. This
1291 * method does not work if any data has been written to the database file,
1292 * and must be called right after the database has been created.
1293 *
1294 * @param numBytes the database page size, in bytes
1295 */
1296 public void setPageSize(long numBytes) {
1297 execSQL("PRAGMA page_size = " + numBytes);
1298 }
1299
1300 /**
1301 * Mark this table as syncable. When an update occurs in this table the
1302 * _sync_dirty field will be set to ensure proper syncing operation.
1303 *
1304 * @param table the table to mark as syncable
1305 * @param deletedTable The deleted table that corresponds to the
1306 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -07001307 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 */
Vasu Nori95675132010-07-21 16:24:40 -07001309 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312
1313 /**
1314 * Mark this table as syncable, with the _sync_dirty residing in another
1315 * table. When an update occurs in this table the _sync_dirty field of the
1316 * row in updateTable with the _id in foreignKey will be set to
1317 * ensure proper syncing operation.
1318 *
1319 * @param table an update on this table will trigger a sync time removal
1320 * @param foreignKey this is the column in table whose value is an _id in
1321 * updateTable
1322 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -07001323 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 */
Vasu Nori95675132010-07-21 16:24:40 -07001325 @Deprecated
1326 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328
1329 /**
1330 * Finds the name of the first table, which is editable.
1331 *
1332 * @param tables a list of tables
1333 * @return the first table listed
1334 */
1335 public static String findEditTable(String tables) {
1336 if (!TextUtils.isEmpty(tables)) {
1337 // find the first word terminated by either a space or a comma
1338 int spacepos = tables.indexOf(' ');
1339 int commapos = tables.indexOf(',');
1340
1341 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
1342 return tables.substring(0, spacepos);
1343 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
1344 return tables.substring(0, commapos);
1345 }
1346 return tables;
1347 } else {
1348 throw new IllegalStateException("Invalid tables");
1349 }
1350 }
1351
1352 /**
1353 * Compiles an SQL statement into a reusable pre-compiled statement object.
1354 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
1355 * statement and fill in those values with {@link SQLiteProgram#bindString}
1356 * and {@link SQLiteProgram#bindLong} each time you want to run the
1357 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -07001358 *<p>
1359 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 *
1361 * @param sql The raw SQL statement, may contain ? for unknown values to be
1362 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001363 * @return A pre-compiled {@link SQLiteStatement} object. Note that
1364 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 */
1366 public SQLiteStatement compileStatement(String sql) throws SQLException {
Vasu Noriccd95442010-05-28 17:04:16 -07001367 verifyDbIsOpen();
Vasu Nori0732f792010-07-29 17:24:12 -07001368 return new SQLiteStatement(this, sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370
1371 /**
1372 * Query the given URL, returning a {@link Cursor} over the result set.
1373 *
1374 * @param distinct true if you want each row to be unique, false otherwise.
1375 * @param table The table name to compile the query against.
1376 * @param columns A list of which columns to return. Passing null will
1377 * return all columns, which is discouraged to prevent reading
1378 * data from storage that isn't going to be used.
1379 * @param selection A filter declaring which rows to return, formatted as an
1380 * SQL WHERE clause (excluding the WHERE itself). Passing null
1381 * will return all rows for the given table.
1382 * @param selectionArgs You may include ?s in selection, which will be
1383 * replaced by the values from selectionArgs, in order that they
1384 * appear in the selection. The values will be bound as Strings.
1385 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1386 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1387 * will cause the rows to not be grouped.
1388 * @param having A filter declare which row groups to include in the cursor,
1389 * if row grouping is being used, formatted as an SQL HAVING
1390 * clause (excluding the HAVING itself). Passing null will cause
1391 * all row groups to be included, and is required when row
1392 * grouping is not being used.
1393 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1394 * (excluding the ORDER BY itself). Passing null will use the
1395 * default sort order, which may be unordered.
1396 * @param limit Limits the number of rows returned by the query,
1397 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001398 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1399 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * @see Cursor
1401 */
1402 public Cursor query(boolean distinct, String table, String[] columns,
1403 String selection, String[] selectionArgs, String groupBy,
1404 String having, String orderBy, String limit) {
1405 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
1406 groupBy, having, orderBy, limit);
1407 }
1408
1409 /**
1410 * Query the given URL, returning a {@link Cursor} over the result set.
1411 *
1412 * @param cursorFactory the cursor factory to use, or null for the default factory
1413 * @param distinct true if you want each row to be unique, false otherwise.
1414 * @param table The table name to compile the query against.
1415 * @param columns A list of which columns to return. Passing null will
1416 * return all columns, which is discouraged to prevent reading
1417 * data from storage that isn't going to be used.
1418 * @param selection A filter declaring which rows to return, formatted as an
1419 * SQL WHERE clause (excluding the WHERE itself). Passing null
1420 * will return all rows for the given table.
1421 * @param selectionArgs You may include ?s in selection, which will be
1422 * replaced by the values from selectionArgs, in order that they
1423 * appear in the selection. The values will be bound as Strings.
1424 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1425 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1426 * will cause the rows to not be grouped.
1427 * @param having A filter declare which row groups to include in the cursor,
1428 * if row grouping is being used, formatted as an SQL HAVING
1429 * clause (excluding the HAVING itself). Passing null will cause
1430 * all row groups to be included, and is required when row
1431 * grouping is not being used.
1432 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1433 * (excluding the ORDER BY itself). Passing null will use the
1434 * default sort order, which may be unordered.
1435 * @param limit Limits the number of rows returned by the query,
1436 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001437 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1438 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 * @see Cursor
1440 */
1441 public Cursor queryWithFactory(CursorFactory cursorFactory,
1442 boolean distinct, String table, String[] columns,
1443 String selection, String[] selectionArgs, String groupBy,
1444 String having, String orderBy, String limit) {
Vasu Noriccd95442010-05-28 17:04:16 -07001445 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 String sql = SQLiteQueryBuilder.buildQueryString(
1447 distinct, table, columns, selection, groupBy, having, orderBy, limit);
1448
1449 return rawQueryWithFactory(
1450 cursorFactory, sql, selectionArgs, findEditTable(table));
1451 }
1452
1453 /**
1454 * Query the given table, returning a {@link Cursor} over the result set.
1455 *
1456 * @param table The table name to compile the query against.
1457 * @param columns A list of which columns to return. Passing null will
1458 * return all columns, which is discouraged to prevent reading
1459 * data from storage that isn't going to be used.
1460 * @param selection A filter declaring which rows to return, formatted as an
1461 * SQL WHERE clause (excluding the WHERE itself). Passing null
1462 * will return all rows for the given table.
1463 * @param selectionArgs You may include ?s in selection, which will be
1464 * replaced by the values from selectionArgs, in order that they
1465 * appear in the selection. The values will be bound as Strings.
1466 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1467 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1468 * will cause the rows to not be grouped.
1469 * @param having A filter declare which row groups to include in the cursor,
1470 * if row grouping is being used, formatted as an SQL HAVING
1471 * clause (excluding the HAVING itself). Passing null will cause
1472 * all row groups to be included, and is required when row
1473 * grouping is not being used.
1474 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1475 * (excluding the ORDER BY itself). Passing null will use the
1476 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001477 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1478 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 * @see Cursor
1480 */
1481 public Cursor query(String table, String[] columns, String selection,
1482 String[] selectionArgs, String groupBy, String having,
1483 String orderBy) {
1484
1485 return query(false, table, columns, selection, selectionArgs, groupBy,
1486 having, orderBy, null /* limit */);
1487 }
1488
1489 /**
1490 * Query the given table, returning a {@link Cursor} over the result set.
1491 *
1492 * @param table The table name to compile the query against.
1493 * @param columns A list of which columns to return. Passing null will
1494 * return all columns, which is discouraged to prevent reading
1495 * data from storage that isn't going to be used.
1496 * @param selection A filter declaring which rows to return, formatted as an
1497 * SQL WHERE clause (excluding the WHERE itself). Passing null
1498 * will return all rows for the given table.
1499 * @param selectionArgs You may include ?s in selection, which will be
1500 * replaced by the values from selectionArgs, in order that they
1501 * appear in the selection. The values will be bound as Strings.
1502 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1503 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1504 * will cause the rows to not be grouped.
1505 * @param having A filter declare which row groups to include in the cursor,
1506 * if row grouping is being used, formatted as an SQL HAVING
1507 * clause (excluding the HAVING itself). Passing null will cause
1508 * all row groups to be included, and is required when row
1509 * grouping is not being used.
1510 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1511 * (excluding the ORDER BY itself). Passing null will use the
1512 * default sort order, which may be unordered.
1513 * @param limit Limits the number of rows returned by the query,
1514 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001515 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1516 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 * @see Cursor
1518 */
1519 public Cursor query(String table, String[] columns, String selection,
1520 String[] selectionArgs, String groupBy, String having,
1521 String orderBy, String limit) {
1522
1523 return query(false, table, columns, selection, selectionArgs, groupBy,
1524 having, orderBy, limit);
1525 }
1526
1527 /**
1528 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1529 *
1530 * @param sql the SQL query. The SQL string must not be ; terminated
1531 * @param selectionArgs You may include ?s in where clause in the query,
1532 * which will be replaced by the values from selectionArgs. The
1533 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001534 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1535 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 */
1537 public Cursor rawQuery(String sql, String[] selectionArgs) {
1538 return rawQueryWithFactory(null, sql, selectionArgs, null);
1539 }
1540
1541 /**
1542 * Runs the provided SQL and returns a cursor over the result set.
1543 *
1544 * @param cursorFactory the cursor factory to use, or null for the default factory
1545 * @param sql the SQL query. The SQL string must not be ; terminated
1546 * @param selectionArgs You may include ?s in where clause in the query,
1547 * which will be replaced by the values from selectionArgs. The
1548 * values will be bound as Strings.
1549 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001550 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1551 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 */
1553 public Cursor rawQueryWithFactory(
1554 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1555 String editTable) {
Vasu Noriccd95442010-05-28 17:04:16 -07001556 verifyDbIsOpen();
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -07001557 BlockGuard.getThreadPolicy().onReadFromDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 long timeStart = 0;
1559
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001560 if (Config.LOGV || mSlowQueryThreshold != -1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 timeStart = System.currentTimeMillis();
1562 }
1563
Vasu Nori6c354da2010-04-26 23:33:39 -07001564 SQLiteDatabase db = getDbConnection(sql);
1565 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001567 Cursor cursor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 try {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001569 cursor = driver.query(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 cursorFactory != null ? cursorFactory : mFactory,
1571 selectionArgs);
1572 } finally {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001573 if (Config.LOGV || mSlowQueryThreshold != -1) {
1574
Vasu Nori020e5342010-04-28 14:22:38 -07001575 // Force query execution
1576 int count = -1;
1577 if (cursor != null) {
1578 count = cursor.getCount();
1579 }
1580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 long duration = System.currentTimeMillis() - timeStart;
1582
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001583 if (Config.LOGV || duration >= mSlowQueryThreshold) {
1584 Log.v(SQLiteCursor.TAG,
1585 "query (" + duration + " ms): " + driver.toString() + ", args are "
1586 + (selectionArgs != null
1587 ? TextUtils.join(",", selectionArgs)
Vasu Nori020e5342010-04-28 14:22:38 -07001588 : "<null>") + ", count is " + count);
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001591 releaseDbConnection(db);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001593 return cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595
1596 /**
1597 * Runs the provided SQL and returns a cursor over the result set.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001598 * The cursor will read an initial set of rows and the return to the caller.
1599 * It will continue to read in batches and send data changed notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 * when the later batches are ready.
1601 * @param sql the SQL query. The SQL string must not be ; terminated
1602 * @param selectionArgs You may include ?s in where clause in the query,
1603 * which will be replaced by the values from selectionArgs. The
1604 * values will be bound as Strings.
1605 * @param initialRead set the initial count of items to read from the cursor
1606 * @param maxRead set the count of items to read on each iteration after the first
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001607 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1608 * {@link Cursor}s are not synchronized, see the documentation for more details.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001609 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001610 * This work is incomplete and not fully tested or reviewed, so currently
1611 * hidden.
1612 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001614 public Cursor rawQuery(String sql, String[] selectionArgs,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 int initialRead, int maxRead) {
1616 SQLiteCursor c = (SQLiteCursor)rawQueryWithFactory(
1617 null, sql, selectionArgs, null);
1618 c.setLoadStyle(initialRead, maxRead);
1619 return c;
1620 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 /**
1623 * Convenience method for inserting a row into the database.
1624 *
1625 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001626 * @param nullColumnHack optional; may be <code>null</code>.
1627 * SQL doesn't allow inserting a completely empty row without
1628 * naming at least one column name. If your provided <code>values</code> is
1629 * empty, no column names are known and an empty row can't be inserted.
1630 * If not set to null, the <code>nullColumnHack</code> parameter
1631 * provides the name of nullable column name to explicitly insert a NULL into
1632 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 * @param values this map contains the initial column values for the
1634 * row. The keys should be the column names and the values the
1635 * column values
1636 * @return the row ID of the newly inserted row, or -1 if an error occurred
1637 */
1638 public long insert(String table, String nullColumnHack, ContentValues values) {
1639 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001640 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 } catch (SQLException e) {
1642 Log.e(TAG, "Error inserting " + values, e);
1643 return -1;
1644 }
1645 }
1646
1647 /**
1648 * Convenience method for inserting a row into the database.
1649 *
1650 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001651 * @param nullColumnHack optional; may be <code>null</code>.
1652 * SQL doesn't allow inserting a completely empty row without
1653 * naming at least one column name. If your provided <code>values</code> is
1654 * empty, no column names are known and an empty row can't be inserted.
1655 * If not set to null, the <code>nullColumnHack</code> parameter
1656 * provides the name of nullable column name to explicitly insert a NULL into
1657 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 * @param values this map contains the initial column values for the
1659 * row. The keys should be the column names and the values the
1660 * column values
1661 * @throws SQLException
1662 * @return the row ID of the newly inserted row, or -1 if an error occurred
1663 */
1664 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1665 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001666 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668
1669 /**
1670 * Convenience method for replacing a row in the database.
1671 *
1672 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001673 * @param nullColumnHack optional; may be <code>null</code>.
1674 * SQL doesn't allow inserting a completely empty row without
1675 * naming at least one column name. If your provided <code>initialValues</code> is
1676 * empty, no column names are known and an empty row can't be inserted.
1677 * If not set to null, the <code>nullColumnHack</code> parameter
1678 * provides the name of nullable column name to explicitly insert a NULL into
1679 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001681 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 * @return the row ID of the newly inserted row, or -1 if an error occurred
1683 */
1684 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1685 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001686 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001687 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 } catch (SQLException e) {
1689 Log.e(TAG, "Error inserting " + initialValues, e);
1690 return -1;
1691 }
1692 }
1693
1694 /**
1695 * Convenience method for replacing a row in the database.
1696 *
1697 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001698 * @param nullColumnHack optional; may be <code>null</code>.
1699 * SQL doesn't allow inserting a completely empty row without
1700 * naming at least one column name. If your provided <code>initialValues</code> is
1701 * empty, no column names are known and an empty row can't be inserted.
1702 * If not set to null, the <code>nullColumnHack</code> parameter
1703 * provides the name of nullable column name to explicitly insert a NULL into
1704 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 * @param initialValues this map contains the initial column values for
1706 * the row. The key
1707 * @throws SQLException
1708 * @return the row ID of the newly inserted row, or -1 if an error occurred
1709 */
1710 public long replaceOrThrow(String table, String nullColumnHack,
1711 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001712 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001713 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715
1716 /**
1717 * General method for inserting a row into the database.
1718 *
1719 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001720 * @param nullColumnHack optional; may be <code>null</code>.
1721 * SQL doesn't allow inserting a completely empty row without
1722 * naming at least one column name. If your provided <code>initialValues</code> is
1723 * empty, no column names are known and an empty row can't be inserted.
1724 * If not set to null, the <code>nullColumnHack</code> parameter
1725 * provides the name of nullable column name to explicitly insert a NULL into
1726 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 * @param initialValues this map contains the initial column values for the
1728 * row. The keys should be the column names and the values the
1729 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001730 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001731 * @return the row ID of the newly inserted row
1732 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001733 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001734 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 */
1736 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001737 ContentValues initialValues, int conflictAlgorithm) {
Vasu Nori0732f792010-07-29 17:24:12 -07001738 StringBuilder sql = new StringBuilder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001740 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 sql.append(" INTO ");
1742 sql.append(table);
Vasu Nori0732f792010-07-29 17:24:12 -07001743 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744
Vasu Nori0732f792010-07-29 17:24:12 -07001745 Object[] bindArgs = null;
1746 int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
1747 if (size > 0) {
1748 bindArgs = new Object[size];
1749 int i = 0;
1750 for (String colName : initialValues.keySet()) {
1751 sql.append((i > 0) ? "," : "");
1752 sql.append(colName);
1753 bindArgs[i++] = initialValues.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 sql.append(')');
Vasu Nori0732f792010-07-29 17:24:12 -07001756 sql.append(" VALUES (");
1757 for (i = 0; i < size; i++) {
1758 sql.append((i > 0) ? ",?" : "?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
Vasu Nori0732f792010-07-29 17:24:12 -07001760 } else {
1761 sql.append(nullColumnHack + ") VALUES (NULL");
1762 }
1763 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764
Vasu Nori0732f792010-07-29 17:24:12 -07001765 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1766 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001767 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 } catch (SQLiteDatabaseCorruptException e) {
1769 onCorruption();
1770 throw e;
1771 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001772 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774 }
1775
1776 /**
1777 * Convenience method for deleting rows in the database.
1778 *
1779 * @param table the table to delete from
1780 * @param whereClause the optional WHERE clause to apply when deleting.
1781 * Passing null will delete all rows.
1782 * @return the number of rows affected if a whereClause is passed in, 0
1783 * otherwise. To remove all rows and get a count pass "1" as the
1784 * whereClause.
1785 */
1786 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Nori0732f792010-07-29 17:24:12 -07001787 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1788 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001790 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 } catch (SQLiteDatabaseCorruptException e) {
1792 onCorruption();
1793 throw e;
1794 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001795 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
1798
1799 /**
1800 * Convenience method for updating rows in the database.
1801 *
1802 * @param table the table to update in
1803 * @param values a map from column names to new column values. null is a
1804 * valid value that will be translated to NULL.
1805 * @param whereClause the optional WHERE clause to apply when updating.
1806 * Passing null will update all rows.
1807 * @return the number of rows affected
1808 */
1809 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001810 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 /**
1814 * Convenience method for updating rows in the database.
1815 *
1816 * @param table the table to update in
1817 * @param values a map from column names to new column values. null is a
1818 * valid value that will be translated to NULL.
1819 * @param whereClause the optional WHERE clause to apply when updating.
1820 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001821 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001824 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001825 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001826 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 throw new IllegalArgumentException("Empty values");
1828 }
1829
1830 StringBuilder sql = new StringBuilder(120);
1831 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001832 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 sql.append(table);
1834 sql.append(" SET ");
1835
Vasu Nori0732f792010-07-29 17:24:12 -07001836 // move all bind args to one array
Brian Muramatsu46a88512010-11-12 13:53:57 -08001837 int setValuesSize = values.size();
Vasu Nori0732f792010-07-29 17:24:12 -07001838 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1839 Object[] bindArgs = new Object[bindArgsSize];
1840 int i = 0;
1841 for (String colName : values.keySet()) {
1842 sql.append((i > 0) ? "," : "");
1843 sql.append(colName);
1844 bindArgs[i++] = values.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 sql.append("=?");
Vasu Nori0732f792010-07-29 17:24:12 -07001846 }
1847 if (whereArgs != null) {
1848 for (i = setValuesSize; i < bindArgsSize; i++) {
1849 bindArgs[i] = whereArgs[i - setValuesSize];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 if (!TextUtils.isEmpty(whereClause)) {
1853 sql.append(" WHERE ");
1854 sql.append(whereClause);
1855 }
1856
Vasu Nori0732f792010-07-29 17:24:12 -07001857 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001859 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 } catch (SQLiteDatabaseCorruptException e) {
1861 onCorruption();
1862 throw e;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001864 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866 }
1867
1868 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001869 * Execute a single SQL statement that is NOT a SELECT
1870 * or any other SQL statement that returns data.
1871 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001872 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001873 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1874 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1875 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001876 * <p>
1877 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1878 * automatically managed by this class. So, do not set journal_mode
1879 * using "PRAGMA journal_mode'<value>" statement if your app is using
1880 * {@link #enableWriteAheadLogging()}
1881 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 *
Vasu Noriccd95442010-05-28 17:04:16 -07001883 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1884 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001885 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001887 public void execSQL(String sql) throws SQLException {
Vasu Nori16057fa2011-03-18 11:40:37 -07001888 if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
Vasu Nori8d111032010-06-22 18:34:21 -07001889 disableWriteAheadLogging();
Vasu Nori24675612010-09-27 14:54:19 -07001890 mHasAttachedDbs = true;
1891 }
Vasu Nori16057fa2011-03-18 11:40:37 -07001892 executeSql(sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894
1895 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001896 * 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 Nori9bf225e2010-07-07 16:38:28 -07001926 * <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 Project9066cfe2009-03-03 19:31:44 -08001932 *
Vasu Noriccd95442010-05-28 17:04:16 -07001933 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1934 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001936 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001938 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 if (bindArgs == null) {
1940 throw new IllegalArgumentException("Empty bindArgs");
1941 }
Vasu Norib83cb7c2010-09-14 13:36:01 -07001942 executeSql(sql, bindArgs);
Vasu Norice38b982010-07-22 13:57:13 -07001943 }
1944
Vasu Nori54025902010-09-14 12:14:26 -07001945 private int executeSql(String sql, Object[] bindArgs) throws SQLException {
Vasu Nori0732f792010-07-29 17:24:12 -07001946 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 try {
Vasu Nori16057fa2011-03-18 11:40:37 -07001948 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 } catch (SQLiteDatabaseCorruptException e) {
1950 onCorruption();
1951 throw e;
1952 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001953 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956
1957 @Override
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001958 protected void finalize() throws Throwable {
1959 try {
1960 if (isOpen()) {
1961 Log.e(TAG, "close() was never explicitly called on database '" +
1962 mPath + "' ", mStackTrace);
1963 closeClosable();
1964 onAllReferencesReleased();
1965 releaseCustomFunctions();
1966 }
1967 } finally {
1968 super.finalize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
1970 }
1971
1972 /**
Vasu Nori21343692010-06-03 16:01:39 -07001973 * Private constructor.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 *
1975 * @param path The full path to the database
1976 * @param factory The factory to use when creating cursors, may be NULL.
1977 * @param flags 0 or {@link #NO_LOCALIZED_COLLATORS}. If the database file already
1978 * exists, mFlags will be updated appropriately.
Vasu Nori21343692010-06-03 16:01:39 -07001979 * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite reports database
1980 * corruption. may be NULL.
Vasu Nori6c354da2010-04-26 23:33:39 -07001981 * @param connectionNum 0 for main database connection handle. 1..N for pooled database
1982 * connection handles.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 */
Vasu Nori21343692010-06-03 16:01:39 -07001984 private SQLiteDatabase(String path, CursorFactory factory, int flags,
Vasu Nori6c354da2010-04-26 23:33:39 -07001985 DatabaseErrorHandler errorHandler, short connectionNum) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if (path == null) {
1987 throw new IllegalArgumentException("path should not be null");
1988 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001989 setMaxSqlCacheSize(DEFAULT_SQL_CACHE_SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 mFlags = flags;
1991 mPath = path;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001992 mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1);
Vasu Nori08b448e2010-03-03 10:05:16 -08001993 mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mFactory = factory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 mPrograms = new WeakHashMap<SQLiteClosable,Object>();
Vasu Nori21343692010-06-03 16:01:39 -07001996 // Set the DatabaseErrorHandler to be used when SQLite reports corruption.
1997 // If the caller sets errorHandler = null, then use default errorhandler.
1998 mErrorHandler = (errorHandler == null) ? new DefaultDatabaseErrorHandler() : errorHandler;
Vasu Nori6c354da2010-04-26 23:33:39 -07001999 mConnectionNum = connectionNum;
Vasu Nori34ad57f02010-12-21 09:32:36 -08002000 /* sqlite soft heap limit http://www.sqlite.org/c3ref/soft_heap_limit64.html
2001 * set it to 4 times the default cursor window size.
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002002 * TODO what is an appropriate value, considering the WAL feature which could burn
Vasu Nori34ad57f02010-12-21 09:32:36 -08002003 * a lot of memory with many connections to the database. needs testing to figure out
2004 * optimal value for this.
2005 */
2006 int limit = Resources.getSystem().getInteger(
2007 com.android.internal.R.integer.config_cursorWindowSize) * 1024 * 4;
2008 native_setSqliteSoftHeapLimit(limit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
2011 /**
2012 * return whether the DB is opened as read only.
2013 * @return true if DB is opened as read only
2014 */
2015 public boolean isReadOnly() {
2016 return (mFlags & OPEN_READ_MASK) == OPEN_READONLY;
2017 }
2018
2019 /**
2020 * @return true if the DB is currently open (has not been closed)
2021 */
2022 public boolean isOpen() {
2023 return mNativeHandle != 0;
2024 }
2025
2026 public boolean needUpgrade(int newVersion) {
2027 return newVersion > getVersion();
2028 }
2029
2030 /**
2031 * Getter for the path to the database file.
2032 *
2033 * @return the path to our database file.
2034 */
2035 public final String getPath() {
2036 return mPath;
2037 }
2038
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002039 /* package */ void logTimeStat(String sql, long beginMillis) {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002040 logTimeStat(sql, beginMillis, null);
2041 }
2042
Vasu Nori16057fa2011-03-18 11:40:37 -07002043 private void logTimeStat(String sql, long beginMillis, String prefix) {
Dan Egnor12311952009-11-23 14:47:45 -08002044 // Sample fast queries in proportion to the time taken.
2045 // Quantize the % first, so the logged sampling probability
2046 // exactly equals the actual sampling rate for this query.
2047
2048 int samplePercent;
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002049 long durationMillis = SystemClock.uptimeMillis() - beginMillis;
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002050 if (durationMillis == 0 && prefix == GET_LOCK_LOG_PREFIX) {
2051 // The common case is locks being uncontended. Don't log those,
2052 // even at 1%, which is our default below.
2053 return;
2054 }
2055 if (sQueryLogTimeInMillis == 0) {
2056 sQueryLogTimeInMillis = SystemProperties.getInt("db.db_operation.threshold_ms", 500);
2057 }
2058 if (durationMillis >= sQueryLogTimeInMillis) {
Dan Egnor12311952009-11-23 14:47:45 -08002059 samplePercent = 100;
Vasu Norifb16cbd2010-07-25 16:38:48 -07002060 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002061 samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1;
Dan Egnor799f7212009-11-24 16:24:44 -08002062 if (mRandom.nextInt(100) >= samplePercent) return;
Dan Egnor12311952009-11-23 14:47:45 -08002063 }
2064
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002065 // Note: the prefix will be "COMMIT;" or "GETLOCK:" when non-null. We wait to do
2066 // it here so we avoid allocating in the common case.
2067 if (prefix != null) {
2068 sql = prefix + sql;
2069 }
Dan Egnor12311952009-11-23 14:47:45 -08002070 if (sql.length() > QUERY_LOG_SQL_LENGTH) sql = sql.substring(0, QUERY_LOG_SQL_LENGTH);
2071
2072 // ActivityThread.currentPackageName() only returns non-null if the
2073 // current thread is an application main thread. This parameter tells
2074 // us whether an event loop is blocked, and if so, which app it is.
2075 //
2076 // Sadly, there's no fast way to determine app name if this is *not* a
2077 // main thread, or when we are invoked via Binder (e.g. ContentProvider).
2078 // Hopefully the full path to the database will be informative enough.
2079
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002080 String blockingPackage = AppGlobals.getInitialPackage();
Dan Egnor12311952009-11-23 14:47:45 -08002081 if (blockingPackage == null) blockingPackage = "";
2082
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002083 EventLog.writeEvent(
Brad Fitzpatrickd8330232010-02-19 10:59:01 -08002084 EVENT_DB_OPERATION,
2085 getPathForLogs(),
2086 sql,
2087 durationMillis,
2088 blockingPackage,
2089 samplePercent);
2090 }
2091
2092 /**
2093 * Removes email addresses from database filenames before they're
2094 * logged to the EventLog where otherwise apps could potentially
2095 * read them.
2096 */
2097 private String getPathForLogs() {
2098 if (mPathForLogs != null) {
2099 return mPathForLogs;
2100 }
2101 if (mPath == null) {
2102 return null;
2103 }
2104 if (mPath.indexOf('@') == -1) {
2105 mPathForLogs = mPath;
2106 } else {
2107 mPathForLogs = EMAIL_IN_DB_PATTERN.matcher(mPath).replaceAll("XX@YY");
2108 }
2109 return mPathForLogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
2111
2112 /**
2113 * Sets the locale for this database. Does nothing if this database has
2114 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
2115 * @throws SQLException if the locale could not be set. The most common reason
2116 * for this is that there is no collator available for the locale you requested.
2117 * In this case the database remains unchanged.
2118 */
2119 public void setLocale(Locale locale) {
2120 lock();
2121 try {
2122 native_setLocale(locale.toString(), mFlags);
2123 } finally {
2124 unlock();
2125 }
2126 }
2127
Vasu Noriccd95442010-05-28 17:04:16 -07002128 /* package */ void verifyDbIsOpen() {
Vasu Nori9463f292010-04-30 12:22:18 -07002129 if (!isOpen()) {
Vasu Nori75010102010-07-01 16:23:06 -07002130 throw new IllegalStateException("database " + getPath() + " (conn# " +
2131 mConnectionNum + ") already closed");
Vasu Nori9463f292010-04-30 12:22:18 -07002132 }
Vasu Noriccd95442010-05-28 17:04:16 -07002133 }
2134
2135 /* package */ void verifyLockOwner() {
2136 verifyDbIsOpen();
2137 if (mLockingEnabled && !isDbLockedByCurrentThread()) {
Vasu Nori9463f292010-04-30 12:22:18 -07002138 throw new IllegalStateException("Don't have database lock!");
2139 }
2140 }
2141
Vasu Norib729dcc2010-09-14 11:35:49 -07002142 /**
2143 * Adds the given SQL and its compiled-statement-id-returned-by-sqlite to the
2144 * cache of compiledQueries attached to 'this'.
2145 * <p>
2146 * If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL,
2147 * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current
2148 * mapping is NOT replaced with the new mapping).
2149 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002150 /* package */ synchronized void addToCompiledQueries(
2151 String sql, SQLiteCompiledSql compiledStatement) {
2152 // don't insert the new mapping if a mapping already exists
2153 if (mCompiledQueries.get(sql) != null) {
2154 return;
2155 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002156
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002157 int maxCacheSz = (mConnectionNum == 0) ? mCompiledQueries.maxSize() :
2158 mParentConnObj.mCompiledQueries.maxSize();
Brian Muramatsu46a88512010-11-12 13:53:57 -08002159
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002160 if (SQLiteDebug.DEBUG_SQL_CACHE) {
2161 boolean printWarning = (mConnectionNum == 0)
2162 ? (!mCacheFullWarning && mCompiledQueries.size() == maxCacheSz)
2163 : (!mParentConnObj.mCacheFullWarning &&
2164 mParentConnObj.mCompiledQueries.size() == maxCacheSz);
2165 if (printWarning) {
2166 /*
2167 * cache size is not enough for this app. log a warning.
2168 * chances are it is NOT using ? for bindargs - or cachesize is too small.
2169 */
2170 Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
2171 getPath() + ". Use setMaxSqlCacheSize() to increase cachesize. ");
2172 mCacheFullWarning = true;
2173 Log.d(TAG, "Here are the SQL statements in Cache of database: " + mPath);
2174 for (String s : mCompiledQueries.snapshot().keySet()) {
2175 Log.d(TAG, "Sql statement in Cache: " + s);
Vasu Nori74fb2682010-10-25 11:48:24 -07002176 }
Vasu Nori7301a232010-11-05 11:46:15 -07002177 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002178 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002179 /* add the given SQLiteCompiledSql compiledStatement to cache.
2180 * no need to worry about the cache size - because {@link #mCompiledQueries}
2181 * self-limits its size.
2182 */
2183 mCompiledQueries.put(sql, compiledStatement);
Vasu Norib729dcc2010-09-14 11:35:49 -07002184 }
2185
2186 /** package-level access for testing purposes */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002187 /* package */ synchronized void deallocCachedSqlStatements() {
2188 for (SQLiteCompiledSql compiledSql : mCompiledQueries.snapshot().values()) {
2189 compiledSql.releaseSqlStatement();
Vasu Norib729dcc2010-09-14 11:35:49 -07002190 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002191 mCompiledQueries.evictAll();
Vasu Norib729dcc2010-09-14 11:35:49 -07002192 }
2193
2194 /**
2195 * From the compiledQueries cache, returns the compiled-statement-id for the given SQL.
2196 * Returns null, if not found in the cache.
2197 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002198 /* package */ synchronized SQLiteCompiledSql getCompiledStatementForSql(String sql) {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002199 return mCompiledQueries.get(sql);
Vasu Norib729dcc2010-09-14 11:35:49 -07002200 }
2201
Vasu Norie495d1f2010-01-06 16:34:19 -08002202 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002203 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08002204 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07002205 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07002206 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07002207 * If this method is called with smaller size than the current maximum value,
2208 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07002209 *<p>
2210 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08002211 *
Vasu Nori90a367262010-04-12 12:49:09 -07002212 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
2213 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or
Vasu Noribfe1dc22010-08-25 16:29:02 -07002214 * the value set with previous setMaxSqlCacheSize() call.
Vasu Norie495d1f2010-01-06 16:34:19 -08002215 */
Vasu Nori54025902010-09-14 12:14:26 -07002216 public void setMaxSqlCacheSize(int cacheSize) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002217 synchronized (this) {
2218 LruCache<String, SQLiteCompiledSql> oldCompiledQueries = mCompiledQueries;
Vasu Nori54025902010-09-14 12:14:26 -07002219 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002220 throw new IllegalStateException(
2221 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
2222 } else if (oldCompiledQueries != null && cacheSize < oldCompiledQueries.maxSize()) {
2223 throw new IllegalStateException("cannot set cacheSize to a value less than the "
2224 + "value set with previous setMaxSqlCacheSize() call.");
Vasu Nori54025902010-09-14 12:14:26 -07002225 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002226 mCompiledQueries = new LruCache<String, SQLiteCompiledSql>(cacheSize) {
2227 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08002228 protected void entryRemoved(boolean evicted, String key, SQLiteCompiledSql oldValue,
2229 SQLiteCompiledSql newValue) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002230 verifyLockOwner();
Jesse Wilson32c80a22011-02-25 17:28:41 -08002231 oldValue.releaseIfNotInUse();
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002232 }
2233 };
2234 if (oldCompiledQueries != null) {
2235 for (Map.Entry<String, SQLiteCompiledSql> entry
2236 : oldCompiledQueries.snapshot().entrySet()) {
2237 mCompiledQueries.put(entry.getKey(), entry.getValue());
2238 }
Vasu Nori24675612010-09-27 14:54:19 -07002239 }
Vasu Nori587423a2010-09-27 18:18:34 -07002240 }
2241 }
2242
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002243 /* package */ synchronized boolean isInStatementCache(String sql) {
2244 return mCompiledQueries.get(sql) != null;
2245 }
2246
2247 /* package */ synchronized void releaseCompiledSqlObj(
2248 String sql, SQLiteCompiledSql compiledSql) {
2249 if (mCompiledQueries.get(sql) == compiledSql) {
2250 // it is in cache - reset its inUse flag
2251 compiledSql.release();
2252 } else {
2253 // it is NOT in cache. finalize it.
2254 compiledSql.releaseSqlStatement();
2255 }
2256 }
2257
2258 private synchronized int getCacheHitNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002259 return mCompiledQueries.hitCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002260 }
2261
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002262 private synchronized int getCacheMissNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002263 return mCompiledQueries.missCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002264 }
2265
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002266 private synchronized int getCachesize() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002267 return mCompiledQueries.size();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002268 }
2269
Vasu Nori6f37f832010-05-19 11:53:25 -07002270 /* package */ void finalizeStatementLater(int id) {
2271 if (!isOpen()) {
2272 // database already closed. this statement will already have been finalized.
2273 return;
2274 }
2275 synchronized(mClosedStatementIds) {
2276 if (mClosedStatementIds.contains(id)) {
2277 // this statement id is already queued up for finalization.
2278 return;
2279 }
2280 mClosedStatementIds.add(id);
2281 }
2282 }
2283
Vasu Nori83ff97d2011-01-30 12:47:55 -08002284 /* package */ boolean isInQueueOfStatementsToBeFinalized(int id) {
2285 if (!isOpen()) {
2286 // database already closed. this statement will already have been finalized.
2287 // return true so that the caller doesn't have to worry about finalizing this statement.
2288 return true;
2289 }
2290 synchronized(mClosedStatementIds) {
2291 return mClosedStatementIds.contains(id);
2292 }
2293 }
2294
Vasu Norice38b982010-07-22 13:57:13 -07002295 /* package */ void closePendingStatements() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002296 if (!isOpen()) {
2297 // since this database is already closed, no need to finalize anything.
2298 mClosedStatementIds.clear();
2299 return;
2300 }
2301 verifyLockOwner();
2302 /* to minimize synchronization on mClosedStatementIds, make a copy of the list */
2303 ArrayList<Integer> list = new ArrayList<Integer>(mClosedStatementIds.size());
2304 synchronized(mClosedStatementIds) {
2305 list.addAll(mClosedStatementIds);
2306 mClosedStatementIds.clear();
2307 }
2308 // finalize all the statements from the copied list
2309 int size = list.size();
2310 for (int i = 0; i < size; i++) {
2311 native_finalize(list.get(i));
2312 }
2313 }
2314
2315 /**
2316 * for testing only
Vasu Nori6f37f832010-05-19 11:53:25 -07002317 */
Vasu Norice38b982010-07-22 13:57:13 -07002318 /* package */ ArrayList<Integer> getQueuedUpStmtList() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002319 return mClosedStatementIds;
2320 }
2321
Vasu Nori6c354da2010-04-26 23:33:39 -07002322 /**
2323 * This method enables parallel execution of queries from multiple threads on the same database.
2324 * It does this by opening multiple handles to the database and using a different
2325 * database handle for each query.
2326 * <p>
2327 * If a transaction is in progress on one connection handle and say, a table is updated in the
2328 * transaction, then query on the same table on another connection handle will block for the
2329 * transaction to complete. But this method enables such queries to execute by having them
2330 * return old version of the data from the table. Most often it is the data that existed in the
2331 * table prior to the above transaction updates on that table.
2332 * <p>
2333 * Maximum number of simultaneous handles used to execute queries in parallel is
2334 * dependent upon the device memory and possibly other properties.
2335 * <p>
2336 * After calling this method, execution of queries in parallel is enabled as long as this
2337 * database handle is open. To disable execution of queries in parallel, database should
2338 * be closed and reopened.
2339 * <p>
2340 * If a query is part of a transaction, then it is executed on the same database handle the
2341 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07002342 * <p>
2343 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07002344 * possible. In such cases, a message is printed to logcat and false is returned.
2345 * <p>
2346 * This feature is not available for :memory: databases. In such cases,
2347 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07002348 * <p>
2349 * A typical way to use this method is the following:
2350 * <pre>
2351 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
2352 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
2353 * db.enableWriteAheadLogging();
2354 * </pre>
2355 * <p>
2356 * Writers should use {@link #beginTransactionNonExclusive()} or
2357 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
2358 * to start a trsnsaction.
2359 * Non-exclusive mode allows database file to be in readable by threads executing queries.
2360 * </p>
2361 *
Vasu Noria98cb262010-06-22 13:16:35 -07002362 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07002363 */
Vasu Noriffe06122010-09-27 12:32:57 -07002364 public boolean enableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002365 // make sure the database is not READONLY. WAL doesn't make sense for readonly-databases.
2366 if (isReadOnly()) {
2367 return false;
2368 }
2369 // acquire lock - no that no other thread is enabling WAL at the same time
2370 lock();
2371 try {
2372 if (mConnectionPool != null) {
2373 // already enabled
2374 return true;
2375 }
2376 if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
2377 Log.i(TAG, "can't enable WAL for memory databases.");
2378 return false;
2379 }
2380
2381 // make sure this database has NO attached databases because sqlite's write-ahead-logging
2382 // doesn't work for databases with attached databases
2383 if (mHasAttachedDbs) {
2384 if (Log.isLoggable(TAG, Log.DEBUG)) {
2385 Log.d(TAG,
2386 "this database: " + mPath + " has attached databases. can't enable WAL.");
2387 }
2388 return false;
2389 }
2390 mConnectionPool = new DatabaseConnectionPool(this);
2391 setJournalMode(mPath, "WAL");
2392 return true;
2393 } finally {
2394 unlock();
2395 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002396 }
2397
Vasu Nori2827d6d2010-07-04 00:26:18 -07002398 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07002399 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
2400 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07002401 */
Vasu Nori7b04c412010-07-20 10:31:21 -07002402 public void disableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002403 // grab database lock so that writeAheadLogging is not disabled from 2 different threads
2404 // at the same time
2405 lock();
2406 try {
2407 if (mConnectionPool == null) {
2408 return; // already disabled
2409 }
2410 mConnectionPool.close();
2411 setJournalMode(mPath, "TRUNCATE");
2412 mConnectionPool = null;
2413 } finally {
2414 unlock();
2415 }
Vasu Nori8d111032010-06-22 18:34:21 -07002416 }
2417
Vasu Nori65a88832010-07-16 15:14:08 -07002418 /* package */ SQLiteDatabase getDatabaseHandle(String sql) {
2419 if (isPooledConnection()) {
2420 // this is a pooled database connection
Vasu Norice38b982010-07-22 13:57:13 -07002421 // use it if it is open AND if I am not currently part of a transaction
2422 if (isOpen() && !amIInTransaction()) {
Vasu Nori65a88832010-07-16 15:14:08 -07002423 // TODO: use another connection from the pool
2424 // if this connection is currently in use by some other thread
2425 // AND if there are free connections in the pool
2426 return this;
2427 } else {
2428 // the pooled connection is not open! could have been closed either due
2429 // to corruption on this or some other connection to the database
2430 // OR, maybe the connection pool is disabled after this connection has been
2431 // allocated to me. try to get some other pooled or main database connection
2432 return getParentDbConnObj().getDbConnection(sql);
2433 }
2434 } else {
2435 // this is NOT a pooled connection. can we get one?
2436 return getDbConnection(sql);
2437 }
2438 }
2439
Vasu Nori6c354da2010-04-26 23:33:39 -07002440 /* package */ SQLiteDatabase createPoolConnection(short connectionNum) {
Vasu Nori65a88832010-07-16 15:14:08 -07002441 SQLiteDatabase db = openDatabase(mPath, mFactory, mFlags, mErrorHandler, connectionNum);
2442 db.mParentConnObj = this;
2443 return db;
2444 }
2445
2446 private synchronized SQLiteDatabase getParentDbConnObj() {
2447 return mParentConnObj;
Vasu Nori6c354da2010-04-26 23:33:39 -07002448 }
2449
2450 private boolean isPooledConnection() {
2451 return this.mConnectionNum > 0;
2452 }
2453
Vasu Nori2827d6d2010-07-04 00:26:18 -07002454 /* package */ SQLiteDatabase getDbConnection(String sql) {
Vasu Nori6c354da2010-04-26 23:33:39 -07002455 verifyDbIsOpen();
Vasu Noribfe1dc22010-08-25 16:29:02 -07002456 // this method should always be called with main database connection handle.
2457 // the only time when it is called with pooled database connection handle is
2458 // corruption occurs while trying to open a pooled database connection handle.
2459 // in that case, simply return 'this' handle
Vasu Nori65a88832010-07-16 15:14:08 -07002460 if (isPooledConnection()) {
Vasu Noribfe1dc22010-08-25 16:29:02 -07002461 return this;
Vasu Nori65a88832010-07-16 15:14:08 -07002462 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002463
2464 // use the current connection handle if
Vasu Norice38b982010-07-22 13:57:13 -07002465 // 1. if the caller is part of the ongoing transaction, if any
Vasu Nori65a88832010-07-16 15:14:08 -07002466 // 2. OR, if there is NO connection handle pool setup
Vasu Norice38b982010-07-22 13:57:13 -07002467 if (amIInTransaction() || mConnectionPool == null) {
Vasu Nori65a88832010-07-16 15:14:08 -07002468 return this;
Vasu Nori6c354da2010-04-26 23:33:39 -07002469 } else {
2470 // get a connection handle from the pool
2471 if (Log.isLoggable(TAG, Log.DEBUG)) {
2472 assert mConnectionPool != null;
Vasu Norice38b982010-07-22 13:57:13 -07002473 Log.i(TAG, mConnectionPool.toString());
Vasu Nori6c354da2010-04-26 23:33:39 -07002474 }
Vasu Nori65a88832010-07-16 15:14:08 -07002475 return mConnectionPool.get(sql);
Vasu Nori6c354da2010-04-26 23:33:39 -07002476 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002477 }
2478
2479 private void releaseDbConnection(SQLiteDatabase db) {
2480 // ignore this release call if
2481 // 1. the database is closed
2482 // 2. OR, if db is NOT a pooled connection handle
2483 // 3. OR, if the database being released is same as 'this' (this condition means
2484 // that we should always be releasing a pooled connection handle by calling this method
2485 // from the 'main' connection handle
2486 if (!isOpen() || !db.isPooledConnection() || (db == this)) {
2487 return;
2488 }
2489 if (Log.isLoggable(TAG, Log.DEBUG)) {
2490 assert isPooledConnection();
2491 assert mConnectionPool != null;
2492 Log.d(TAG, "releaseDbConnection threadid = " + Thread.currentThread().getId() +
2493 ", releasing # " + db.mConnectionNum + ", " + getPath());
2494 }
2495 mConnectionPool.release(db);
2496 }
2497
Vasu Norif3cf8a42010-03-23 11:41:44 -07002498 /**
2499 * this method is used to collect data about ALL open databases in the current process.
Vasu Nori0732f792010-07-29 17:24:12 -07002500 * bugreport is a user of this data.
Vasu Norif3cf8a42010-03-23 11:41:44 -07002501 */
Vasu Noric3849202010-03-09 10:47:25 -08002502 /* package */ static ArrayList<DbStats> getDbStats() {
2503 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Vasu Nori24675612010-09-27 14:54:19 -07002504 // make a local copy of mActiveDatabases - so that this method is not competing
2505 // for synchronization lock on mActiveDatabases
2506 ArrayList<WeakReference<SQLiteDatabase>> tempList;
2507 synchronized(mActiveDatabases) {
2508 tempList = (ArrayList<WeakReference<SQLiteDatabase>>)mActiveDatabases.clone();
2509 }
2510 for (WeakReference<SQLiteDatabase> w : tempList) {
2511 SQLiteDatabase db = w.get();
2512 if (db == null || !db.isOpen()) {
2513 continue;
2514 }
2515
2516 try {
2517 // get SQLITE_DBSTATUS_LOOKASIDE_USED for the db
2518 int lookasideUsed = db.native_getDbLookaside();
2519
2520 // get the lastnode of the dbname
2521 String path = db.getPath();
2522 int indx = path.lastIndexOf("/");
2523 String lastnode = path.substring((indx != -1) ? ++indx : 0);
2524
2525 // get list of attached dbs and for each db, get its size and pagesize
Vasu Noria017eda2011-01-27 10:52:55 -08002526 List<Pair<String, String>> attachedDbs = db.getAttachedDbs();
Vasu Nori24675612010-09-27 14:54:19 -07002527 if (attachedDbs == null) {
2528 continue;
2529 }
2530 for (int i = 0; i < attachedDbs.size(); i++) {
2531 Pair<String, String> p = attachedDbs.get(i);
2532 long pageCount = DatabaseUtils.longForQuery(db, "PRAGMA " + p.first
2533 + ".page_count;", null);
2534
2535 // first entry in the attached db list is always the main database
2536 // don't worry about prefixing the dbname with "main"
2537 String dbName;
2538 if (i == 0) {
2539 dbName = lastnode;
2540 } else {
2541 // lookaside is only relevant for the main db
2542 lookasideUsed = 0;
2543 dbName = " (attached) " + p.first;
2544 // if the attached db has a path, attach the lastnode from the path to above
2545 if (p.second.trim().length() > 0) {
2546 int idx = p.second.lastIndexOf("/");
2547 dbName += " : " + p.second.substring((idx != -1) ? ++idx : 0);
2548 }
2549 }
2550 if (pageCount > 0) {
2551 dbStatsList.add(new DbStats(dbName, pageCount, db.getPageSize(),
2552 lookasideUsed, db.getCacheHitNum(), db.getCacheMissNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002553 db.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002554 }
2555 }
2556 // if there are pooled connections, return the cache stats for them also.
2557 // while we are trying to query the pooled connections for stats, some other thread
2558 // could be disabling conneciton pool. so, grab a reference to the connection pool.
2559 DatabaseConnectionPool connPool = db.mConnectionPool;
2560 if (connPool != null) {
2561 for (SQLiteDatabase pDb : connPool.getConnectionList()) {
2562 dbStatsList.add(new DbStats("(pooled # " + pDb.mConnectionNum + ") "
2563 + lastnode, 0, 0, 0, pDb.getCacheHitNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002564 pDb.getCacheMissNum(), pDb.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002565 }
2566 }
2567 } catch (SQLiteException e) {
2568 // ignore. we don't care about exceptions when we are taking adb
2569 // bugreport!
2570 }
2571 }
Vasu Noric3849202010-03-09 10:47:25 -08002572 return dbStatsList;
2573 }
2574
2575 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002576 * Returns list of full pathnames of all attached databases including the main database
2577 * by executing 'pragma database_list' on the database.
2578 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002579 * @return ArrayList of pairs of (database name, database file path) or null if the database
2580 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08002581 */
Vasu Noria017eda2011-01-27 10:52:55 -08002582 public List<Pair<String, String>> getAttachedDbs() {
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002583 if (!isOpen()) {
Vasu Norif3cf8a42010-03-23 11:41:44 -07002584 return null;
2585 }
Vasu Noric3849202010-03-09 10:47:25 -08002586 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Vasu Nori24675612010-09-27 14:54:19 -07002587 if (!mHasAttachedDbs) {
2588 // No attached databases.
2589 // There is a small window where attached databases exist but this flag is not set yet.
2590 // This can occur when this thread is in a race condition with another thread
2591 // that is executing the SQL statement: "attach database <blah> as <foo>"
2592 // If this thread is NOT ok with such a race condition (and thus possibly not receive
2593 // the entire list of attached databases), then the caller should ensure that no thread
2594 // is executing any SQL statements while a thread is calling this method.
2595 // Typically, this method is called when 'adb bugreport' is done or the caller wants to
2596 // collect stats on the database and all its attached databases.
2597 attachedDbs.add(new Pair<String, String>("main", mPath));
2598 return attachedDbs;
2599 }
2600 // has attached databases. query sqlite to get the list of attached databases.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002601 Cursor c = null;
2602 try {
2603 c = rawQuery("pragma database_list;", null);
2604 while (c.moveToNext()) {
2605 // sqlite returns a row for each database in the returned list of databases.
2606 // in each row,
2607 // 1st column is the database name such as main, or the database
2608 // name specified on the "ATTACH" command
2609 // 2nd column is the database file path.
2610 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
2611 }
2612 } finally {
2613 if (c != null) {
2614 c.close();
2615 }
Vasu Noric3849202010-03-09 10:47:25 -08002616 }
Vasu Noric3849202010-03-09 10:47:25 -08002617 return attachedDbs;
2618 }
2619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002621 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
2622 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002623 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07002624 *<p>
2625 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002626 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07002627 *<p>
2628 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002629 *
2630 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07002631 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002632 */
2633 public boolean isDatabaseIntegrityOk() {
Vasu Noriccd95442010-05-28 17:04:16 -07002634 verifyDbIsOpen();
Vasu Noria017eda2011-01-27 10:52:55 -08002635 List<Pair<String, String>> attachedDbs = null;
Vasu Noribfe1dc22010-08-25 16:29:02 -07002636 try {
2637 attachedDbs = getAttachedDbs();
2638 if (attachedDbs == null) {
2639 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
2640 "be retrieved. probably because the database is closed");
2641 }
2642 } catch (SQLiteException e) {
2643 // can't get attachedDb list. do integrity check on the main database
2644 attachedDbs = new ArrayList<Pair<String, String>>();
2645 attachedDbs.add(new Pair<String, String>("main", this.mPath));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002646 }
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002647 for (int i = 0; i < attachedDbs.size(); i++) {
2648 Pair<String, String> p = attachedDbs.get(i);
2649 SQLiteStatement prog = null;
2650 try {
2651 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
2652 String rslt = prog.simpleQueryForString();
2653 if (!rslt.equalsIgnoreCase("ok")) {
2654 // integrity_checker failed on main or attached databases
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002655 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
Vasu Noribfe1dc22010-08-25 16:29:02 -07002656 return false;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002657 }
2658 } finally {
2659 if (prog != null) prog.close();
2660 }
2661 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07002662 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002663 }
2664
2665 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 * Native call to open the database.
2667 *
2668 * @param path The full path to the database
2669 */
2670 private native void dbopen(String path, int flags);
2671
2672 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002673 * Native call to setup tracing of all SQL statements
Vasu Nori3ef94e22010-02-05 14:49:04 -08002674 *
2675 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002676 * @param connectionNum connection number: 0 - N, where the main database
2677 * connection handle is numbered 0 and the connection handles in the connection
2678 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002679 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002680 private native void enableSqlTracing(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002681
2682 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002683 * Native call to setup profiling of all SQL statements.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002684 * currently, sqlite's profiling = printing of execution-time
Vasu Noriccd95442010-05-28 17:04:16 -07002685 * (wall-clock time) of each of the SQL statements, as they
Vasu Nori3ef94e22010-02-05 14:49:04 -08002686 * are executed.
2687 *
2688 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002689 * @param connectionNum connection number: 0 - N, where the main database
2690 * connection handle is numbered 0 and the connection handles in the connection
2691 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002692 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002693 private native void enableSqlProfiling(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002694
2695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 * Native call to set the locale. {@link #lock} must be held when calling
2697 * this method.
2698 * @throws SQLException
2699 */
Vasu Nori0732f792010-07-29 17:24:12 -07002700 private native void native_setLocale(String loc, int flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701
2702 /**
Vasu Noric3849202010-03-09 10:47:25 -08002703 * return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here
2704 * http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html
2705 * @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED
2706 */
2707 private native int native_getDbLookaside();
Vasu Nori6f37f832010-05-19 11:53:25 -07002708
2709 /**
2710 * finalizes the given statement id.
2711 *
2712 * @param statementId statement to be finzlied by sqlite
2713 */
2714 private final native void native_finalize(int statementId);
Vasu Nori34ad57f02010-12-21 09:32:36 -08002715
2716 /**
2717 * set sqlite soft heap limit
2718 * http://www.sqlite.org/c3ref/soft_heap_limit64.html
2719 */
2720 private native void native_setSqliteSoftHeapLimit(int softHeapLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721}