blob: d23873d7dc9777be090a31bad525db982a2807b9 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070034import android.util.Log;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080035import android.util.LruCache;
Vasu Noric3849202010-03-09 10:47:25 -080036import android.util.Pair;
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -070037import dalvik.system.BlockGuard;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import java.io.File;
Vasu Noric3849202010-03-09 10:47:25 -080039import java.lang.ref.WeakReference;
Vasu Noric3849202010-03-09 10:47:25 -080040import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import java.util.HashMap;
42import java.util.Iterator;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080043import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.util.Locale;
45import java.util.Map;
Dan Egnor12311952009-11-23 14:47:45 -080046import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.util.WeakHashMap;
Vasu Norid4608a32011-02-03 16:24:06 -080048import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.concurrent.locks.ReentrantLock;
Brad Fitzpatrickd8330232010-02-19 10:59:01 -080050import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52/**
53 * Exposes methods to manage a SQLite database.
54 * <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and
55 * perform other common database management tasks.
56 * <p>See the Notepad sample application in the SDK for an example of creating
57 * and managing a database.
58 * <p> Database names must be unique within an application, not across all
59 * applications.
60 *
61 * <h3>Localized Collation - ORDER BY</h3>
62 * <p>In addition to SQLite's default <code>BINARY</code> collator, Android supplies
63 * two more, <code>LOCALIZED</code>, which changes with the system's current locale
64 * if you wire it up correctly (XXX a link needed!), and <code>UNICODE</code>, which
65 * is the Unicode Collation Algorithm and not tailored to the current locale.
66 */
67public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070068 private static final String TAG = "SQLiteDatabase";
Christopher Tatead9e8b12011-10-05 17:49:26 -070069 private static final boolean ENABLE_DB_SAMPLE = false; // true to enable stats in event log
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) {
Christopher Tatead9e8b12011-10-05 17:49:26 -0700444 if (ENABLE_DB_SAMPLE) {
445 logTimeStat(sql, timeStart, GET_LOCK_LOG_PREFIX);
446 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
Vasu Norid4608a32011-02-03 16:24:06 -0800449 private static class DatabaseReentrantLock extends ReentrantLock {
450 DatabaseReentrantLock(boolean fair) {
451 super(fair);
452 }
453 @Override
454 public Thread getOwner() {
455 return super.getOwner();
456 }
457 public String getOwnerDescription() {
458 Thread t = getOwner();
459 return (t== null) ? "none" : String.valueOf(t.getId());
460 }
461 }
462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 /**
464 * Locks the database for exclusive access. The database lock must be held when
465 * touch the native sqlite3* object since it is single threaded and uses
466 * a polling lock contention algorithm. The lock is recursive, and may be acquired
467 * multiple times by the same thread.
468 *
469 * @see #unlockForced()
470 */
471 private void lockForced() {
Vasu Nori16057fa2011-03-18 11:40:37 -0700472 lock(null, true);
473 }
474
475 private void lockForced(String sql) {
476 lock(sql, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478
479 /**
480 * Releases the database lock. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700481 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 * @see #unlock()
483 */
484 /* package */ void unlock() {
485 if (!mLockingEnabled) return;
486 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
487 if (mLock.getHoldCount() == 1) {
488 checkLockHoldTime();
489 }
490 }
491 mLock.unlock();
492 }
493
494 /**
495 * Releases the database lock.
496 *
497 * @see #unlockForced()
498 */
499 private void unlockForced() {
500 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
501 if (mLock.getHoldCount() == 1) {
502 checkLockHoldTime();
503 }
504 }
505 mLock.unlock();
506 }
507
508 private void checkLockHoldTime() {
509 // Use elapsed real-time since the CPU may sleep when waiting for IO
510 long elapsedTime = SystemClock.elapsedRealtime();
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700511 long lockedTime = elapsedTime - mLockAcquiredWallTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 if (lockedTime < LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT &&
513 !Log.isLoggable(TAG, Log.VERBOSE) &&
514 (elapsedTime - mLastLockMessageTime) < LOCK_WARNING_WINDOW_IN_MS) {
515 return;
516 }
517 if (lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS) {
518 int threadTime = (int)
519 ((Debug.threadCpuTimeNanos() - mLockAcquiredThreadTime) / 1000000);
520 if (threadTime > LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS ||
521 lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT) {
522 mLastLockMessageTime = elapsedTime;
523 String msg = "lock held on " + mPath + " for " + lockedTime + "ms. Thread time was "
524 + threadTime + "ms";
525 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING_STACK_TRACE) {
526 Log.d(TAG, msg, new Exception());
527 } else {
528 Log.d(TAG, msg);
529 }
530 }
531 }
532 }
533
534 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700535 * Begins a transaction in EXCLUSIVE mode.
536 * <p>
537 * Transactions can be nested.
538 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 * the work done in that transaction and all of the nested transactions will be committed or
540 * rolled back. The changes will be rolled back if any transaction is ended without being
541 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700542 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 * <p>Here is the standard idiom for transactions:
544 *
545 * <pre>
546 * db.beginTransaction();
547 * try {
548 * ...
549 * db.setTransactionSuccessful();
550 * } finally {
551 * db.endTransaction();
552 * }
553 * </pre>
554 */
555 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700556 beginTransaction(null /* transactionStatusCallback */, true);
557 }
558
559 /**
560 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
561 * the outer transaction is ended all of the work done in that transaction
562 * and all of the nested transactions will be committed or rolled back. The
563 * changes will be rolled back if any transaction is ended without being
564 * marked as clean (by calling setTransactionSuccessful). Otherwise they
565 * will be committed.
566 * <p>
567 * Here is the standard idiom for transactions:
568 *
569 * <pre>
570 * db.beginTransactionNonExclusive();
571 * try {
572 * ...
573 * db.setTransactionSuccessful();
574 * } finally {
575 * db.endTransaction();
576 * }
577 * </pre>
578 */
579 public void beginTransactionNonExclusive() {
580 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700581 }
582
583 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700584 * Begins a transaction in EXCLUSIVE mode.
585 * <p>
586 * Transactions can be nested.
587 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700588 * the work done in that transaction and all of the nested transactions will be committed or
589 * rolled back. The changes will be rolled back if any transaction is ended without being
590 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700591 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700592 * <p>Here is the standard idiom for transactions:
593 *
594 * <pre>
595 * db.beginTransactionWithListener(listener);
596 * try {
597 * ...
598 * db.setTransactionSuccessful();
599 * } finally {
600 * db.endTransaction();
601 * }
602 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700603 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700604 * @param transactionListener listener that should be notified when the transaction begins,
605 * commits, or is rolled back, either explicitly or by a call to
606 * {@link #yieldIfContendedSafely}.
607 */
608 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700609 beginTransaction(transactionListener, true);
610 }
611
612 /**
613 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
614 * the outer transaction is ended all of the work done in that transaction
615 * and all of the nested transactions will be committed or rolled back. The
616 * changes will be rolled back if any transaction is ended without being
617 * marked as clean (by calling setTransactionSuccessful). Otherwise they
618 * will be committed.
619 * <p>
620 * Here is the standard idiom for transactions:
621 *
622 * <pre>
623 * db.beginTransactionWithListenerNonExclusive(listener);
624 * try {
625 * ...
626 * db.setTransactionSuccessful();
627 * } finally {
628 * db.endTransaction();
629 * }
630 * </pre>
631 *
632 * @param transactionListener listener that should be notified when the
633 * transaction begins, commits, or is rolled back, either
634 * explicitly or by a call to {@link #yieldIfContendedSafely}.
635 */
636 public void beginTransactionWithListenerNonExclusive(
637 SQLiteTransactionListener transactionListener) {
638 beginTransaction(transactionListener, false);
639 }
640
641 private void beginTransaction(SQLiteTransactionListener transactionListener,
642 boolean exclusive) {
Vasu Noriccd95442010-05-28 17:04:16 -0700643 verifyDbIsOpen();
Vasu Nori16057fa2011-03-18 11:40:37 -0700644 lockForced(BEGIN_SQL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 boolean ok = false;
646 try {
647 // If this thread already had the lock then get out
648 if (mLock.getHoldCount() > 1) {
649 if (mInnerTransactionIsSuccessful) {
650 String msg = "Cannot call beginTransaction between "
651 + "calling setTransactionSuccessful and endTransaction";
652 IllegalStateException e = new IllegalStateException(msg);
653 Log.e(TAG, "beginTransaction() failed", e);
654 throw e;
655 }
656 ok = true;
657 return;
658 }
659
660 // This thread didn't already have the lock, so begin a database
661 // transaction now.
Vasu Nori57feb5d2010-06-22 10:39:04 -0700662 if (exclusive && mConnectionPool == null) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700663 execSQL("BEGIN EXCLUSIVE;");
664 } else {
665 execSQL("BEGIN IMMEDIATE;");
666 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700667 mTransStartTime = SystemClock.uptimeMillis();
Fred Quintanac4516a72009-09-03 12:14:06 -0700668 mTransactionListener = transactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 mTransactionIsSuccessful = true;
670 mInnerTransactionIsSuccessful = false;
Fred Quintanac4516a72009-09-03 12:14:06 -0700671 if (transactionListener != null) {
672 try {
673 transactionListener.onBegin();
674 } catch (RuntimeException e) {
675 execSQL("ROLLBACK;");
676 throw e;
677 }
678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 ok = true;
680 } finally {
681 if (!ok) {
682 // beginTransaction is called before the try block so we must release the lock in
683 // the case of failure.
684 unlockForced();
685 }
686 }
687 }
688
689 /**
690 * End a transaction. See beginTransaction for notes about how to use this and when transactions
691 * are committed and rolled back.
692 */
693 public void endTransaction() {
Vasu Noriccd95442010-05-28 17:04:16 -0700694 verifyLockOwner();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 try {
696 if (mInnerTransactionIsSuccessful) {
697 mInnerTransactionIsSuccessful = false;
698 } else {
699 mTransactionIsSuccessful = false;
700 }
701 if (mLock.getHoldCount() != 1) {
702 return;
703 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700704 RuntimeException savedException = null;
705 if (mTransactionListener != null) {
706 try {
707 if (mTransactionIsSuccessful) {
708 mTransactionListener.onCommit();
709 } else {
710 mTransactionListener.onRollback();
711 }
712 } catch (RuntimeException e) {
713 savedException = e;
714 mTransactionIsSuccessful = false;
715 }
716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mTransactionIsSuccessful) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800718 execSQL(COMMIT_SQL);
Vasu Nori6c354da2010-04-26 23:33:39 -0700719 // if write-ahead logging is used, we have to take care of checkpoint.
720 // TODO: should applications be given the flexibility of choosing when to
721 // trigger checkpoint?
722 // for now, do checkpoint after every COMMIT because that is the fastest
723 // way to guarantee that readers will see latest data.
724 // but this is the slowest way to run sqlite with in write-ahead logging mode.
725 if (this.mConnectionPool != null) {
726 execSQL("PRAGMA wal_checkpoint;");
727 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
728 Log.i(TAG, "PRAGMA wal_Checkpoint done");
729 }
730 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700731 // log the transaction time to the Eventlog.
Christopher Tatead9e8b12011-10-05 17:49:26 -0700732 if (ENABLE_DB_SAMPLE) {
733 logTimeStat(getLastSqlStatement(), mTransStartTime, COMMIT_SQL);
734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 } else {
736 try {
737 execSQL("ROLLBACK;");
Fred Quintanac4516a72009-09-03 12:14:06 -0700738 if (savedException != null) {
739 throw savedException;
740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 } catch (SQLException e) {
Joe Onorato43a17652011-04-06 19:22:23 -0700742 if (false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 Log.d(TAG, "exception during rollback, maybe the DB previously "
744 + "performed an auto-rollback");
745 }
746 }
747 }
748 } finally {
Fred Quintanac4516a72009-09-03 12:14:06 -0700749 mTransactionListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 unlockForced();
Joe Onorato43a17652011-04-06 19:22:23 -0700751 if (false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 Log.v(TAG, "unlocked " + Thread.currentThread()
753 + ", holdCount is " + mLock.getHoldCount());
754 }
755 }
756 }
757
758 /**
759 * Marks the current transaction as successful. Do not do any more database work between
760 * calling this and calling endTransaction. Do as little non-database work as possible in that
761 * situation too. If any errors are encountered between this and endTransaction the transaction
762 * will still be committed.
763 *
764 * @throws IllegalStateException if the current thread is not in a transaction or the
765 * transaction is already marked as successful.
766 */
767 public void setTransactionSuccessful() {
Vasu Noriccd95442010-05-28 17:04:16 -0700768 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 if (!mLock.isHeldByCurrentThread()) {
770 throw new IllegalStateException("no transaction pending");
771 }
772 if (mInnerTransactionIsSuccessful) {
773 throw new IllegalStateException(
774 "setTransactionSuccessful may only be called once per call to beginTransaction");
775 }
776 mInnerTransactionIsSuccessful = true;
777 }
778
779 /**
780 * return true if there is a transaction pending
781 */
782 public boolean inTransaction() {
Vasu Norice38b982010-07-22 13:57:13 -0700783 return mLock.getHoldCount() > 0 || mTransactionUsingExecSql;
784 }
785
786 /* package */ synchronized void setTransactionUsingExecSqlFlag() {
787 if (Log.isLoggable(TAG, Log.DEBUG)) {
788 Log.i(TAG, "found execSQL('begin transaction')");
789 }
790 mTransactionUsingExecSql = true;
791 }
792
793 /* package */ synchronized void resetTransactionUsingExecSqlFlag() {
794 if (Log.isLoggable(TAG, Log.DEBUG)) {
795 if (mTransactionUsingExecSql) {
796 Log.i(TAG, "found execSQL('commit or end or rollback')");
797 }
798 }
799 mTransactionUsingExecSql = false;
800 }
801
802 /**
803 * Returns true if the caller is considered part of the current transaction, if any.
804 * <p>
805 * Caller is part of the current transaction if either of the following is true
806 * <ol>
807 * <li>If transaction is started by calling beginTransaction() methods AND if the caller is
808 * in the same thread as the thread that started the transaction.
809 * </li>
810 * <li>If the transaction is started by calling {@link #execSQL(String)} like this:
811 * execSQL("BEGIN transaction"). In this case, every thread in the process is considered
812 * part of the current transaction.</li>
813 * </ol>
814 *
815 * @return true if the caller is considered part of the current transaction, if any.
816 */
817 /* package */ synchronized boolean amIInTransaction() {
818 // always do this test on the main database connection - NOT on pooled database connection
819 // since transactions always occur on the main database connections only.
820 SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this;
821 boolean b = (!db.inTransaction()) ? false :
822 db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread();
823 if (Log.isLoggable(TAG, Log.DEBUG)) {
824 Log.i(TAG, "amIinTransaction: " + b);
825 }
826 return b;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828
829 /**
830 * Checks if the database lock is held by this thread.
831 *
832 * @return true, if this thread is holding the database lock.
833 */
834 public boolean isDbLockedByCurrentThread() {
835 return mLock.isHeldByCurrentThread();
836 }
837
838 /**
839 * Checks if the database is locked by another thread. This is
840 * just an estimate, since this status can change at any time,
841 * including after the call is made but before the result has
842 * been acted upon.
843 *
844 * @return true, if the database is locked by another thread
845 */
846 public boolean isDbLockedByOtherThreads() {
847 return !mLock.isHeldByCurrentThread() && mLock.isLocked();
848 }
849
850 /**
851 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
852 * successful so far. Do not call setTransactionSuccessful before calling this. When this
853 * returns a new transaction will have been created but not marked as successful.
854 * @return true if the transaction was yielded
855 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
856 * will not be yielded. Use yieldIfContendedSafely instead.
857 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700858 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700860 return yieldIfContendedHelper(false /* do not check yielding */,
861 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863
864 /**
865 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
866 * successful so far. Do not call setTransactionSuccessful before calling this. When this
867 * returns a new transaction will have been created but not marked as successful. This assumes
868 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700869 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 * @return true if the transaction was yielded
871 */
872 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700873 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
875
Fred Quintana5c7aede2009-08-27 21:41:27 -0700876 /**
877 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
878 * successful so far. Do not call setTransactionSuccessful before calling this. When this
879 * returns a new transaction will have been created but not marked as successful. This assumes
880 * that there are no nested transactions (beginTransaction has only been called once) and will
881 * throw an exception if that is not the case.
882 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
883 * the lock was actually yielded. This will allow other background threads to make some
884 * more progress than they would if we started the transaction immediately.
885 * @return true if the transaction was yielded
886 */
887 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
888 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
889 }
890
891 private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 if (mLock.getQueueLength() == 0) {
893 // Reset the lock acquire time since we know that the thread was willing to yield
894 // the lock at this time.
895 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
896 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
897 return false;
898 }
899 setTransactionSuccessful();
Fred Quintanac4516a72009-09-03 12:14:06 -0700900 SQLiteTransactionListener transactionListener = mTransactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 endTransaction();
902 if (checkFullyYielded) {
903 if (this.isDbLockedByCurrentThread()) {
904 throw new IllegalStateException(
905 "Db locked more than once. yielfIfContended cannot yield");
906 }
907 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700908 if (sleepAfterYieldDelay > 0) {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700909 // Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to
910 // check if anyone is using the database. If the database is not contended,
911 // retake the lock and return.
912 long remainingDelay = sleepAfterYieldDelay;
913 while (remainingDelay > 0) {
914 try {
915 Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ?
916 remainingDelay : SLEEP_AFTER_YIELD_QUANTUM);
917 } catch (InterruptedException e) {
918 Thread.interrupted();
919 }
920 remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM;
921 if (mLock.getQueueLength() == 0) {
922 break;
923 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700924 }
925 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700926 beginTransactionWithListener(transactionListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 return true;
928 }
929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 /**
Vasu Nori95675132010-07-21 16:24:40 -0700931 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 */
Vasu Nori95675132010-07-21 16:24:40 -0700933 @Deprecated
934 public Map<String, String> getSyncedTables() {
935 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937
938 /**
939 * Used to allow returning sub-classes of {@link Cursor} when calling query.
940 */
941 public interface CursorFactory {
942 /**
943 * See
Vasu Noribfe1dc22010-08-25 16:29:02 -0700944 * {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 */
946 public Cursor newCursor(SQLiteDatabase db,
947 SQLiteCursorDriver masterQuery, String editTable,
948 SQLiteQuery query);
949 }
950
951 /**
952 * Open the database according to the flags {@link #OPEN_READWRITE}
953 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
954 *
955 * <p>Sets the locale of the database to the the system's current locale.
956 * Call {@link #setLocale} if you would like something else.</p>
957 *
958 * @param path to database file to open and/or create
959 * @param factory an optional factory class that is called to instantiate a
960 * cursor when query is called, or null for default
961 * @param flags to control database access mode
962 * @return the newly opened database
963 * @throws SQLiteException if the database cannot be opened
964 */
965 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700966 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
967 }
968
969 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700970 * Open the database according to the flags {@link #OPEN_READWRITE}
971 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
972 *
973 * <p>Sets the locale of the database to the the system's current locale.
974 * Call {@link #setLocale} if you would like something else.</p>
975 *
976 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
977 * used to handle corruption when sqlite reports database corruption.</p>
978 *
979 * @param path to database file to open and/or create
980 * @param factory an optional factory class that is called to instantiate a
981 * cursor when query is called, or null for default
982 * @param flags to control database access mode
983 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
984 * when sqlite reports database corruption
985 * @return the newly opened database
986 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700987 */
988 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
989 DatabaseErrorHandler errorHandler) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700990 SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler,
991 (short) 0 /* the main connection handle */);
Vasu Noria8c24902010-06-01 11:30:27 -0700992
993 // set sqlite pagesize to mBlockSize
994 if (sBlockSize == 0) {
995 // TODO: "/data" should be a static final String constant somewhere. it is hardcoded
996 // in several places right now.
997 sBlockSize = new StatFs("/data").getBlockSize();
998 }
999 sqliteDatabase.setPageSize(sBlockSize);
Vasu Noria22d8842011-01-06 08:30:29 -08001000 sqliteDatabase.setJournalMode(path, "TRUNCATE");
Vasu Norif9e2bd02010-06-04 16:49:51 -07001001
Vasu Noriccd95442010-05-28 17:04:16 -07001002 // add this database to the list of databases opened in this process
Vasu Nori0732f792010-07-29 17:24:12 -07001003 synchronized(mActiveDatabases) {
1004 mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase));
1005 }
Vasu Noric3849202010-03-09 10:47:25 -08001006 return sqliteDatabase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008
Vasu Nori6c354da2010-04-26 23:33:39 -07001009 private static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
1010 DatabaseErrorHandler errorHandler, short connectionNum) {
1011 SQLiteDatabase db = new SQLiteDatabase(path, factory, flags, errorHandler, connectionNum);
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001012 try {
Vasu Norice38b982010-07-22 13:57:13 -07001013 if (Log.isLoggable(TAG, Log.DEBUG)) {
1014 Log.i(TAG, "opening the db : " + path);
1015 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001016 // Open the database.
1017 db.dbopen(path, flags);
1018 db.setLocale(Locale.getDefault());
1019 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
1020 db.enableSqlTracing(path, connectionNum);
1021 }
1022 if (SQLiteDebug.DEBUG_SQL_TIME) {
1023 db.enableSqlProfiling(path, connectionNum);
1024 }
1025 return db;
1026 } catch (SQLiteDatabaseCorruptException e) {
Vasu Nori6a904bc2011-01-05 18:35:40 -08001027 db.mErrorHandler.onCorruption(db);
1028 return SQLiteDatabase.openDatabase(path, factory, flags, errorHandler);
Vasu Nori6c354da2010-04-26 23:33:39 -07001029 } catch (SQLiteException e) {
1030 Log.e(TAG, "Failed to open the database. closing it.", e);
1031 db.close();
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001032 throw e;
1033 }
1034 }
1035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 /**
1037 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
1038 */
1039 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
1040 return openOrCreateDatabase(file.getPath(), factory);
1041 }
1042
1043 /**
1044 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
1045 */
1046 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
1047 return openDatabase(path, factory, CREATE_IF_NECESSARY);
1048 }
1049
1050 /**
Vasu Nori6c354da2010-04-26 23:33:39 -07001051 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001052 */
1053 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
1054 DatabaseErrorHandler errorHandler) {
1055 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
1056 }
1057
Vasu Noria98cb262010-06-22 13:16:35 -07001058 private void setJournalMode(final String dbPath, final String mode) {
1059 // journal mode can be set only for non-memory databases
Vasu Nori8fcda302010-11-08 13:46:40 -08001060 // AND can't be set for readonly databases
1061 if (dbPath.equalsIgnoreCase(MEMORY_DB_PATH) || isReadOnly()) {
1062 return;
1063 }
1064 String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null);
1065 if (!s.equalsIgnoreCase(mode)) {
1066 Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + dbPath +
1067 " (on pragma set journal_mode, sqlite returned:" + s);
Vasu Noria98cb262010-06-22 13:16:35 -07001068 }
1069 }
1070
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001071 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 * Create a memory backed SQLite database. Its contents will be destroyed
1073 * when the database is closed.
1074 *
1075 * <p>Sets the locale of the database to the the system's current locale.
1076 * Call {@link #setLocale} if you would like something else.</p>
1077 *
1078 * @param factory an optional factory class that is called to instantiate a
1079 * cursor when query is called
1080 * @return a SQLiteDatabase object, or null if the database can't be created
1081 */
1082 public static SQLiteDatabase create(CursorFactory factory) {
1083 // This is a magic string with special meaning for SQLite.
Vasu Noria98cb262010-06-22 13:16:35 -07001084 return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086
1087 /**
1088 * Close the database.
1089 */
1090 public void close() {
Vasu Nori587423a2010-09-27 18:18:34 -07001091 if (!isOpen()) {
1092 return;
1093 }
Vasu Norice38b982010-07-22 13:57:13 -07001094 if (Log.isLoggable(TAG, Log.DEBUG)) {
Vasu Nori75010102010-07-01 16:23:06 -07001095 Log.i(TAG, "closing db: " + mPath + " (connection # " + mConnectionNum);
1096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 lock();
1098 try {
Vasu Noriffe06122010-09-27 12:32:57 -07001099 // some other thread could have closed this database while I was waiting for lock.
1100 // check the database state
1101 if (!isOpen()) {
1102 return;
1103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 closeClosable();
Vasu Norifea6f6d2010-05-21 15:36:06 -07001105 // finalize ALL statements queued up so far
1106 closePendingStatements();
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001107 releaseCustomFunctions();
Vasu Norif6373e92010-03-16 10:21:00 -07001108 // close this database instance - regardless of its reference count value
Vasu Nori422dad02010-09-03 16:03:08 -07001109 closeDatabase();
Vasu Nori6c354da2010-04-26 23:33:39 -07001110 if (mConnectionPool != null) {
Vasu Norice38b982010-07-22 13:57:13 -07001111 if (Log.isLoggable(TAG, Log.DEBUG)) {
1112 assert mConnectionPool != null;
1113 Log.i(TAG, mConnectionPool.toString());
1114 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001115 mConnectionPool.close();
1116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 } finally {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001118 unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120 }
1121
1122 private void closeClosable() {
Vasu Noriccd95442010-05-28 17:04:16 -07001123 /* deallocate all compiled SQL statement objects from mCompiledQueries cache.
Vasu Norie495d1f2010-01-06 16:34:19 -08001124 * this should be done before de-referencing all {@link SQLiteClosable} objects
1125 * from this database object because calling
1126 * {@link SQLiteClosable#onAllReferencesReleasedFromContainer()} could cause the database
1127 * to be closed. sqlite doesn't let a database close if there are
1128 * any unfinalized statements - such as the compiled-sql objects in mCompiledQueries.
1129 */
Vasu Norib729dcc2010-09-14 11:35:49 -07001130 deallocCachedSqlStatements();
Vasu Norie495d1f2010-01-06 16:34:19 -08001131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1133 while (iter.hasNext()) {
1134 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1135 SQLiteClosable program = entry.getKey();
1136 if (program != null) {
1137 program.onAllReferencesReleasedFromContainer();
1138 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
Vasu Nori422dad02010-09-03 16:03:08 -07001143 * package level access for testing purposes
1144 */
1145 /* package */ void closeDatabase() throws SQLiteException {
1146 try {
1147 dbclose();
1148 } catch (SQLiteUnfinalizedObjectsException e) {
1149 String msg = e.getMessage();
1150 String[] tokens = msg.split(",", 2);
1151 int stmtId = Integer.parseInt(tokens[0]);
1152 // get extra info about this statement, if it is still to be released by closeClosable()
1153 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1154 boolean found = false;
1155 while (iter.hasNext()) {
1156 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1157 SQLiteClosable program = entry.getKey();
1158 if (program != null && program instanceof SQLiteProgram) {
Vasu Norib4389022010-11-29 14:10:46 -08001159 SQLiteCompiledSql compiledSql = ((SQLiteProgram)program).mCompiledSql;
1160 if (compiledSql.nStatement == stmtId) {
1161 msg = compiledSql.toString();
1162 found = true;
1163 }
Vasu Nori422dad02010-09-03 16:03:08 -07001164 }
1165 }
1166 if (!found) {
1167 // the statement is already released by closeClosable(). is it waiting to be
1168 // finalized?
1169 if (mClosedStatementIds.contains(stmtId)) {
1170 Log.w(TAG, "this shouldn't happen. finalizing the statement now: ");
1171 closePendingStatements();
1172 // try to close the database again
1173 closeDatabase();
1174 }
1175 } else {
1176 // the statement is not yet closed. most probably programming error in the app.
Vasu Norib4389022010-11-29 14:10:46 -08001177 throw new SQLiteUnfinalizedObjectsException(
1178 "close() on database: " + getPath() +
1179 " failed due to un-close()d SQL statements: " + msg);
Vasu Nori422dad02010-09-03 16:03:08 -07001180 }
1181 }
1182 }
1183
1184 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 * Native call to close the database.
1186 */
1187 private native void dbclose();
1188
1189 /**
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001190 * A callback interface for a custom sqlite3 function.
1191 * This can be used to create a function that can be called from
1192 * sqlite3 database triggers.
1193 * @hide
1194 */
1195 public interface CustomFunction {
1196 public void callback(String[] args);
1197 }
1198
1199 /**
1200 * Registers a CustomFunction callback as a function that can be called from
1201 * sqlite3 database triggers.
1202 * @param name the name of the sqlite3 function
1203 * @param numArgs the number of arguments for the function
1204 * @param function callback to call when the function is executed
1205 * @hide
1206 */
1207 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
1208 verifyDbIsOpen();
1209 synchronized (mCustomFunctions) {
1210 int ref = native_addCustomFunction(name, numArgs, function);
1211 if (ref != 0) {
1212 // save a reference to the function for cleanup later
1213 mCustomFunctions.add(new Integer(ref));
1214 } else {
1215 throw new SQLiteException("failed to add custom function " + name);
1216 }
1217 }
1218 }
1219
1220 private void releaseCustomFunctions() {
1221 synchronized (mCustomFunctions) {
1222 for (int i = 0; i < mCustomFunctions.size(); i++) {
1223 Integer function = mCustomFunctions.get(i);
1224 native_releaseCustomFunction(function.intValue());
1225 }
1226 mCustomFunctions.clear();
1227 }
1228 }
1229
1230 // list of CustomFunction references so we can clean up when the database closes
1231 private final ArrayList<Integer> mCustomFunctions =
1232 new ArrayList<Integer>();
1233
1234 private native int native_addCustomFunction(String name, int numArgs, CustomFunction function);
1235 private native void native_releaseCustomFunction(int function);
1236
1237 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 * Gets the database version.
1239 *
1240 * @return the database version
1241 */
1242 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -07001243 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
1245
1246 /**
1247 * Sets the database version.
1248 *
1249 * @param version the new database version
1250 */
1251 public void setVersion(int version) {
1252 execSQL("PRAGMA user_version = " + version);
1253 }
1254
1255 /**
1256 * Returns the maximum size the database may grow to.
1257 *
1258 * @return the new maximum database size
1259 */
1260 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001261 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
1262 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264
1265 /**
1266 * Sets the maximum size the database will grow to. The maximum size cannot
1267 * be set below the current size.
1268 *
1269 * @param numBytes the maximum database size, in bytes
1270 * @return the new maximum database size
1271 */
1272 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -07001273 long pageSize = getPageSize();
1274 long numPages = numBytes / pageSize;
1275 // If numBytes isn't a multiple of pageSize, bump up a page
1276 if ((numBytes % pageSize) != 0) {
1277 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -07001278 }
Vasu Noriccd95442010-05-28 17:04:16 -07001279 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
1280 null);
1281 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 }
1283
1284 /**
1285 * Returns the current database page size, in bytes.
1286 *
1287 * @return the database page size, in bytes
1288 */
1289 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001290 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292
1293 /**
1294 * Sets the database page size. The page size must be a power of two. This
1295 * method does not work if any data has been written to the database file,
1296 * and must be called right after the database has been created.
1297 *
1298 * @param numBytes the database page size, in bytes
1299 */
1300 public void setPageSize(long numBytes) {
1301 execSQL("PRAGMA page_size = " + numBytes);
1302 }
1303
1304 /**
1305 * Mark this table as syncable. When an update occurs in this table the
1306 * _sync_dirty field will be set to ensure proper syncing operation.
1307 *
1308 * @param table the table to mark as syncable
1309 * @param deletedTable The deleted table that corresponds to the
1310 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -07001311 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 */
Vasu Nori95675132010-07-21 16:24:40 -07001313 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316
1317 /**
1318 * Mark this table as syncable, with the _sync_dirty residing in another
1319 * table. When an update occurs in this table the _sync_dirty field of the
1320 * row in updateTable with the _id in foreignKey will be set to
1321 * ensure proper syncing operation.
1322 *
1323 * @param table an update on this table will trigger a sync time removal
1324 * @param foreignKey this is the column in table whose value is an _id in
1325 * updateTable
1326 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -07001327 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 */
Vasu Nori95675132010-07-21 16:24:40 -07001329 @Deprecated
1330 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 /**
1334 * Finds the name of the first table, which is editable.
1335 *
1336 * @param tables a list of tables
1337 * @return the first table listed
1338 */
1339 public static String findEditTable(String tables) {
1340 if (!TextUtils.isEmpty(tables)) {
1341 // find the first word terminated by either a space or a comma
1342 int spacepos = tables.indexOf(' ');
1343 int commapos = tables.indexOf(',');
1344
1345 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
1346 return tables.substring(0, spacepos);
1347 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
1348 return tables.substring(0, commapos);
1349 }
1350 return tables;
1351 } else {
1352 throw new IllegalStateException("Invalid tables");
1353 }
1354 }
1355
1356 /**
1357 * Compiles an SQL statement into a reusable pre-compiled statement object.
1358 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
1359 * statement and fill in those values with {@link SQLiteProgram#bindString}
1360 * and {@link SQLiteProgram#bindLong} each time you want to run the
1361 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -07001362 *<p>
1363 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 *
1365 * @param sql The raw SQL statement, may contain ? for unknown values to be
1366 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001367 * @return A pre-compiled {@link SQLiteStatement} object. Note that
1368 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 */
1370 public SQLiteStatement compileStatement(String sql) throws SQLException {
Vasu Noriccd95442010-05-28 17:04:16 -07001371 verifyDbIsOpen();
Vasu Nori0732f792010-07-29 17:24:12 -07001372 return new SQLiteStatement(this, sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
1375 /**
1376 * Query the given URL, returning a {@link Cursor} over the result set.
1377 *
1378 * @param distinct true if you want each row to be unique, false otherwise.
1379 * @param table The table name to compile the query against.
1380 * @param columns A list of which columns to return. Passing null will
1381 * return all columns, which is discouraged to prevent reading
1382 * data from storage that isn't going to be used.
1383 * @param selection A filter declaring which rows to return, formatted as an
1384 * SQL WHERE clause (excluding the WHERE itself). Passing null
1385 * will return all rows for the given table.
1386 * @param selectionArgs You may include ?s in selection, which will be
1387 * replaced by the values from selectionArgs, in order that they
1388 * appear in the selection. The values will be bound as Strings.
1389 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1390 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1391 * will cause the rows to not be grouped.
1392 * @param having A filter declare which row groups to include in the cursor,
1393 * if row grouping is being used, formatted as an SQL HAVING
1394 * clause (excluding the HAVING itself). Passing null will cause
1395 * all row groups to be included, and is required when row
1396 * grouping is not being used.
1397 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1398 * (excluding the ORDER BY itself). Passing null will use the
1399 * default sort order, which may be unordered.
1400 * @param limit Limits the number of rows returned by the query,
1401 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001402 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1403 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 * @see Cursor
1405 */
1406 public Cursor query(boolean distinct, String table, String[] columns,
1407 String selection, String[] selectionArgs, String groupBy,
1408 String having, String orderBy, String limit) {
1409 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
1410 groupBy, having, orderBy, limit);
1411 }
1412
1413 /**
1414 * Query the given URL, returning a {@link Cursor} over the result set.
1415 *
1416 * @param cursorFactory the cursor factory to use, or null for the default factory
1417 * @param distinct true if you want each row to be unique, false otherwise.
1418 * @param table The table name to compile the query against.
1419 * @param columns A list of which columns to return. Passing null will
1420 * return all columns, which is discouraged to prevent reading
1421 * data from storage that isn't going to be used.
1422 * @param selection A filter declaring which rows to return, formatted as an
1423 * SQL WHERE clause (excluding the WHERE itself). Passing null
1424 * will return all rows for the given table.
1425 * @param selectionArgs You may include ?s in selection, which will be
1426 * replaced by the values from selectionArgs, in order that they
1427 * appear in the selection. The values will be bound as Strings.
1428 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1429 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1430 * will cause the rows to not be grouped.
1431 * @param having A filter declare which row groups to include in the cursor,
1432 * if row grouping is being used, formatted as an SQL HAVING
1433 * clause (excluding the HAVING itself). Passing null will cause
1434 * all row groups to be included, and is required when row
1435 * grouping is not being used.
1436 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1437 * (excluding the ORDER BY itself). Passing null will use the
1438 * default sort order, which may be unordered.
1439 * @param limit Limits the number of rows returned by the query,
1440 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001441 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1442 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 * @see Cursor
1444 */
1445 public Cursor queryWithFactory(CursorFactory cursorFactory,
1446 boolean distinct, String table, String[] columns,
1447 String selection, String[] selectionArgs, String groupBy,
1448 String having, String orderBy, String limit) {
Vasu Noriccd95442010-05-28 17:04:16 -07001449 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 String sql = SQLiteQueryBuilder.buildQueryString(
1451 distinct, table, columns, selection, groupBy, having, orderBy, limit);
1452
1453 return rawQueryWithFactory(
1454 cursorFactory, sql, selectionArgs, findEditTable(table));
1455 }
1456
1457 /**
1458 * Query the given table, returning a {@link Cursor} over the result set.
1459 *
1460 * @param table The table name to compile the query against.
1461 * @param columns A list of which columns to return. Passing null will
1462 * return all columns, which is discouraged to prevent reading
1463 * data from storage that isn't going to be used.
1464 * @param selection A filter declaring which rows to return, formatted as an
1465 * SQL WHERE clause (excluding the WHERE itself). Passing null
1466 * will return all rows for the given table.
1467 * @param selectionArgs You may include ?s in selection, which will be
1468 * replaced by the values from selectionArgs, in order that they
1469 * appear in the selection. The values will be bound as Strings.
1470 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1471 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1472 * will cause the rows to not be grouped.
1473 * @param having A filter declare which row groups to include in the cursor,
1474 * if row grouping is being used, formatted as an SQL HAVING
1475 * clause (excluding the HAVING itself). Passing null will cause
1476 * all row groups to be included, and is required when row
1477 * grouping is not being used.
1478 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1479 * (excluding the ORDER BY itself). Passing null will use the
1480 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001481 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1482 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 * @see Cursor
1484 */
1485 public Cursor query(String table, String[] columns, String selection,
1486 String[] selectionArgs, String groupBy, String having,
1487 String orderBy) {
1488
1489 return query(false, table, columns, selection, selectionArgs, groupBy,
1490 having, orderBy, null /* limit */);
1491 }
1492
1493 /**
1494 * Query the given table, returning a {@link Cursor} over the result set.
1495 *
1496 * @param table The table name to compile the query against.
1497 * @param columns A list of which columns to return. Passing null will
1498 * return all columns, which is discouraged to prevent reading
1499 * data from storage that isn't going to be used.
1500 * @param selection A filter declaring which rows to return, formatted as an
1501 * SQL WHERE clause (excluding the WHERE itself). Passing null
1502 * will return all rows for the given table.
1503 * @param selectionArgs You may include ?s in selection, which will be
1504 * replaced by the values from selectionArgs, in order that they
1505 * appear in the selection. The values will be bound as Strings.
1506 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1507 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1508 * will cause the rows to not be grouped.
1509 * @param having A filter declare which row groups to include in the cursor,
1510 * if row grouping is being used, formatted as an SQL HAVING
1511 * clause (excluding the HAVING itself). Passing null will cause
1512 * all row groups to be included, and is required when row
1513 * grouping is not being used.
1514 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1515 * (excluding the ORDER BY itself). Passing null will use the
1516 * default sort order, which may be unordered.
1517 * @param limit Limits the number of rows returned by the query,
1518 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001519 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1520 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 * @see Cursor
1522 */
1523 public Cursor query(String table, String[] columns, String selection,
1524 String[] selectionArgs, String groupBy, String having,
1525 String orderBy, String limit) {
1526
1527 return query(false, table, columns, selection, selectionArgs, groupBy,
1528 having, orderBy, limit);
1529 }
1530
1531 /**
1532 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1533 *
1534 * @param sql the SQL query. The SQL string must not be ; terminated
1535 * @param selectionArgs You may include ?s in where clause in the query,
1536 * which will be replaced by the values from selectionArgs. The
1537 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001538 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1539 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 */
1541 public Cursor rawQuery(String sql, String[] selectionArgs) {
1542 return rawQueryWithFactory(null, sql, selectionArgs, null);
1543 }
1544
1545 /**
1546 * Runs the provided SQL and returns a cursor over the result set.
1547 *
1548 * @param cursorFactory the cursor factory to use, or null for the default factory
1549 * @param sql the SQL query. The SQL string must not be ; terminated
1550 * @param selectionArgs You may include ?s in where clause in the query,
1551 * which will be replaced by the values from selectionArgs. The
1552 * values will be bound as Strings.
1553 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001554 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1555 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 */
1557 public Cursor rawQueryWithFactory(
1558 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1559 String editTable) {
Vasu Noriccd95442010-05-28 17:04:16 -07001560 verifyDbIsOpen();
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -07001561 BlockGuard.getThreadPolicy().onReadFromDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 long timeStart = 0;
1563
Joe Onorato43a17652011-04-06 19:22:23 -07001564 if (false || mSlowQueryThreshold != -1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 timeStart = System.currentTimeMillis();
1566 }
1567
Vasu Nori6c354da2010-04-26 23:33:39 -07001568 SQLiteDatabase db = getDbConnection(sql);
1569 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001571 Cursor cursor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 try {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001573 cursor = driver.query(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 cursorFactory != null ? cursorFactory : mFactory,
1575 selectionArgs);
1576 } finally {
Joe Onorato43a17652011-04-06 19:22:23 -07001577 if (false || mSlowQueryThreshold != -1) {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001578
Vasu Nori020e5342010-04-28 14:22:38 -07001579 // Force query execution
1580 int count = -1;
1581 if (cursor != null) {
1582 count = cursor.getCount();
1583 }
1584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 long duration = System.currentTimeMillis() - timeStart;
1586
Joe Onorato43a17652011-04-06 19:22:23 -07001587 if (false || duration >= mSlowQueryThreshold) {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001588 Log.v(SQLiteCursor.TAG,
1589 "query (" + duration + " ms): " + driver.toString() + ", args are "
1590 + (selectionArgs != null
1591 ? TextUtils.join(",", selectionArgs)
Vasu Nori020e5342010-04-28 14:22:38 -07001592 : "<null>") + ", count is " + count);
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001595 releaseDbConnection(db);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001597 return cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599
1600 /**
1601 * Runs the provided SQL and returns a cursor over the result set.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001602 * The cursor will read an initial set of rows and the return to the caller.
1603 * It will continue to read in batches and send data changed notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 * when the later batches are ready.
1605 * @param sql the SQL query. The SQL string must not be ; terminated
1606 * @param selectionArgs You may include ?s in where clause in the query,
1607 * which will be replaced by the values from selectionArgs. The
1608 * values will be bound as Strings.
1609 * @param initialRead set the initial count of items to read from the cursor
1610 * @param maxRead set the count of items to read on each iteration after the first
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001611 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1612 * {@link Cursor}s are not synchronized, see the documentation for more details.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001613 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001614 * This work is incomplete and not fully tested or reviewed, so currently
1615 * hidden.
1616 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001618 public Cursor rawQuery(String sql, String[] selectionArgs,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 int initialRead, int maxRead) {
1620 SQLiteCursor c = (SQLiteCursor)rawQueryWithFactory(
1621 null, sql, selectionArgs, null);
1622 c.setLoadStyle(initialRead, maxRead);
1623 return c;
1624 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 /**
1627 * Convenience method for inserting a row into the database.
1628 *
1629 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001630 * @param nullColumnHack optional; may be <code>null</code>.
1631 * SQL doesn't allow inserting a completely empty row without
1632 * naming at least one column name. If your provided <code>values</code> is
1633 * empty, no column names are known and an empty row can't be inserted.
1634 * If not set to null, the <code>nullColumnHack</code> parameter
1635 * provides the name of nullable column name to explicitly insert a NULL into
1636 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 * @param values this map contains the initial column values for the
1638 * row. The keys should be the column names and the values the
1639 * column values
1640 * @return the row ID of the newly inserted row, or -1 if an error occurred
1641 */
1642 public long insert(String table, String nullColumnHack, ContentValues values) {
1643 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001644 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 } catch (SQLException e) {
1646 Log.e(TAG, "Error inserting " + values, e);
1647 return -1;
1648 }
1649 }
1650
1651 /**
1652 * Convenience method for inserting a row into the database.
1653 *
1654 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001655 * @param nullColumnHack optional; may be <code>null</code>.
1656 * SQL doesn't allow inserting a completely empty row without
1657 * naming at least one column name. If your provided <code>values</code> is
1658 * empty, no column names are known and an empty row can't be inserted.
1659 * If not set to null, the <code>nullColumnHack</code> parameter
1660 * provides the name of nullable column name to explicitly insert a NULL into
1661 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 * @param values this map contains the initial column values for the
1663 * row. The keys should be the column names and the values the
1664 * column values
1665 * @throws SQLException
1666 * @return the row ID of the newly inserted row, or -1 if an error occurred
1667 */
1668 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1669 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001670 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672
1673 /**
1674 * Convenience method for replacing a row in the database.
1675 *
1676 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001677 * @param nullColumnHack optional; may be <code>null</code>.
1678 * SQL doesn't allow inserting a completely empty row without
1679 * naming at least one column name. If your provided <code>initialValues</code> is
1680 * empty, no column names are known and an empty row can't be inserted.
1681 * If not set to null, the <code>nullColumnHack</code> parameter
1682 * provides the name of nullable column name to explicitly insert a NULL into
1683 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001685 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 * @return the row ID of the newly inserted row, or -1 if an error occurred
1687 */
1688 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1689 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001690 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001691 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 } catch (SQLException e) {
1693 Log.e(TAG, "Error inserting " + initialValues, e);
1694 return -1;
1695 }
1696 }
1697
1698 /**
1699 * Convenience method for replacing a row in the database.
1700 *
1701 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001702 * @param nullColumnHack optional; may be <code>null</code>.
1703 * SQL doesn't allow inserting a completely empty row without
1704 * naming at least one column name. If your provided <code>initialValues</code> is
1705 * empty, no column names are known and an empty row can't be inserted.
1706 * If not set to null, the <code>nullColumnHack</code> parameter
1707 * provides the name of nullable column name to explicitly insert a NULL into
1708 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 * @param initialValues this map contains the initial column values for
1710 * the row. The key
1711 * @throws SQLException
1712 * @return the row ID of the newly inserted row, or -1 if an error occurred
1713 */
1714 public long replaceOrThrow(String table, String nullColumnHack,
1715 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001716 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001717 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719
1720 /**
1721 * General method for inserting a row into the database.
1722 *
1723 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001724 * @param nullColumnHack optional; may be <code>null</code>.
1725 * SQL doesn't allow inserting a completely empty row without
1726 * naming at least one column name. If your provided <code>initialValues</code> is
1727 * empty, no column names are known and an empty row can't be inserted.
1728 * If not set to null, the <code>nullColumnHack</code> parameter
1729 * provides the name of nullable column name to explicitly insert a NULL into
1730 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 * @param initialValues this map contains the initial column values for the
1732 * row. The keys should be the column names and the values the
1733 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001734 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001735 * @return the row ID of the newly inserted row
1736 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001737 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001738 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 */
1740 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001741 ContentValues initialValues, int conflictAlgorithm) {
Vasu Nori0732f792010-07-29 17:24:12 -07001742 StringBuilder sql = new StringBuilder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001744 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 sql.append(" INTO ");
1746 sql.append(table);
Vasu Nori0732f792010-07-29 17:24:12 -07001747 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748
Vasu Nori0732f792010-07-29 17:24:12 -07001749 Object[] bindArgs = null;
1750 int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
1751 if (size > 0) {
1752 bindArgs = new Object[size];
1753 int i = 0;
1754 for (String colName : initialValues.keySet()) {
1755 sql.append((i > 0) ? "," : "");
1756 sql.append(colName);
1757 bindArgs[i++] = initialValues.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 sql.append(')');
Vasu Nori0732f792010-07-29 17:24:12 -07001760 sql.append(" VALUES (");
1761 for (i = 0; i < size; i++) {
1762 sql.append((i > 0) ? ",?" : "?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 }
Vasu Nori0732f792010-07-29 17:24:12 -07001764 } else {
1765 sql.append(nullColumnHack + ") VALUES (NULL");
1766 }
1767 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768
Vasu Nori0732f792010-07-29 17:24:12 -07001769 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1770 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001771 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 } catch (SQLiteDatabaseCorruptException e) {
1773 onCorruption();
1774 throw e;
1775 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001776 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
1778 }
1779
1780 /**
1781 * Convenience method for deleting rows in the database.
1782 *
1783 * @param table the table to delete from
1784 * @param whereClause the optional WHERE clause to apply when deleting.
1785 * Passing null will delete all rows.
1786 * @return the number of rows affected if a whereClause is passed in, 0
1787 * otherwise. To remove all rows and get a count pass "1" as the
1788 * whereClause.
1789 */
1790 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Nori0732f792010-07-29 17:24:12 -07001791 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1792 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001794 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 } catch (SQLiteDatabaseCorruptException e) {
1796 onCorruption();
1797 throw e;
1798 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001799 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
1801 }
1802
1803 /**
1804 * Convenience method for updating rows in the database.
1805 *
1806 * @param table the table to update in
1807 * @param values a map from column names to new column values. null is a
1808 * valid value that will be translated to NULL.
1809 * @param whereClause the optional WHERE clause to apply when updating.
1810 * Passing null will update all rows.
1811 * @return the number of rows affected
1812 */
1813 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001814 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 /**
1818 * Convenience method for updating rows in the database.
1819 *
1820 * @param table the table to update in
1821 * @param values a map from column names to new column values. null is a
1822 * valid value that will be translated to NULL.
1823 * @param whereClause the optional WHERE clause to apply when updating.
1824 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001825 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001828 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001829 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001830 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 throw new IllegalArgumentException("Empty values");
1832 }
1833
1834 StringBuilder sql = new StringBuilder(120);
1835 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001836 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 sql.append(table);
1838 sql.append(" SET ");
1839
Vasu Nori0732f792010-07-29 17:24:12 -07001840 // move all bind args to one array
Brian Muramatsu46a88512010-11-12 13:53:57 -08001841 int setValuesSize = values.size();
Vasu Nori0732f792010-07-29 17:24:12 -07001842 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1843 Object[] bindArgs = new Object[bindArgsSize];
1844 int i = 0;
1845 for (String colName : values.keySet()) {
1846 sql.append((i > 0) ? "," : "");
1847 sql.append(colName);
1848 bindArgs[i++] = values.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 sql.append("=?");
Vasu Nori0732f792010-07-29 17:24:12 -07001850 }
1851 if (whereArgs != null) {
1852 for (i = setValuesSize; i < bindArgsSize; i++) {
1853 bindArgs[i] = whereArgs[i - setValuesSize];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
1855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (!TextUtils.isEmpty(whereClause)) {
1857 sql.append(" WHERE ");
1858 sql.append(whereClause);
1859 }
1860
Vasu Nori0732f792010-07-29 17:24:12 -07001861 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001863 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 } catch (SQLiteDatabaseCorruptException e) {
1865 onCorruption();
1866 throw e;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001868 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
1870 }
1871
1872 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001873 * Execute a single SQL statement that is NOT a SELECT
1874 * or any other SQL statement that returns data.
1875 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001876 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001877 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1878 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1879 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001880 * <p>
1881 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1882 * automatically managed by this class. So, do not set journal_mode
1883 * using "PRAGMA journal_mode'<value>" statement if your app is using
1884 * {@link #enableWriteAheadLogging()}
1885 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 *
Vasu Noriccd95442010-05-28 17:04:16 -07001887 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1888 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001889 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001891 public void execSQL(String sql) throws SQLException {
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 Noricc1eaf62011-03-14 19:22:16 -07001946 if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
1947 disableWriteAheadLogging();
1948 mHasAttachedDbs = true;
1949 }
Vasu Nori0732f792010-07-29 17:24:12 -07001950 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 try {
Vasu Nori16057fa2011-03-18 11:40:37 -07001952 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 } catch (SQLiteDatabaseCorruptException e) {
1954 onCorruption();
1955 throw e;
1956 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001957 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
1960
1961 @Override
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001962 protected void finalize() throws Throwable {
1963 try {
1964 if (isOpen()) {
1965 Log.e(TAG, "close() was never explicitly called on database '" +
1966 mPath + "' ", mStackTrace);
1967 closeClosable();
1968 onAllReferencesReleased();
1969 releaseCustomFunctions();
1970 }
1971 } finally {
1972 super.finalize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974 }
1975
1976 /**
Vasu Nori21343692010-06-03 16:01:39 -07001977 * Private constructor.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 *
1979 * @param path The full path to the database
1980 * @param factory The factory to use when creating cursors, may be NULL.
1981 * @param flags 0 or {@link #NO_LOCALIZED_COLLATORS}. If the database file already
1982 * exists, mFlags will be updated appropriately.
Vasu Nori21343692010-06-03 16:01:39 -07001983 * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite reports database
1984 * corruption. may be NULL.
Vasu Nori6c354da2010-04-26 23:33:39 -07001985 * @param connectionNum 0 for main database connection handle. 1..N for pooled database
1986 * connection handles.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 */
Vasu Nori21343692010-06-03 16:01:39 -07001988 private SQLiteDatabase(String path, CursorFactory factory, int flags,
Vasu Nori6c354da2010-04-26 23:33:39 -07001989 DatabaseErrorHandler errorHandler, short connectionNum) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if (path == null) {
1991 throw new IllegalArgumentException("path should not be null");
1992 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001993 setMaxSqlCacheSize(DEFAULT_SQL_CACHE_SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mFlags = flags;
1995 mPath = path;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001996 mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1);
Vasu Nori08b448e2010-03-03 10:05:16 -08001997 mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 mFactory = factory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 mPrograms = new WeakHashMap<SQLiteClosable,Object>();
Vasu Nori21343692010-06-03 16:01:39 -07002000 // Set the DatabaseErrorHandler to be used when SQLite reports corruption.
2001 // If the caller sets errorHandler = null, then use default errorhandler.
2002 mErrorHandler = (errorHandler == null) ? new DefaultDatabaseErrorHandler() : errorHandler;
Vasu Nori6c354da2010-04-26 23:33:39 -07002003 mConnectionNum = connectionNum;
Vasu Nori34ad57f02010-12-21 09:32:36 -08002004 /* sqlite soft heap limit http://www.sqlite.org/c3ref/soft_heap_limit64.html
2005 * set it to 4 times the default cursor window size.
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002006 * TODO what is an appropriate value, considering the WAL feature which could burn
Vasu Nori34ad57f02010-12-21 09:32:36 -08002007 * a lot of memory with many connections to the database. needs testing to figure out
2008 * optimal value for this.
2009 */
2010 int limit = Resources.getSystem().getInteger(
2011 com.android.internal.R.integer.config_cursorWindowSize) * 1024 * 4;
2012 native_setSqliteSoftHeapLimit(limit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
2015 /**
2016 * return whether the DB is opened as read only.
2017 * @return true if DB is opened as read only
2018 */
2019 public boolean isReadOnly() {
2020 return (mFlags & OPEN_READ_MASK) == OPEN_READONLY;
2021 }
2022
2023 /**
2024 * @return true if the DB is currently open (has not been closed)
2025 */
2026 public boolean isOpen() {
2027 return mNativeHandle != 0;
2028 }
2029
2030 public boolean needUpgrade(int newVersion) {
2031 return newVersion > getVersion();
2032 }
2033
2034 /**
2035 * Getter for the path to the database file.
2036 *
2037 * @return the path to our database file.
2038 */
2039 public final String getPath() {
2040 return mPath;
2041 }
2042
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002043 /* package */ void logTimeStat(String sql, long beginMillis) {
Christopher Tatead9e8b12011-10-05 17:49:26 -07002044 if (ENABLE_DB_SAMPLE) {
2045 logTimeStat(sql, beginMillis, null);
2046 }
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002047 }
2048
Vasu Nori16057fa2011-03-18 11:40:37 -07002049 private void logTimeStat(String sql, long beginMillis, String prefix) {
Dan Egnor12311952009-11-23 14:47:45 -08002050 // Sample fast queries in proportion to the time taken.
2051 // Quantize the % first, so the logged sampling probability
2052 // exactly equals the actual sampling rate for this query.
2053
2054 int samplePercent;
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002055 long durationMillis = SystemClock.uptimeMillis() - beginMillis;
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002056 if (durationMillis == 0 && prefix == GET_LOCK_LOG_PREFIX) {
2057 // The common case is locks being uncontended. Don't log those,
2058 // even at 1%, which is our default below.
2059 return;
2060 }
2061 if (sQueryLogTimeInMillis == 0) {
2062 sQueryLogTimeInMillis = SystemProperties.getInt("db.db_operation.threshold_ms", 500);
2063 }
2064 if (durationMillis >= sQueryLogTimeInMillis) {
Dan Egnor12311952009-11-23 14:47:45 -08002065 samplePercent = 100;
Vasu Norifb16cbd2010-07-25 16:38:48 -07002066 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002067 samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1;
Dan Egnor799f7212009-11-24 16:24:44 -08002068 if (mRandom.nextInt(100) >= samplePercent) return;
Dan Egnor12311952009-11-23 14:47:45 -08002069 }
2070
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002071 // Note: the prefix will be "COMMIT;" or "GETLOCK:" when non-null. We wait to do
2072 // it here so we avoid allocating in the common case.
2073 if (prefix != null) {
2074 sql = prefix + sql;
2075 }
Dan Egnor12311952009-11-23 14:47:45 -08002076 if (sql.length() > QUERY_LOG_SQL_LENGTH) sql = sql.substring(0, QUERY_LOG_SQL_LENGTH);
2077
2078 // ActivityThread.currentPackageName() only returns non-null if the
2079 // current thread is an application main thread. This parameter tells
2080 // us whether an event loop is blocked, and if so, which app it is.
2081 //
2082 // Sadly, there's no fast way to determine app name if this is *not* a
2083 // main thread, or when we are invoked via Binder (e.g. ContentProvider).
2084 // Hopefully the full path to the database will be informative enough.
2085
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002086 String blockingPackage = AppGlobals.getInitialPackage();
Dan Egnor12311952009-11-23 14:47:45 -08002087 if (blockingPackage == null) blockingPackage = "";
2088
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002089 EventLog.writeEvent(
Brad Fitzpatrickd8330232010-02-19 10:59:01 -08002090 EVENT_DB_OPERATION,
2091 getPathForLogs(),
2092 sql,
2093 durationMillis,
2094 blockingPackage,
2095 samplePercent);
2096 }
2097
2098 /**
2099 * Removes email addresses from database filenames before they're
2100 * logged to the EventLog where otherwise apps could potentially
2101 * read them.
2102 */
2103 private String getPathForLogs() {
2104 if (mPathForLogs != null) {
2105 return mPathForLogs;
2106 }
2107 if (mPath == null) {
2108 return null;
2109 }
2110 if (mPath.indexOf('@') == -1) {
2111 mPathForLogs = mPath;
2112 } else {
2113 mPathForLogs = EMAIL_IN_DB_PATTERN.matcher(mPath).replaceAll("XX@YY");
2114 }
2115 return mPathForLogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 }
2117
2118 /**
2119 * Sets the locale for this database. Does nothing if this database has
2120 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
2121 * @throws SQLException if the locale could not be set. The most common reason
2122 * for this is that there is no collator available for the locale you requested.
2123 * In this case the database remains unchanged.
2124 */
2125 public void setLocale(Locale locale) {
2126 lock();
2127 try {
2128 native_setLocale(locale.toString(), mFlags);
2129 } finally {
2130 unlock();
2131 }
2132 }
2133
Vasu Noriccd95442010-05-28 17:04:16 -07002134 /* package */ void verifyDbIsOpen() {
Vasu Nori9463f292010-04-30 12:22:18 -07002135 if (!isOpen()) {
Vasu Nori75010102010-07-01 16:23:06 -07002136 throw new IllegalStateException("database " + getPath() + " (conn# " +
2137 mConnectionNum + ") already closed");
Vasu Nori9463f292010-04-30 12:22:18 -07002138 }
Vasu Noriccd95442010-05-28 17:04:16 -07002139 }
2140
2141 /* package */ void verifyLockOwner() {
2142 verifyDbIsOpen();
2143 if (mLockingEnabled && !isDbLockedByCurrentThread()) {
Vasu Nori9463f292010-04-30 12:22:18 -07002144 throw new IllegalStateException("Don't have database lock!");
2145 }
2146 }
2147
Vasu Norib729dcc2010-09-14 11:35:49 -07002148 /**
2149 * Adds the given SQL and its compiled-statement-id-returned-by-sqlite to the
2150 * cache of compiledQueries attached to 'this'.
2151 * <p>
2152 * If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL,
2153 * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current
2154 * mapping is NOT replaced with the new mapping).
2155 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002156 /* package */ synchronized void addToCompiledQueries(
2157 String sql, SQLiteCompiledSql compiledStatement) {
2158 // don't insert the new mapping if a mapping already exists
2159 if (mCompiledQueries.get(sql) != null) {
2160 return;
2161 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002162
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002163 int maxCacheSz = (mConnectionNum == 0) ? mCompiledQueries.maxSize() :
2164 mParentConnObj.mCompiledQueries.maxSize();
Brian Muramatsu46a88512010-11-12 13:53:57 -08002165
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002166 if (SQLiteDebug.DEBUG_SQL_CACHE) {
2167 boolean printWarning = (mConnectionNum == 0)
2168 ? (!mCacheFullWarning && mCompiledQueries.size() == maxCacheSz)
2169 : (!mParentConnObj.mCacheFullWarning &&
2170 mParentConnObj.mCompiledQueries.size() == maxCacheSz);
2171 if (printWarning) {
2172 /*
2173 * cache size is not enough for this app. log a warning.
2174 * chances are it is NOT using ? for bindargs - or cachesize is too small.
2175 */
2176 Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
2177 getPath() + ". Use setMaxSqlCacheSize() to increase cachesize. ");
2178 mCacheFullWarning = true;
2179 Log.d(TAG, "Here are the SQL statements in Cache of database: " + mPath);
2180 for (String s : mCompiledQueries.snapshot().keySet()) {
2181 Log.d(TAG, "Sql statement in Cache: " + s);
Vasu Nori74fb2682010-10-25 11:48:24 -07002182 }
Vasu Nori7301a232010-11-05 11:46:15 -07002183 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002184 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002185 /* add the given SQLiteCompiledSql compiledStatement to cache.
2186 * no need to worry about the cache size - because {@link #mCompiledQueries}
2187 * self-limits its size.
2188 */
2189 mCompiledQueries.put(sql, compiledStatement);
Vasu Norib729dcc2010-09-14 11:35:49 -07002190 }
2191
2192 /** package-level access for testing purposes */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002193 /* package */ synchronized void deallocCachedSqlStatements() {
2194 for (SQLiteCompiledSql compiledSql : mCompiledQueries.snapshot().values()) {
2195 compiledSql.releaseSqlStatement();
Vasu Norib729dcc2010-09-14 11:35:49 -07002196 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002197 mCompiledQueries.evictAll();
Vasu Norib729dcc2010-09-14 11:35:49 -07002198 }
2199
2200 /**
2201 * From the compiledQueries cache, returns the compiled-statement-id for the given SQL.
2202 * Returns null, if not found in the cache.
2203 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002204 /* package */ synchronized SQLiteCompiledSql getCompiledStatementForSql(String sql) {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002205 return mCompiledQueries.get(sql);
Vasu Norib729dcc2010-09-14 11:35:49 -07002206 }
2207
Vasu Norie495d1f2010-01-06 16:34:19 -08002208 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002209 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08002210 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07002211 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07002212 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07002213 * If this method is called with smaller size than the current maximum value,
2214 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07002215 *<p>
2216 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08002217 *
Vasu Nori90a367262010-04-12 12:49:09 -07002218 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
2219 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or
Vasu Noribfe1dc22010-08-25 16:29:02 -07002220 * the value set with previous setMaxSqlCacheSize() call.
Vasu Norie495d1f2010-01-06 16:34:19 -08002221 */
Vasu Nori54025902010-09-14 12:14:26 -07002222 public void setMaxSqlCacheSize(int cacheSize) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002223 synchronized (this) {
2224 LruCache<String, SQLiteCompiledSql> oldCompiledQueries = mCompiledQueries;
Vasu Nori54025902010-09-14 12:14:26 -07002225 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002226 throw new IllegalStateException(
2227 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
2228 } else if (oldCompiledQueries != null && cacheSize < oldCompiledQueries.maxSize()) {
2229 throw new IllegalStateException("cannot set cacheSize to a value less than the "
2230 + "value set with previous setMaxSqlCacheSize() call.");
Vasu Nori54025902010-09-14 12:14:26 -07002231 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002232 mCompiledQueries = new LruCache<String, SQLiteCompiledSql>(cacheSize) {
2233 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08002234 protected void entryRemoved(boolean evicted, String key, SQLiteCompiledSql oldValue,
2235 SQLiteCompiledSql newValue) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002236 verifyLockOwner();
Jesse Wilson32c80a22011-02-25 17:28:41 -08002237 oldValue.releaseIfNotInUse();
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002238 }
2239 };
2240 if (oldCompiledQueries != null) {
2241 for (Map.Entry<String, SQLiteCompiledSql> entry
2242 : oldCompiledQueries.snapshot().entrySet()) {
2243 mCompiledQueries.put(entry.getKey(), entry.getValue());
2244 }
Vasu Nori24675612010-09-27 14:54:19 -07002245 }
Vasu Nori587423a2010-09-27 18:18:34 -07002246 }
2247 }
2248
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002249 /* package */ synchronized boolean isInStatementCache(String sql) {
2250 return mCompiledQueries.get(sql) != null;
2251 }
2252
2253 /* package */ synchronized void releaseCompiledSqlObj(
2254 String sql, SQLiteCompiledSql compiledSql) {
2255 if (mCompiledQueries.get(sql) == compiledSql) {
2256 // it is in cache - reset its inUse flag
2257 compiledSql.release();
2258 } else {
2259 // it is NOT in cache. finalize it.
2260 compiledSql.releaseSqlStatement();
2261 }
2262 }
2263
2264 private synchronized int getCacheHitNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002265 return mCompiledQueries.hitCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002266 }
2267
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002268 private synchronized int getCacheMissNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002269 return mCompiledQueries.missCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002270 }
2271
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002272 private synchronized int getCachesize() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002273 return mCompiledQueries.size();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002274 }
2275
Vasu Nori6f37f832010-05-19 11:53:25 -07002276 /* package */ void finalizeStatementLater(int id) {
2277 if (!isOpen()) {
2278 // database already closed. this statement will already have been finalized.
2279 return;
2280 }
2281 synchronized(mClosedStatementIds) {
2282 if (mClosedStatementIds.contains(id)) {
2283 // this statement id is already queued up for finalization.
2284 return;
2285 }
2286 mClosedStatementIds.add(id);
2287 }
2288 }
2289
Vasu Nori83ff97d2011-01-30 12:47:55 -08002290 /* package */ boolean isInQueueOfStatementsToBeFinalized(int id) {
2291 if (!isOpen()) {
2292 // database already closed. this statement will already have been finalized.
2293 // return true so that the caller doesn't have to worry about finalizing this statement.
2294 return true;
2295 }
2296 synchronized(mClosedStatementIds) {
2297 return mClosedStatementIds.contains(id);
2298 }
2299 }
2300
Vasu Norice38b982010-07-22 13:57:13 -07002301 /* package */ void closePendingStatements() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002302 if (!isOpen()) {
2303 // since this database is already closed, no need to finalize anything.
2304 mClosedStatementIds.clear();
2305 return;
2306 }
2307 verifyLockOwner();
2308 /* to minimize synchronization on mClosedStatementIds, make a copy of the list */
2309 ArrayList<Integer> list = new ArrayList<Integer>(mClosedStatementIds.size());
2310 synchronized(mClosedStatementIds) {
2311 list.addAll(mClosedStatementIds);
2312 mClosedStatementIds.clear();
2313 }
2314 // finalize all the statements from the copied list
2315 int size = list.size();
2316 for (int i = 0; i < size; i++) {
2317 native_finalize(list.get(i));
2318 }
2319 }
2320
2321 /**
2322 * for testing only
Vasu Nori6f37f832010-05-19 11:53:25 -07002323 */
Vasu Norice38b982010-07-22 13:57:13 -07002324 /* package */ ArrayList<Integer> getQueuedUpStmtList() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002325 return mClosedStatementIds;
2326 }
2327
Vasu Nori6c354da2010-04-26 23:33:39 -07002328 /**
2329 * This method enables parallel execution of queries from multiple threads on the same database.
2330 * It does this by opening multiple handles to the database and using a different
2331 * database handle for each query.
2332 * <p>
2333 * If a transaction is in progress on one connection handle and say, a table is updated in the
2334 * transaction, then query on the same table on another connection handle will block for the
2335 * transaction to complete. But this method enables such queries to execute by having them
2336 * return old version of the data from the table. Most often it is the data that existed in the
2337 * table prior to the above transaction updates on that table.
2338 * <p>
2339 * Maximum number of simultaneous handles used to execute queries in parallel is
2340 * dependent upon the device memory and possibly other properties.
2341 * <p>
2342 * After calling this method, execution of queries in parallel is enabled as long as this
2343 * database handle is open. To disable execution of queries in parallel, database should
2344 * be closed and reopened.
2345 * <p>
2346 * If a query is part of a transaction, then it is executed on the same database handle the
2347 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07002348 * <p>
2349 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07002350 * possible. In such cases, a message is printed to logcat and false is returned.
2351 * <p>
2352 * This feature is not available for :memory: databases. In such cases,
2353 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07002354 * <p>
2355 * A typical way to use this method is the following:
2356 * <pre>
2357 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
2358 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
2359 * db.enableWriteAheadLogging();
2360 * </pre>
2361 * <p>
2362 * Writers should use {@link #beginTransactionNonExclusive()} or
2363 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
2364 * to start a trsnsaction.
2365 * Non-exclusive mode allows database file to be in readable by threads executing queries.
2366 * </p>
2367 *
Vasu Noria98cb262010-06-22 13:16:35 -07002368 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07002369 */
Vasu Noriffe06122010-09-27 12:32:57 -07002370 public boolean enableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002371 // make sure the database is not READONLY. WAL doesn't make sense for readonly-databases.
2372 if (isReadOnly()) {
2373 return false;
2374 }
2375 // acquire lock - no that no other thread is enabling WAL at the same time
2376 lock();
2377 try {
2378 if (mConnectionPool != null) {
2379 // already enabled
2380 return true;
2381 }
2382 if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
2383 Log.i(TAG, "can't enable WAL for memory databases.");
2384 return false;
2385 }
2386
2387 // make sure this database has NO attached databases because sqlite's write-ahead-logging
2388 // doesn't work for databases with attached databases
2389 if (mHasAttachedDbs) {
2390 if (Log.isLoggable(TAG, Log.DEBUG)) {
2391 Log.d(TAG,
2392 "this database: " + mPath + " has attached databases. can't enable WAL.");
2393 }
2394 return false;
2395 }
2396 mConnectionPool = new DatabaseConnectionPool(this);
2397 setJournalMode(mPath, "WAL");
2398 return true;
2399 } finally {
2400 unlock();
2401 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002402 }
2403
Vasu Nori2827d6d2010-07-04 00:26:18 -07002404 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07002405 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
2406 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07002407 */
Vasu Nori7b04c412010-07-20 10:31:21 -07002408 public void disableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002409 // grab database lock so that writeAheadLogging is not disabled from 2 different threads
2410 // at the same time
2411 lock();
2412 try {
2413 if (mConnectionPool == null) {
2414 return; // already disabled
2415 }
2416 mConnectionPool.close();
2417 setJournalMode(mPath, "TRUNCATE");
2418 mConnectionPool = null;
2419 } finally {
2420 unlock();
2421 }
Vasu Nori8d111032010-06-22 18:34:21 -07002422 }
2423
Vasu Nori65a88832010-07-16 15:14:08 -07002424 /* package */ SQLiteDatabase getDatabaseHandle(String sql) {
2425 if (isPooledConnection()) {
2426 // this is a pooled database connection
Vasu Norice38b982010-07-22 13:57:13 -07002427 // use it if it is open AND if I am not currently part of a transaction
2428 if (isOpen() && !amIInTransaction()) {
Vasu Nori65a88832010-07-16 15:14:08 -07002429 // TODO: use another connection from the pool
2430 // if this connection is currently in use by some other thread
2431 // AND if there are free connections in the pool
2432 return this;
2433 } else {
2434 // the pooled connection is not open! could have been closed either due
2435 // to corruption on this or some other connection to the database
2436 // OR, maybe the connection pool is disabled after this connection has been
2437 // allocated to me. try to get some other pooled or main database connection
2438 return getParentDbConnObj().getDbConnection(sql);
2439 }
2440 } else {
2441 // this is NOT a pooled connection. can we get one?
2442 return getDbConnection(sql);
2443 }
2444 }
2445
Vasu Nori6c354da2010-04-26 23:33:39 -07002446 /* package */ SQLiteDatabase createPoolConnection(short connectionNum) {
Vasu Nori65a88832010-07-16 15:14:08 -07002447 SQLiteDatabase db = openDatabase(mPath, mFactory, mFlags, mErrorHandler, connectionNum);
2448 db.mParentConnObj = this;
2449 return db;
2450 }
2451
2452 private synchronized SQLiteDatabase getParentDbConnObj() {
2453 return mParentConnObj;
Vasu Nori6c354da2010-04-26 23:33:39 -07002454 }
2455
2456 private boolean isPooledConnection() {
2457 return this.mConnectionNum > 0;
2458 }
2459
Vasu Nori2827d6d2010-07-04 00:26:18 -07002460 /* package */ SQLiteDatabase getDbConnection(String sql) {
Vasu Nori6c354da2010-04-26 23:33:39 -07002461 verifyDbIsOpen();
Vasu Noribfe1dc22010-08-25 16:29:02 -07002462 // this method should always be called with main database connection handle.
2463 // the only time when it is called with pooled database connection handle is
2464 // corruption occurs while trying to open a pooled database connection handle.
2465 // in that case, simply return 'this' handle
Vasu Nori65a88832010-07-16 15:14:08 -07002466 if (isPooledConnection()) {
Vasu Noribfe1dc22010-08-25 16:29:02 -07002467 return this;
Vasu Nori65a88832010-07-16 15:14:08 -07002468 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002469
2470 // use the current connection handle if
Vasu Norice38b982010-07-22 13:57:13 -07002471 // 1. if the caller is part of the ongoing transaction, if any
Vasu Nori65a88832010-07-16 15:14:08 -07002472 // 2. OR, if there is NO connection handle pool setup
Vasu Norice38b982010-07-22 13:57:13 -07002473 if (amIInTransaction() || mConnectionPool == null) {
Vasu Nori65a88832010-07-16 15:14:08 -07002474 return this;
Vasu Nori6c354da2010-04-26 23:33:39 -07002475 } else {
2476 // get a connection handle from the pool
2477 if (Log.isLoggable(TAG, Log.DEBUG)) {
2478 assert mConnectionPool != null;
Vasu Norice38b982010-07-22 13:57:13 -07002479 Log.i(TAG, mConnectionPool.toString());
Vasu Nori6c354da2010-04-26 23:33:39 -07002480 }
Vasu Nori65a88832010-07-16 15:14:08 -07002481 return mConnectionPool.get(sql);
Vasu Nori6c354da2010-04-26 23:33:39 -07002482 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002483 }
2484
2485 private void releaseDbConnection(SQLiteDatabase db) {
2486 // ignore this release call if
2487 // 1. the database is closed
2488 // 2. OR, if db is NOT a pooled connection handle
2489 // 3. OR, if the database being released is same as 'this' (this condition means
2490 // that we should always be releasing a pooled connection handle by calling this method
2491 // from the 'main' connection handle
2492 if (!isOpen() || !db.isPooledConnection() || (db == this)) {
2493 return;
2494 }
2495 if (Log.isLoggable(TAG, Log.DEBUG)) {
2496 assert isPooledConnection();
2497 assert mConnectionPool != null;
2498 Log.d(TAG, "releaseDbConnection threadid = " + Thread.currentThread().getId() +
2499 ", releasing # " + db.mConnectionNum + ", " + getPath());
2500 }
2501 mConnectionPool.release(db);
2502 }
2503
Vasu Norif3cf8a42010-03-23 11:41:44 -07002504 /**
2505 * this method is used to collect data about ALL open databases in the current process.
Vasu Nori0732f792010-07-29 17:24:12 -07002506 * bugreport is a user of this data.
Vasu Norif3cf8a42010-03-23 11:41:44 -07002507 */
Vasu Noric3849202010-03-09 10:47:25 -08002508 /* package */ static ArrayList<DbStats> getDbStats() {
2509 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Vasu Nori24675612010-09-27 14:54:19 -07002510 // make a local copy of mActiveDatabases - so that this method is not competing
2511 // for synchronization lock on mActiveDatabases
2512 ArrayList<WeakReference<SQLiteDatabase>> tempList;
2513 synchronized(mActiveDatabases) {
2514 tempList = (ArrayList<WeakReference<SQLiteDatabase>>)mActiveDatabases.clone();
2515 }
2516 for (WeakReference<SQLiteDatabase> w : tempList) {
2517 SQLiteDatabase db = w.get();
2518 if (db == null || !db.isOpen()) {
2519 continue;
2520 }
2521
2522 try {
2523 // get SQLITE_DBSTATUS_LOOKASIDE_USED for the db
2524 int lookasideUsed = db.native_getDbLookaside();
2525
2526 // get the lastnode of the dbname
2527 String path = db.getPath();
2528 int indx = path.lastIndexOf("/");
2529 String lastnode = path.substring((indx != -1) ? ++indx : 0);
2530
2531 // get list of attached dbs and for each db, get its size and pagesize
Vasu Noria017eda2011-01-27 10:52:55 -08002532 List<Pair<String, String>> attachedDbs = db.getAttachedDbs();
Vasu Nori24675612010-09-27 14:54:19 -07002533 if (attachedDbs == null) {
2534 continue;
2535 }
2536 for (int i = 0; i < attachedDbs.size(); i++) {
2537 Pair<String, String> p = attachedDbs.get(i);
2538 long pageCount = DatabaseUtils.longForQuery(db, "PRAGMA " + p.first
2539 + ".page_count;", null);
2540
2541 // first entry in the attached db list is always the main database
2542 // don't worry about prefixing the dbname with "main"
2543 String dbName;
2544 if (i == 0) {
2545 dbName = lastnode;
2546 } else {
2547 // lookaside is only relevant for the main db
2548 lookasideUsed = 0;
2549 dbName = " (attached) " + p.first;
2550 // if the attached db has a path, attach the lastnode from the path to above
2551 if (p.second.trim().length() > 0) {
2552 int idx = p.second.lastIndexOf("/");
2553 dbName += " : " + p.second.substring((idx != -1) ? ++idx : 0);
2554 }
2555 }
2556 if (pageCount > 0) {
2557 dbStatsList.add(new DbStats(dbName, pageCount, db.getPageSize(),
2558 lookasideUsed, db.getCacheHitNum(), db.getCacheMissNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002559 db.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002560 }
2561 }
2562 // if there are pooled connections, return the cache stats for them also.
2563 // while we are trying to query the pooled connections for stats, some other thread
2564 // could be disabling conneciton pool. so, grab a reference to the connection pool.
2565 DatabaseConnectionPool connPool = db.mConnectionPool;
2566 if (connPool != null) {
2567 for (SQLiteDatabase pDb : connPool.getConnectionList()) {
2568 dbStatsList.add(new DbStats("(pooled # " + pDb.mConnectionNum + ") "
2569 + lastnode, 0, 0, 0, pDb.getCacheHitNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002570 pDb.getCacheMissNum(), pDb.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002571 }
2572 }
2573 } catch (SQLiteException e) {
2574 // ignore. we don't care about exceptions when we are taking adb
2575 // bugreport!
2576 }
2577 }
Vasu Noric3849202010-03-09 10:47:25 -08002578 return dbStatsList;
2579 }
2580
2581 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002582 * Returns list of full pathnames of all attached databases including the main database
2583 * by executing 'pragma database_list' on the database.
2584 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002585 * @return ArrayList of pairs of (database name, database file path) or null if the database
2586 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08002587 */
Vasu Noria017eda2011-01-27 10:52:55 -08002588 public List<Pair<String, String>> getAttachedDbs() {
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002589 if (!isOpen()) {
Vasu Norif3cf8a42010-03-23 11:41:44 -07002590 return null;
2591 }
Vasu Noric3849202010-03-09 10:47:25 -08002592 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Vasu Nori24675612010-09-27 14:54:19 -07002593 if (!mHasAttachedDbs) {
2594 // No attached databases.
2595 // There is a small window where attached databases exist but this flag is not set yet.
2596 // This can occur when this thread is in a race condition with another thread
2597 // that is executing the SQL statement: "attach database <blah> as <foo>"
2598 // If this thread is NOT ok with such a race condition (and thus possibly not receive
2599 // the entire list of attached databases), then the caller should ensure that no thread
2600 // is executing any SQL statements while a thread is calling this method.
2601 // Typically, this method is called when 'adb bugreport' is done or the caller wants to
2602 // collect stats on the database and all its attached databases.
2603 attachedDbs.add(new Pair<String, String>("main", mPath));
2604 return attachedDbs;
2605 }
2606 // has attached databases. query sqlite to get the list of attached databases.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002607 Cursor c = null;
2608 try {
2609 c = rawQuery("pragma database_list;", null);
2610 while (c.moveToNext()) {
2611 // sqlite returns a row for each database in the returned list of databases.
2612 // in each row,
2613 // 1st column is the database name such as main, or the database
2614 // name specified on the "ATTACH" command
2615 // 2nd column is the database file path.
2616 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
2617 }
2618 } finally {
2619 if (c != null) {
2620 c.close();
2621 }
Vasu Noric3849202010-03-09 10:47:25 -08002622 }
Vasu Noric3849202010-03-09 10:47:25 -08002623 return attachedDbs;
2624 }
2625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002627 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
2628 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002629 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07002630 *<p>
2631 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002632 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07002633 *<p>
2634 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002635 *
2636 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07002637 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002638 */
2639 public boolean isDatabaseIntegrityOk() {
Vasu Noriccd95442010-05-28 17:04:16 -07002640 verifyDbIsOpen();
Vasu Noria017eda2011-01-27 10:52:55 -08002641 List<Pair<String, String>> attachedDbs = null;
Vasu Noribfe1dc22010-08-25 16:29:02 -07002642 try {
2643 attachedDbs = getAttachedDbs();
2644 if (attachedDbs == null) {
2645 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
2646 "be retrieved. probably because the database is closed");
2647 }
2648 } catch (SQLiteException e) {
2649 // can't get attachedDb list. do integrity check on the main database
2650 attachedDbs = new ArrayList<Pair<String, String>>();
2651 attachedDbs.add(new Pair<String, String>("main", this.mPath));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002652 }
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002653 for (int i = 0; i < attachedDbs.size(); i++) {
2654 Pair<String, String> p = attachedDbs.get(i);
2655 SQLiteStatement prog = null;
2656 try {
2657 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
2658 String rslt = prog.simpleQueryForString();
2659 if (!rslt.equalsIgnoreCase("ok")) {
2660 // integrity_checker failed on main or attached databases
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002661 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
Vasu Noribfe1dc22010-08-25 16:29:02 -07002662 return false;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002663 }
2664 } finally {
2665 if (prog != null) prog.close();
2666 }
2667 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07002668 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002669 }
2670
2671 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 * Native call to open the database.
2673 *
2674 * @param path The full path to the database
2675 */
2676 private native void dbopen(String path, int flags);
2677
2678 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002679 * Native call to setup tracing of all SQL statements
Vasu Nori3ef94e22010-02-05 14:49:04 -08002680 *
2681 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002682 * @param connectionNum connection number: 0 - N, where the main database
2683 * connection handle is numbered 0 and the connection handles in the connection
2684 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002685 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002686 private native void enableSqlTracing(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002687
2688 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002689 * Native call to setup profiling of all SQL statements.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002690 * currently, sqlite's profiling = printing of execution-time
Vasu Noriccd95442010-05-28 17:04:16 -07002691 * (wall-clock time) of each of the SQL statements, as they
Vasu Nori3ef94e22010-02-05 14:49:04 -08002692 * are executed.
2693 *
2694 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002695 * @param connectionNum connection number: 0 - N, where the main database
2696 * connection handle is numbered 0 and the connection handles in the connection
2697 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002698 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002699 private native void enableSqlProfiling(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002700
2701 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 * Native call to set the locale. {@link #lock} must be held when calling
2703 * this method.
2704 * @throws SQLException
2705 */
Vasu Nori0732f792010-07-29 17:24:12 -07002706 private native void native_setLocale(String loc, int flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707
2708 /**
Vasu Noric3849202010-03-09 10:47:25 -08002709 * return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here
2710 * http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html
2711 * @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED
2712 */
2713 private native int native_getDbLookaside();
Vasu Nori6f37f832010-05-19 11:53:25 -07002714
2715 /**
2716 * finalizes the given statement id.
2717 *
2718 * @param statementId statement to be finzlied by sqlite
2719 */
2720 private final native void native_finalize(int statementId);
Vasu Nori34ad57f02010-12-21 09:32:36 -08002721
2722 /**
2723 * set sqlite soft heap limit
2724 * http://www.sqlite.org/c3ref/soft_heap_limit64.html
2725 */
2726 private native void native_setSqliteSoftHeapLimit(int softHeapLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727}