blob: 90a5b5de8c09ac9e0030263833b1e8bec7f469ad [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.database.sqlite;
18
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070019import android.app.AppGlobals;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentValues;
Vasu Nori34ad57f02010-12-21 09:32:36 -080021import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.database.Cursor;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070023import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.database.DatabaseUtils;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070025import android.database.DefaultDatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.database.SQLException;
Vasu Noric3849202010-03-09 10:47:25 -080027import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.os.Debug;
Vasu Noria8c24902010-06-01 11:30:27 -070029import android.os.StatFs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.SystemClock;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070031import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.text.TextUtils;
33import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070035import android.util.Log;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080036import android.util.LruCache;
Vasu Noric3849202010-03-09 10:47:25 -080037import android.util.Pair;
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -070038import dalvik.system.BlockGuard;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import java.io.File;
Vasu Noric3849202010-03-09 10:47:25 -080040import java.lang.ref.WeakReference;
Vasu Noric3849202010-03-09 10:47:25 -080041import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.util.HashMap;
43import java.util.Iterator;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080044import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.util.Locale;
46import java.util.Map;
Dan Egnor12311952009-11-23 14:47:45 -080047import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.util.WeakHashMap;
Vasu Norid4608a32011-02-03 16:24:06 -080049import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.concurrent.locks.ReentrantLock;
Brad Fitzpatrickd8330232010-02-19 10:59:01 -080051import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
53/**
54 * Exposes methods to manage a SQLite database.
55 * <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and
56 * perform other common database management tasks.
57 * <p>See the Notepad sample application in the SDK for an example of creating
58 * and managing a database.
59 * <p> Database names must be unique within an application, not across all
60 * applications.
61 *
62 * <h3>Localized Collation - ORDER BY</h3>
63 * <p>In addition to SQLite's default <code>BINARY</code> collator, Android supplies
64 * two more, <code>LOCALIZED</code>, which changes with the system's current locale
65 * if you wire it up correctly (XXX a link needed!), and <code>UNICODE</code>, which
66 * is the Unicode Collation Algorithm and not tailored to the current locale.
67 */
68public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070069 private static final String TAG = "SQLiteDatabase";
Jeff Hamilton082c2af2009-09-29 11:49:51 -070070 private static final int EVENT_DB_OPERATION = 52000;
71 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73 /**
74 * Algorithms used in ON CONFLICT clause
75 * http://www.sqlite.org/lang_conflict.html
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 */
Vasu Nori8d45e4e2010-02-05 22:35:47 -080077 /**
78 * When a constraint violation occurs, an immediate ROLLBACK occurs,
79 * thus ending the current transaction, and the command aborts with a
80 * return code of SQLITE_CONSTRAINT. If no transaction is active
81 * (other than the implied transaction that is created on every command)
82 * then this algorithm works the same as ABORT.
83 */
84 public static final int CONFLICT_ROLLBACK = 1;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -070085
Vasu Nori8d45e4e2010-02-05 22:35:47 -080086 /**
87 * When a constraint violation occurs,no ROLLBACK is executed
88 * so changes from prior commands within the same transaction
89 * are preserved. This is the default behavior.
90 */
91 public static final int CONFLICT_ABORT = 2;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -070092
Vasu Nori8d45e4e2010-02-05 22:35:47 -080093 /**
94 * When a constraint violation occurs, the command aborts with a return
95 * code SQLITE_CONSTRAINT. But any changes to the database that
96 * the command made prior to encountering the constraint violation
97 * are preserved and are not backed out.
98 */
99 public static final int CONFLICT_FAIL = 3;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700100
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800101 /**
102 * When a constraint violation occurs, the one row that contains
103 * the constraint violation is not inserted or changed.
104 * But the command continues executing normally. Other rows before and
105 * after the row that contained the constraint violation continue to be
106 * inserted or updated normally. No error is returned.
107 */
108 public static final int CONFLICT_IGNORE = 4;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700109
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800110 /**
111 * When a UNIQUE constraint violation occurs, the pre-existing rows that
112 * are causing the constraint violation are removed prior to inserting
113 * or updating the current row. Thus the insert or update always occurs.
114 * The command continues executing normally. No error is returned.
115 * If a NOT NULL constraint violation occurs, the NULL value is replaced
116 * by the default value for that column. If the column has no default
117 * value, then the ABORT algorithm is used. If a CHECK constraint
118 * violation occurs then the IGNORE algorithm is used. When this conflict
119 * resolution strategy deletes rows in order to satisfy a constraint,
120 * it does not invoke delete triggers on those rows.
121 * This behavior might change in a future release.
122 */
123 public static final int CONFLICT_REPLACE = 5;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700124
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800125 /**
126 * use the following when no conflict action is specified.
127 */
128 public static final int CONFLICT_NONE = 0;
129 private static final String[] CONFLICT_VALUES = new String[]
130 {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 /**
133 * Maximum Length Of A LIKE Or GLOB Pattern
134 * The pattern matching algorithm used in the default LIKE and GLOB implementation
135 * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
136 * the pattern) for certain pathological cases. To avoid denial-of-service attacks
137 * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
138 * The default value of this limit is 50000. A modern workstation can evaluate
139 * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
140 * The denial of service problem only comes into play when the pattern length gets
141 * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
142 * are at most a few dozen bytes in length, paranoid application developers may
143 * want to reduce this parameter to something in the range of a few hundred
144 * if they know that external users are able to generate arbitrary patterns.
145 */
146 public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
147
148 /**
149 * Flag for {@link #openDatabase} to open the database for reading and writing.
150 * If the disk is full, this may fail even before you actually write anything.
151 *
152 * {@more} Note that the value of this flag is 0, so it is the default.
153 */
154 public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
155
156 /**
157 * Flag for {@link #openDatabase} to open the database for reading only.
158 * This is the only reliable way to open a database if the disk may be full.
159 */
160 public static final int OPEN_READONLY = 0x00000001; // update native code if changing
161
162 private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
163
164 /**
165 * Flag for {@link #openDatabase} to open the database without support for localized collators.
166 *
167 * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
168 * You must be consistent when using this flag to use the setting the database was
169 * created with. If this is set, {@link #setLocale} will do nothing.
170 */
171 public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
172
173 /**
174 * Flag for {@link #openDatabase} to create the database file if it does not already exist.
175 */
176 public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
177
178 /**
179 * Indicates whether the most-recently started transaction has been marked as successful.
180 */
181 private boolean mInnerTransactionIsSuccessful;
182
183 /**
184 * Valid during the life of a transaction, and indicates whether the entire transaction (the
185 * outer one and all of the inner ones) so far has been successful.
186 */
187 private boolean mTransactionIsSuccessful;
188
Fred Quintanac4516a72009-09-03 12:14:06 -0700189 /**
190 * Valid during the life of a transaction.
191 */
192 private SQLiteTransactionListener mTransactionListener;
193
Vasu Norice38b982010-07-22 13:57:13 -0700194 /**
195 * this member is set if {@link #execSQL(String)} is used to begin and end transactions.
196 */
197 private boolean mTransactionUsingExecSql;
198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 /** Synchronize on this when accessing the database */
Vasu Norid4608a32011-02-03 16:24:06 -0800200 private final DatabaseReentrantLock mLock = new DatabaseReentrantLock(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
202 private long mLockAcquiredWallTime = 0L;
203 private long mLockAcquiredThreadTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // limit the frequency of complaints about each database to one within 20 sec
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700206 // unless run command adb shell setprop log.tag.Database VERBOSE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private static final int LOCK_WARNING_WINDOW_IN_MS = 20000;
208 /** If the lock is held this long then a warning will be printed when it is released. */
209 private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS = 300;
210 private static final int LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS = 100;
211 private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT = 2000;
212
Dmitri Plotnikovb43b58d2009-09-09 18:10:42 -0700213 private static final int SLEEP_AFTER_YIELD_QUANTUM = 1000;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700214
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800215 // The pattern we remove from database filenames before
216 // potentially logging them.
217 private static final Pattern EMAIL_IN_DB_PATTERN = Pattern.compile("[\\w\\.\\-]+@[\\w\\.\\-]+");
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private long mLastLockMessageTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700220
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800221 // Things related to query logging/sampling for debugging
222 // slow/frequent queries during development. Always log queries
Brad Fitzpatrick722802e2010-03-23 22:22:16 -0700223 // which take (by default) 500ms+; shorter queries are sampled
224 // accordingly. Commit statements, which are typically slow, are
225 // logged together with the most recently executed SQL statement,
226 // for disambiguation. The 500ms value is configurable via a
227 // SystemProperty, but developers actively debugging database I/O
228 // should probably use the regular log tunable,
229 // LOG_SLOW_QUERIES_PROPERTY, defined below.
230 private static int sQueryLogTimeInMillis = 0; // lazily initialized
Dan Egnor12311952009-11-23 14:47:45 -0800231 private static final int QUERY_LOG_SQL_LENGTH = 64;
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800232 private static final String COMMIT_SQL = "COMMIT;";
Dan Egnor12311952009-11-23 14:47:45 -0800233 private final Random mRandom = new Random();
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800234 private String mLastSqlStatement = null;
Dan Egnor12311952009-11-23 14:47:45 -0800235
Brad Fitzpatrick722802e2010-03-23 22:22:16 -0700236 // String prefix for slow database query EventLog records that show
237 // lock acquistions of the database.
238 /* package */ static final String GET_LOCK_LOG_PREFIX = "GETLOCK:";
239
Vasu Nori6f37f832010-05-19 11:53:25 -0700240 /** Used by native code, do not rename. make it volatile, so it is thread-safe. */
241 /* package */ volatile int mNativeHandle = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Vasu Noria8c24902010-06-01 11:30:27 -0700243 /**
244 * The size, in bytes, of a block on "/data". This corresponds to the Unix
245 * statfs.f_bsize field. note that this field is lazily initialized.
246 */
247 private static int sBlockSize = 0;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 /** The path for the database file */
Vasu Noriccd95442010-05-28 17:04:16 -0700250 private final String mPath;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800252 /** The anonymized path for the database file for logging purposes */
253 private String mPathForLogs = null; // lazily populated
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 /** The flags passed to open/create */
Vasu Noriccd95442010-05-28 17:04:16 -0700256 private final int mFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
258 /** The optional factory to use when creating new Cursors */
Vasu Noriccd95442010-05-28 17:04:16 -0700259 private final CursorFactory mFactory;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700260
Vasu Nori21343692010-06-03 16:01:39 -0700261 private final WeakHashMap<SQLiteClosable, Object> mPrograms;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700262
Jesse Wilson9b5a9352011-02-10 11:19:09 -0800263 /** Default statement-cache size per database connection ( = instance of this class) */
Jesse Wilsonc2c9a242011-02-10 19:19:02 -0800264 private static final int DEFAULT_SQL_CACHE_SIZE = 25;
Jesse Wilson9b5a9352011-02-10 11:19:09 -0800265
Vasu Nori5a03f362009-10-20 15:16:35 -0700266 /**
Vasu Norib729dcc2010-09-14 11:35:49 -0700267 * for each instance of this class, a LRU cache is maintained to store
268 * the compiled query statement ids returned by sqlite database.
269 * key = SQL statement with "?" for bind args
270 * value = {@link SQLiteCompiledSql}
271 * If an application opens the database and keeps it open during its entire life, then
272 * there will not be an overhead of compilation of SQL statements by sqlite.
273 *
274 * why is this cache NOT static? because sqlite attaches compiledsql statements to the
275 * struct created when {@link SQLiteDatabase#openDatabase(String, CursorFactory, int)} is
276 * invoked.
277 *
Jesse Wilson9b5a9352011-02-10 11:19:09 -0800278 * this cache's max size is settable by calling the method
Jesse Wilsondfe515e2011-02-10 19:06:09 -0800279 * (@link #setMaxSqlCacheSize(int)}.
Vasu Norib729dcc2010-09-14 11:35:49 -0700280 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -0800281 // guarded by this
282 private LruCache<String, SQLiteCompiledSql> mCompiledQueries;
283
Vasu Norib729dcc2010-09-14 11:35:49 -0700284 /**
285 * absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}
286 * size of each prepared-statement is between 1K - 6K, depending on the complexity of the
Vasu Noriccd95442010-05-28 17:04:16 -0700287 * SQL statement & schema.
Vasu Norie495d1f2010-01-06 16:34:19 -0800288 */
Vasu Nori90a367262010-04-12 12:49:09 -0700289 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Nori5e89ae22010-09-15 14:23:29 -0700290 private boolean mCacheFullWarning;
Vasu Norib729dcc2010-09-14 11:35:49 -0700291
Vasu Norid606b4b2010-02-24 12:54:20 -0800292 /** Used to find out where this object was created in case it never got closed. */
Vasu Nori21343692010-06-03 16:01:39 -0700293 private final Throwable mStackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Dmitri Plotnikov90142c92009-09-15 10:52:17 -0700295 // System property that enables logging of slow queries. Specify the threshold in ms.
296 private static final String LOG_SLOW_QUERIES_PROPERTY = "db.log.slow_query_threshold";
297 private final int mSlowQueryThreshold;
298
Vasu Nori6f37f832010-05-19 11:53:25 -0700299 /** stores the list of statement ids that need to be finalized by sqlite */
Vasu Nori21343692010-06-03 16:01:39 -0700300 private final ArrayList<Integer> mClosedStatementIds = new ArrayList<Integer>();
Vasu Nori6f37f832010-05-19 11:53:25 -0700301
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700302 /** {@link DatabaseErrorHandler} to be used when SQLite returns any of the following errors
303 * Corruption
304 * */
Vasu Nori21343692010-06-03 16:01:39 -0700305 private final DatabaseErrorHandler mErrorHandler;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700306
Vasu Nori6c354da2010-04-26 23:33:39 -0700307 /** The Database connection pool {@link DatabaseConnectionPool}.
308 * Visibility is package-private for testing purposes. otherwise, private visibility is enough.
309 */
310 /* package */ volatile DatabaseConnectionPool mConnectionPool = null;
311
312 /** Each database connection handle in the pool is assigned a number 1..N, where N is the
313 * size of the connection pool.
314 * The main connection handle to which the pool is attached is assigned a value of 0.
315 */
316 /* package */ final short mConnectionNum;
317
Vasu Nori65a88832010-07-16 15:14:08 -0700318 /** on pooled database connections, this member points to the parent ( = main)
319 * database connection handle.
320 * package visibility only for testing purposes
321 */
322 /* package */ SQLiteDatabase mParentConnObj = null;
323
Vasu Noria98cb262010-06-22 13:16:35 -0700324 private static final String MEMORY_DB_PATH = ":memory:";
325
Vasu Nori24675612010-09-27 14:54:19 -0700326 /** set to true if the database has attached databases */
327 private volatile boolean mHasAttachedDbs = false;
328
Vasu Nori0732f792010-07-29 17:24:12 -0700329 /** stores reference to all databases opened in the current process. */
330 private static ArrayList<WeakReference<SQLiteDatabase>> mActiveDatabases =
331 new ArrayList<WeakReference<SQLiteDatabase>>();
332
Vasu Nori2827d6d2010-07-04 00:26:18 -0700333 synchronized void addSQLiteClosable(SQLiteClosable closable) {
334 // mPrograms is per instance of SQLiteDatabase and it doesn't actually touch the database
335 // itself. so, there is no need to lock().
336 mPrograms.put(closable, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700338
Vasu Nori2827d6d2010-07-04 00:26:18 -0700339 synchronized void removeSQLiteClosable(SQLiteClosable closable) {
340 mPrograms.remove(closable);
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700341 }
342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 @Override
344 protected void onAllReferencesReleased() {
345 if (isOpen()) {
Vasu Noriad239ab2010-06-14 16:58:47 -0700346 // close the database which will close all pending statements to be finalized also
347 close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
349 }
350
351 /**
352 * Attempts to release memory that SQLite holds but does not require to
353 * operate properly. Typically this memory will come from the page cache.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700354 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 * @return the number of bytes actually released
356 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700357 static public native int releaseMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358
359 /**
360 * Control whether or not the SQLiteDatabase is made thread-safe by using locks
361 * around critical sections. This is pretty expensive, so if you know that your
362 * DB will only be used by a single thread then you should set this to false.
363 * The default is true.
364 * @param lockingEnabled set to true to enable locks, false otherwise
365 */
366 public void setLockingEnabled(boolean lockingEnabled) {
367 mLockingEnabled = lockingEnabled;
368 }
369
370 /**
371 * If set then the SQLiteDatabase is made thread-safe by using locks
372 * around critical sections
373 */
374 private boolean mLockingEnabled = true;
375
376 /* package */ void onCorruption() {
Vasu Norif3cf8a42010-03-23 11:41:44 -0700377 EventLog.writeEvent(EVENT_DB_CORRUPT, mPath);
Vasu Noriccd95442010-05-28 17:04:16 -0700378 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
380
381 /**
382 * Locks the database for exclusive access. The database lock must be held when
383 * touch the native sqlite3* object since it is single threaded and uses
384 * a polling lock contention algorithm. The lock is recursive, and may be acquired
385 * multiple times by the same thread. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700386 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * @see #unlock()
388 */
389 /* package */ void lock() {
Vasu Nori6d970252010-10-05 10:48:49 -0700390 lock(false);
391 }
Vasu Norid4608a32011-02-03 16:24:06 -0800392 private static final long LOCK_WAIT_PERIOD = 30L;
Vasu Nori6d970252010-10-05 10:48:49 -0700393 private void lock(boolean forced) {
394 // make sure this method is NOT being called from a 'synchronized' method
395 if (Thread.holdsLock(this)) {
Vasu Nori4b92aee2011-01-26 23:22:34 -0800396 Log.w(TAG, "don't lock() while in a synchronized method");
Vasu Nori6d970252010-10-05 10:48:49 -0700397 }
Vasu Nori7b04c412010-07-20 10:31:21 -0700398 verifyDbIsOpen();
Vasu Nori6d970252010-10-05 10:48:49 -0700399 if (!forced && !mLockingEnabled) return;
Vasu Norid4608a32011-02-03 16:24:06 -0800400 boolean done = false;
401 while (!done) {
402 try {
403 // wait for 30sec to acquire the lock
404 done = mLock.tryLock(LOCK_WAIT_PERIOD, TimeUnit.SECONDS);
405 if (!done) {
406 // lock not acquired in NSec. print a message and stacktrace saying the lock
407 // has not been available for 30sec.
408 Log.w(TAG, "database lock has not been available for " + LOCK_WAIT_PERIOD +
409 " sec. Current Owner of the lock is " + mLock.getOwnerDescription() +
Vasu Norie9714e62011-02-11 16:50:51 -0800410 ". Continuing to wait in thread: " + Thread.currentThread().getId());
Vasu Norid4608a32011-02-03 16:24:06 -0800411 }
412 } catch (InterruptedException e) {
413 // ignore the interruption
414 }
415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
417 if (mLock.getHoldCount() == 1) {
418 // Use elapsed real-time since the CPU may sleep when waiting for IO
419 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
420 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
421 }
422 }
423 }
Vasu Norid4608a32011-02-03 16:24:06 -0800424 private static class DatabaseReentrantLock extends ReentrantLock {
425 DatabaseReentrantLock(boolean fair) {
426 super(fair);
427 }
428 @Override
429 public Thread getOwner() {
430 return super.getOwner();
431 }
432 public String getOwnerDescription() {
433 Thread t = getOwner();
434 return (t== null) ? "none" : String.valueOf(t.getId());
435 }
436 }
437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 /**
439 * Locks the database for exclusive access. The database lock must be held when
440 * touch the native sqlite3* object since it is single threaded and uses
441 * a polling lock contention algorithm. The lock is recursive, and may be acquired
442 * multiple times by the same thread.
443 *
444 * @see #unlockForced()
445 */
446 private void lockForced() {
Vasu Nori6d970252010-10-05 10:48:49 -0700447 lock(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
449
450 /**
451 * Releases the database lock. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700452 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 * @see #unlock()
454 */
455 /* package */ void unlock() {
456 if (!mLockingEnabled) return;
457 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
458 if (mLock.getHoldCount() == 1) {
459 checkLockHoldTime();
460 }
461 }
462 mLock.unlock();
463 }
464
465 /**
466 * Releases the database lock.
467 *
468 * @see #unlockForced()
469 */
470 private void unlockForced() {
471 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
472 if (mLock.getHoldCount() == 1) {
473 checkLockHoldTime();
474 }
475 }
476 mLock.unlock();
477 }
478
479 private void checkLockHoldTime() {
480 // Use elapsed real-time since the CPU may sleep when waiting for IO
481 long elapsedTime = SystemClock.elapsedRealtime();
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700482 long lockedTime = elapsedTime - mLockAcquiredWallTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 if (lockedTime < LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT &&
484 !Log.isLoggable(TAG, Log.VERBOSE) &&
485 (elapsedTime - mLastLockMessageTime) < LOCK_WARNING_WINDOW_IN_MS) {
486 return;
487 }
488 if (lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS) {
489 int threadTime = (int)
490 ((Debug.threadCpuTimeNanos() - mLockAcquiredThreadTime) / 1000000);
491 if (threadTime > LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS ||
492 lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT) {
493 mLastLockMessageTime = elapsedTime;
494 String msg = "lock held on " + mPath + " for " + lockedTime + "ms. Thread time was "
495 + threadTime + "ms";
496 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING_STACK_TRACE) {
497 Log.d(TAG, msg, new Exception());
498 } else {
499 Log.d(TAG, msg);
500 }
501 }
502 }
503 }
504
505 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700506 * Begins a transaction in EXCLUSIVE mode.
507 * <p>
508 * Transactions can be nested.
509 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 * the work done in that transaction and all of the nested transactions will be committed or
511 * rolled back. The changes will be rolled back if any transaction is ended without being
512 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700513 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 * <p>Here is the standard idiom for transactions:
515 *
516 * <pre>
517 * db.beginTransaction();
518 * try {
519 * ...
520 * db.setTransactionSuccessful();
521 * } finally {
522 * db.endTransaction();
523 * }
524 * </pre>
525 */
526 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700527 beginTransaction(null /* transactionStatusCallback */, true);
528 }
529
530 /**
531 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
532 * the outer transaction is ended all of the work done in that transaction
533 * and all of the nested transactions will be committed or rolled back. The
534 * changes will be rolled back if any transaction is ended without being
535 * marked as clean (by calling setTransactionSuccessful). Otherwise they
536 * will be committed.
537 * <p>
538 * Here is the standard idiom for transactions:
539 *
540 * <pre>
541 * db.beginTransactionNonExclusive();
542 * try {
543 * ...
544 * db.setTransactionSuccessful();
545 * } finally {
546 * db.endTransaction();
547 * }
548 * </pre>
549 */
550 public void beginTransactionNonExclusive() {
551 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700552 }
553
554 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700555 * Begins a transaction in EXCLUSIVE mode.
556 * <p>
557 * Transactions can be nested.
558 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700559 * the work done in that transaction and all of the nested transactions will be committed or
560 * rolled back. The changes will be rolled back if any transaction is ended without being
561 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700562 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700563 * <p>Here is the standard idiom for transactions:
564 *
565 * <pre>
566 * db.beginTransactionWithListener(listener);
567 * try {
568 * ...
569 * db.setTransactionSuccessful();
570 * } finally {
571 * db.endTransaction();
572 * }
573 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700574 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700575 * @param transactionListener listener that should be notified when the transaction begins,
576 * commits, or is rolled back, either explicitly or by a call to
577 * {@link #yieldIfContendedSafely}.
578 */
579 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700580 beginTransaction(transactionListener, true);
581 }
582
583 /**
584 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
585 * the outer transaction is ended all of the work done in that transaction
586 * and all of the nested transactions will be committed or rolled back. The
587 * changes will be rolled back if any transaction is ended without being
588 * marked as clean (by calling setTransactionSuccessful). Otherwise they
589 * will be committed.
590 * <p>
591 * Here is the standard idiom for transactions:
592 *
593 * <pre>
594 * db.beginTransactionWithListenerNonExclusive(listener);
595 * try {
596 * ...
597 * db.setTransactionSuccessful();
598 * } finally {
599 * db.endTransaction();
600 * }
601 * </pre>
602 *
603 * @param transactionListener listener that should be notified when the
604 * transaction begins, commits, or is rolled back, either
605 * explicitly or by a call to {@link #yieldIfContendedSafely}.
606 */
607 public void beginTransactionWithListenerNonExclusive(
608 SQLiteTransactionListener transactionListener) {
609 beginTransaction(transactionListener, false);
610 }
611
612 private void beginTransaction(SQLiteTransactionListener transactionListener,
613 boolean exclusive) {
Vasu Noriccd95442010-05-28 17:04:16 -0700614 verifyDbIsOpen();
Vasu Noric8e1f232010-04-13 15:05:09 -0700615 lockForced();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 boolean ok = false;
617 try {
618 // If this thread already had the lock then get out
619 if (mLock.getHoldCount() > 1) {
620 if (mInnerTransactionIsSuccessful) {
621 String msg = "Cannot call beginTransaction between "
622 + "calling setTransactionSuccessful and endTransaction";
623 IllegalStateException e = new IllegalStateException(msg);
624 Log.e(TAG, "beginTransaction() failed", e);
625 throw e;
626 }
627 ok = true;
628 return;
629 }
630
631 // This thread didn't already have the lock, so begin a database
632 // transaction now.
Vasu Nori57feb5d2010-06-22 10:39:04 -0700633 if (exclusive && mConnectionPool == null) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700634 execSQL("BEGIN EXCLUSIVE;");
635 } else {
636 execSQL("BEGIN IMMEDIATE;");
637 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700638 mTransactionListener = transactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 mTransactionIsSuccessful = true;
640 mInnerTransactionIsSuccessful = false;
Fred Quintanac4516a72009-09-03 12:14:06 -0700641 if (transactionListener != null) {
642 try {
643 transactionListener.onBegin();
644 } catch (RuntimeException e) {
645 execSQL("ROLLBACK;");
646 throw e;
647 }
648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 ok = true;
650 } finally {
651 if (!ok) {
652 // beginTransaction is called before the try block so we must release the lock in
653 // the case of failure.
654 unlockForced();
655 }
656 }
657 }
658
659 /**
660 * End a transaction. See beginTransaction for notes about how to use this and when transactions
661 * are committed and rolled back.
662 */
663 public void endTransaction() {
Vasu Noriccd95442010-05-28 17:04:16 -0700664 verifyLockOwner();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 try {
666 if (mInnerTransactionIsSuccessful) {
667 mInnerTransactionIsSuccessful = false;
668 } else {
669 mTransactionIsSuccessful = false;
670 }
671 if (mLock.getHoldCount() != 1) {
672 return;
673 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700674 RuntimeException savedException = null;
675 if (mTransactionListener != null) {
676 try {
677 if (mTransactionIsSuccessful) {
678 mTransactionListener.onCommit();
679 } else {
680 mTransactionListener.onRollback();
681 }
682 } catch (RuntimeException e) {
683 savedException = e;
684 mTransactionIsSuccessful = false;
685 }
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 if (mTransactionIsSuccessful) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800688 execSQL(COMMIT_SQL);
Vasu Nori6c354da2010-04-26 23:33:39 -0700689 // if write-ahead logging is used, we have to take care of checkpoint.
690 // TODO: should applications be given the flexibility of choosing when to
691 // trigger checkpoint?
692 // for now, do checkpoint after every COMMIT because that is the fastest
693 // way to guarantee that readers will see latest data.
694 // but this is the slowest way to run sqlite with in write-ahead logging mode.
695 if (this.mConnectionPool != null) {
696 execSQL("PRAGMA wal_checkpoint;");
697 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
698 Log.i(TAG, "PRAGMA wal_Checkpoint done");
699 }
700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 } else {
702 try {
703 execSQL("ROLLBACK;");
Fred Quintanac4516a72009-09-03 12:14:06 -0700704 if (savedException != null) {
705 throw savedException;
706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 } catch (SQLException e) {
708 if (Config.LOGD) {
709 Log.d(TAG, "exception during rollback, maybe the DB previously "
710 + "performed an auto-rollback");
711 }
712 }
713 }
714 } finally {
Fred Quintanac4516a72009-09-03 12:14:06 -0700715 mTransactionListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 unlockForced();
717 if (Config.LOGV) {
718 Log.v(TAG, "unlocked " + Thread.currentThread()
719 + ", holdCount is " + mLock.getHoldCount());
720 }
721 }
722 }
723
724 /**
725 * Marks the current transaction as successful. Do not do any more database work between
726 * calling this and calling endTransaction. Do as little non-database work as possible in that
727 * situation too. If any errors are encountered between this and endTransaction the transaction
728 * will still be committed.
729 *
730 * @throws IllegalStateException if the current thread is not in a transaction or the
731 * transaction is already marked as successful.
732 */
733 public void setTransactionSuccessful() {
Vasu Noriccd95442010-05-28 17:04:16 -0700734 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 if (!mLock.isHeldByCurrentThread()) {
736 throw new IllegalStateException("no transaction pending");
737 }
738 if (mInnerTransactionIsSuccessful) {
739 throw new IllegalStateException(
740 "setTransactionSuccessful may only be called once per call to beginTransaction");
741 }
742 mInnerTransactionIsSuccessful = true;
743 }
744
745 /**
746 * return true if there is a transaction pending
747 */
748 public boolean inTransaction() {
Vasu Norice38b982010-07-22 13:57:13 -0700749 return mLock.getHoldCount() > 0 || mTransactionUsingExecSql;
750 }
751
752 /* package */ synchronized void setTransactionUsingExecSqlFlag() {
753 if (Log.isLoggable(TAG, Log.DEBUG)) {
754 Log.i(TAG, "found execSQL('begin transaction')");
755 }
756 mTransactionUsingExecSql = true;
757 }
758
759 /* package */ synchronized void resetTransactionUsingExecSqlFlag() {
760 if (Log.isLoggable(TAG, Log.DEBUG)) {
761 if (mTransactionUsingExecSql) {
762 Log.i(TAG, "found execSQL('commit or end or rollback')");
763 }
764 }
765 mTransactionUsingExecSql = false;
766 }
767
768 /**
769 * Returns true if the caller is considered part of the current transaction, if any.
770 * <p>
771 * Caller is part of the current transaction if either of the following is true
772 * <ol>
773 * <li>If transaction is started by calling beginTransaction() methods AND if the caller is
774 * in the same thread as the thread that started the transaction.
775 * </li>
776 * <li>If the transaction is started by calling {@link #execSQL(String)} like this:
777 * execSQL("BEGIN transaction"). In this case, every thread in the process is considered
778 * part of the current transaction.</li>
779 * </ol>
780 *
781 * @return true if the caller is considered part of the current transaction, if any.
782 */
783 /* package */ synchronized boolean amIInTransaction() {
784 // always do this test on the main database connection - NOT on pooled database connection
785 // since transactions always occur on the main database connections only.
786 SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this;
787 boolean b = (!db.inTransaction()) ? false :
788 db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread();
789 if (Log.isLoggable(TAG, Log.DEBUG)) {
790 Log.i(TAG, "amIinTransaction: " + b);
791 }
792 return b;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 }
794
795 /**
796 * Checks if the database lock is held by this thread.
797 *
798 * @return true, if this thread is holding the database lock.
799 */
800 public boolean isDbLockedByCurrentThread() {
801 return mLock.isHeldByCurrentThread();
802 }
803
804 /**
805 * Checks if the database is locked by another thread. This is
806 * just an estimate, since this status can change at any time,
807 * including after the call is made but before the result has
808 * been acted upon.
809 *
810 * @return true, if the database is locked by another thread
811 */
812 public boolean isDbLockedByOtherThreads() {
813 return !mLock.isHeldByCurrentThread() && mLock.isLocked();
814 }
815
816 /**
817 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
818 * successful so far. Do not call setTransactionSuccessful before calling this. When this
819 * returns a new transaction will have been created but not marked as successful.
820 * @return true if the transaction was yielded
821 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
822 * will not be yielded. Use yieldIfContendedSafely instead.
823 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700824 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700826 return yieldIfContendedHelper(false /* do not check yielding */,
827 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829
830 /**
831 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
832 * successful so far. Do not call setTransactionSuccessful before calling this. When this
833 * returns a new transaction will have been created but not marked as successful. This assumes
834 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700835 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 * @return true if the transaction was yielded
837 */
838 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700839 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841
Fred Quintana5c7aede2009-08-27 21:41:27 -0700842 /**
843 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
844 * successful so far. Do not call setTransactionSuccessful before calling this. When this
845 * returns a new transaction will have been created but not marked as successful. This assumes
846 * that there are no nested transactions (beginTransaction has only been called once) and will
847 * throw an exception if that is not the case.
848 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
849 * the lock was actually yielded. This will allow other background threads to make some
850 * more progress than they would if we started the transaction immediately.
851 * @return true if the transaction was yielded
852 */
853 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
854 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
855 }
856
857 private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 if (mLock.getQueueLength() == 0) {
859 // Reset the lock acquire time since we know that the thread was willing to yield
860 // the lock at this time.
861 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
862 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
863 return false;
864 }
865 setTransactionSuccessful();
Fred Quintanac4516a72009-09-03 12:14:06 -0700866 SQLiteTransactionListener transactionListener = mTransactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 endTransaction();
868 if (checkFullyYielded) {
869 if (this.isDbLockedByCurrentThread()) {
870 throw new IllegalStateException(
871 "Db locked more than once. yielfIfContended cannot yield");
872 }
873 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700874 if (sleepAfterYieldDelay > 0) {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700875 // Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to
876 // check if anyone is using the database. If the database is not contended,
877 // retake the lock and return.
878 long remainingDelay = sleepAfterYieldDelay;
879 while (remainingDelay > 0) {
880 try {
881 Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ?
882 remainingDelay : SLEEP_AFTER_YIELD_QUANTUM);
883 } catch (InterruptedException e) {
884 Thread.interrupted();
885 }
886 remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM;
887 if (mLock.getQueueLength() == 0) {
888 break;
889 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700890 }
891 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700892 beginTransactionWithListener(transactionListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 return true;
894 }
895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 /**
Vasu Nori95675132010-07-21 16:24:40 -0700897 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 */
Vasu Nori95675132010-07-21 16:24:40 -0700899 @Deprecated
900 public Map<String, String> getSyncedTables() {
901 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903
904 /**
905 * Used to allow returning sub-classes of {@link Cursor} when calling query.
906 */
907 public interface CursorFactory {
908 /**
909 * See
Vasu Noribfe1dc22010-08-25 16:29:02 -0700910 * {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 */
912 public Cursor newCursor(SQLiteDatabase db,
913 SQLiteCursorDriver masterQuery, String editTable,
914 SQLiteQuery query);
915 }
916
917 /**
918 * Open the database according to the flags {@link #OPEN_READWRITE}
919 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
920 *
921 * <p>Sets the locale of the database to the the system's current locale.
922 * Call {@link #setLocale} if you would like something else.</p>
923 *
924 * @param path to database file to open and/or create
925 * @param factory an optional factory class that is called to instantiate a
926 * cursor when query is called, or null for default
927 * @param flags to control database access mode
928 * @return the newly opened database
929 * @throws SQLiteException if the database cannot be opened
930 */
931 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700932 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
933 }
934
935 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700936 * Open the database according to the flags {@link #OPEN_READWRITE}
937 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
938 *
939 * <p>Sets the locale of the database to the the system's current locale.
940 * Call {@link #setLocale} if you would like something else.</p>
941 *
942 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
943 * used to handle corruption when sqlite reports database corruption.</p>
944 *
945 * @param path to database file to open and/or create
946 * @param factory an optional factory class that is called to instantiate a
947 * cursor when query is called, or null for default
948 * @param flags to control database access mode
949 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
950 * when sqlite reports database corruption
951 * @return the newly opened database
952 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700953 */
954 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
955 DatabaseErrorHandler errorHandler) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700956 SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler,
957 (short) 0 /* the main connection handle */);
Vasu Noria8c24902010-06-01 11:30:27 -0700958
959 // set sqlite pagesize to mBlockSize
960 if (sBlockSize == 0) {
961 // TODO: "/data" should be a static final String constant somewhere. it is hardcoded
962 // in several places right now.
963 sBlockSize = new StatFs("/data").getBlockSize();
964 }
965 sqliteDatabase.setPageSize(sBlockSize);
Vasu Noria22d8842011-01-06 08:30:29 -0800966 sqliteDatabase.setJournalMode(path, "TRUNCATE");
Vasu Norif9e2bd02010-06-04 16:49:51 -0700967
Vasu Noriccd95442010-05-28 17:04:16 -0700968 // add this database to the list of databases opened in this process
Vasu Nori0732f792010-07-29 17:24:12 -0700969 synchronized(mActiveDatabases) {
970 mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase));
971 }
Vasu Noric3849202010-03-09 10:47:25 -0800972 return sqliteDatabase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974
Vasu Nori6c354da2010-04-26 23:33:39 -0700975 private static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
976 DatabaseErrorHandler errorHandler, short connectionNum) {
977 SQLiteDatabase db = new SQLiteDatabase(path, factory, flags, errorHandler, connectionNum);
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700978 try {
Vasu Norice38b982010-07-22 13:57:13 -0700979 if (Log.isLoggable(TAG, Log.DEBUG)) {
980 Log.i(TAG, "opening the db : " + path);
981 }
Vasu Nori6c354da2010-04-26 23:33:39 -0700982 // Open the database.
983 db.dbopen(path, flags);
984 db.setLocale(Locale.getDefault());
985 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
986 db.enableSqlTracing(path, connectionNum);
987 }
988 if (SQLiteDebug.DEBUG_SQL_TIME) {
989 db.enableSqlProfiling(path, connectionNum);
990 }
991 return db;
992 } catch (SQLiteDatabaseCorruptException e) {
Vasu Nori6a904bc2011-01-05 18:35:40 -0800993 db.mErrorHandler.onCorruption(db);
994 return SQLiteDatabase.openDatabase(path, factory, flags, errorHandler);
Vasu Nori6c354da2010-04-26 23:33:39 -0700995 } catch (SQLiteException e) {
996 Log.e(TAG, "Failed to open the database. closing it.", e);
997 db.close();
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700998 throw e;
999 }
1000 }
1001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 /**
1003 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
1004 */
1005 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
1006 return openOrCreateDatabase(file.getPath(), factory);
1007 }
1008
1009 /**
1010 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
1011 */
1012 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
1013 return openDatabase(path, factory, CREATE_IF_NECESSARY);
1014 }
1015
1016 /**
Vasu Nori6c354da2010-04-26 23:33:39 -07001017 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001018 */
1019 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
1020 DatabaseErrorHandler errorHandler) {
1021 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
1022 }
1023
Vasu Noria98cb262010-06-22 13:16:35 -07001024 private void setJournalMode(final String dbPath, final String mode) {
1025 // journal mode can be set only for non-memory databases
Vasu Nori8fcda302010-11-08 13:46:40 -08001026 // AND can't be set for readonly databases
1027 if (dbPath.equalsIgnoreCase(MEMORY_DB_PATH) || isReadOnly()) {
1028 return;
1029 }
1030 String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null);
1031 if (!s.equalsIgnoreCase(mode)) {
1032 Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + dbPath +
1033 " (on pragma set journal_mode, sqlite returned:" + s);
Vasu Noria98cb262010-06-22 13:16:35 -07001034 }
1035 }
1036
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001037 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 * Create a memory backed SQLite database. Its contents will be destroyed
1039 * when the database is closed.
1040 *
1041 * <p>Sets the locale of the database to the the system's current locale.
1042 * Call {@link #setLocale} if you would like something else.</p>
1043 *
1044 * @param factory an optional factory class that is called to instantiate a
1045 * cursor when query is called
1046 * @return a SQLiteDatabase object, or null if the database can't be created
1047 */
1048 public static SQLiteDatabase create(CursorFactory factory) {
1049 // This is a magic string with special meaning for SQLite.
Vasu Noria98cb262010-06-22 13:16:35 -07001050 return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052
1053 /**
1054 * Close the database.
1055 */
1056 public void close() {
Vasu Nori587423a2010-09-27 18:18:34 -07001057 if (!isOpen()) {
1058 return;
1059 }
Vasu Norice38b982010-07-22 13:57:13 -07001060 if (Log.isLoggable(TAG, Log.DEBUG)) {
Vasu Nori75010102010-07-01 16:23:06 -07001061 Log.i(TAG, "closing db: " + mPath + " (connection # " + mConnectionNum);
1062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 lock();
1064 try {
Vasu Noriffe06122010-09-27 12:32:57 -07001065 // some other thread could have closed this database while I was waiting for lock.
1066 // check the database state
1067 if (!isOpen()) {
1068 return;
1069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 closeClosable();
Vasu Norifea6f6d2010-05-21 15:36:06 -07001071 // finalize ALL statements queued up so far
1072 closePendingStatements();
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001073 releaseCustomFunctions();
Vasu Norif6373e92010-03-16 10:21:00 -07001074 // close this database instance - regardless of its reference count value
Vasu Nori422dad02010-09-03 16:03:08 -07001075 closeDatabase();
Vasu Nori6c354da2010-04-26 23:33:39 -07001076 if (mConnectionPool != null) {
Vasu Norice38b982010-07-22 13:57:13 -07001077 if (Log.isLoggable(TAG, Log.DEBUG)) {
1078 assert mConnectionPool != null;
1079 Log.i(TAG, mConnectionPool.toString());
1080 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001081 mConnectionPool.close();
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 } finally {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001084 unlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086 }
1087
1088 private void closeClosable() {
Vasu Noriccd95442010-05-28 17:04:16 -07001089 /* deallocate all compiled SQL statement objects from mCompiledQueries cache.
Vasu Norie495d1f2010-01-06 16:34:19 -08001090 * this should be done before de-referencing all {@link SQLiteClosable} objects
1091 * from this database object because calling
1092 * {@link SQLiteClosable#onAllReferencesReleasedFromContainer()} could cause the database
1093 * to be closed. sqlite doesn't let a database close if there are
1094 * any unfinalized statements - such as the compiled-sql objects in mCompiledQueries.
1095 */
Vasu Norib729dcc2010-09-14 11:35:49 -07001096 deallocCachedSqlStatements();
Vasu Norie495d1f2010-01-06 16:34:19 -08001097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1099 while (iter.hasNext()) {
1100 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1101 SQLiteClosable program = entry.getKey();
1102 if (program != null) {
1103 program.onAllReferencesReleasedFromContainer();
1104 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 /**
Vasu Nori422dad02010-09-03 16:03:08 -07001109 * package level access for testing purposes
1110 */
1111 /* package */ void closeDatabase() throws SQLiteException {
1112 try {
1113 dbclose();
1114 } catch (SQLiteUnfinalizedObjectsException e) {
1115 String msg = e.getMessage();
1116 String[] tokens = msg.split(",", 2);
1117 int stmtId = Integer.parseInt(tokens[0]);
1118 // get extra info about this statement, if it is still to be released by closeClosable()
1119 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1120 boolean found = false;
1121 while (iter.hasNext()) {
1122 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1123 SQLiteClosable program = entry.getKey();
1124 if (program != null && program instanceof SQLiteProgram) {
Vasu Norib4389022010-11-29 14:10:46 -08001125 SQLiteCompiledSql compiledSql = ((SQLiteProgram)program).mCompiledSql;
1126 if (compiledSql.nStatement == stmtId) {
1127 msg = compiledSql.toString();
1128 found = true;
1129 }
Vasu Nori422dad02010-09-03 16:03:08 -07001130 }
1131 }
1132 if (!found) {
1133 // the statement is already released by closeClosable(). is it waiting to be
1134 // finalized?
1135 if (mClosedStatementIds.contains(stmtId)) {
1136 Log.w(TAG, "this shouldn't happen. finalizing the statement now: ");
1137 closePendingStatements();
1138 // try to close the database again
1139 closeDatabase();
1140 }
1141 } else {
1142 // the statement is not yet closed. most probably programming error in the app.
Vasu Norib4389022010-11-29 14:10:46 -08001143 throw new SQLiteUnfinalizedObjectsException(
1144 "close() on database: " + getPath() +
1145 " failed due to un-close()d SQL statements: " + msg);
Vasu Nori422dad02010-09-03 16:03:08 -07001146 }
1147 }
1148 }
1149
1150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 * Native call to close the database.
1152 */
1153 private native void dbclose();
1154
1155 /**
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001156 * A callback interface for a custom sqlite3 function.
1157 * This can be used to create a function that can be called from
1158 * sqlite3 database triggers.
1159 * @hide
1160 */
1161 public interface CustomFunction {
1162 public void callback(String[] args);
1163 }
1164
1165 /**
1166 * Registers a CustomFunction callback as a function that can be called from
1167 * sqlite3 database triggers.
1168 * @param name the name of the sqlite3 function
1169 * @param numArgs the number of arguments for the function
1170 * @param function callback to call when the function is executed
1171 * @hide
1172 */
1173 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
1174 verifyDbIsOpen();
1175 synchronized (mCustomFunctions) {
1176 int ref = native_addCustomFunction(name, numArgs, function);
1177 if (ref != 0) {
1178 // save a reference to the function for cleanup later
1179 mCustomFunctions.add(new Integer(ref));
1180 } else {
1181 throw new SQLiteException("failed to add custom function " + name);
1182 }
1183 }
1184 }
1185
1186 private void releaseCustomFunctions() {
1187 synchronized (mCustomFunctions) {
1188 for (int i = 0; i < mCustomFunctions.size(); i++) {
1189 Integer function = mCustomFunctions.get(i);
1190 native_releaseCustomFunction(function.intValue());
1191 }
1192 mCustomFunctions.clear();
1193 }
1194 }
1195
1196 // list of CustomFunction references so we can clean up when the database closes
1197 private final ArrayList<Integer> mCustomFunctions =
1198 new ArrayList<Integer>();
1199
1200 private native int native_addCustomFunction(String name, int numArgs, CustomFunction function);
1201 private native void native_releaseCustomFunction(int function);
1202
1203 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 * Gets the database version.
1205 *
1206 * @return the database version
1207 */
1208 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -07001209 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
1212 /**
1213 * Sets the database version.
1214 *
1215 * @param version the new database version
1216 */
1217 public void setVersion(int version) {
1218 execSQL("PRAGMA user_version = " + version);
1219 }
1220
1221 /**
1222 * Returns the maximum size the database may grow to.
1223 *
1224 * @return the new maximum database size
1225 */
1226 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001227 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
1228 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
1230
1231 /**
1232 * Sets the maximum size the database will grow to. The maximum size cannot
1233 * be set below the current size.
1234 *
1235 * @param numBytes the maximum database size, in bytes
1236 * @return the new maximum database size
1237 */
1238 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -07001239 long pageSize = getPageSize();
1240 long numPages = numBytes / pageSize;
1241 // If numBytes isn't a multiple of pageSize, bump up a page
1242 if ((numBytes % pageSize) != 0) {
1243 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -07001244 }
Vasu Noriccd95442010-05-28 17:04:16 -07001245 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
1246 null);
1247 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
1249
1250 /**
1251 * Returns the current database page size, in bytes.
1252 *
1253 * @return the database page size, in bytes
1254 */
1255 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001256 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258
1259 /**
1260 * Sets the database page size. The page size must be a power of two. This
1261 * method does not work if any data has been written to the database file,
1262 * and must be called right after the database has been created.
1263 *
1264 * @param numBytes the database page size, in bytes
1265 */
1266 public void setPageSize(long numBytes) {
1267 execSQL("PRAGMA page_size = " + numBytes);
1268 }
1269
1270 /**
1271 * Mark this table as syncable. When an update occurs in this table the
1272 * _sync_dirty field will be set to ensure proper syncing operation.
1273 *
1274 * @param table the table to mark as syncable
1275 * @param deletedTable The deleted table that corresponds to the
1276 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -07001277 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 */
Vasu Nori95675132010-07-21 16:24:40 -07001279 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282
1283 /**
1284 * Mark this table as syncable, with the _sync_dirty residing in another
1285 * table. When an update occurs in this table the _sync_dirty field of the
1286 * row in updateTable with the _id in foreignKey will be set to
1287 * ensure proper syncing operation.
1288 *
1289 * @param table an update on this table will trigger a sync time removal
1290 * @param foreignKey this is the column in table whose value is an _id in
1291 * updateTable
1292 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -07001293 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 */
Vasu Nori95675132010-07-21 16:24:40 -07001295 @Deprecated
1296 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
1298
1299 /**
1300 * Finds the name of the first table, which is editable.
1301 *
1302 * @param tables a list of tables
1303 * @return the first table listed
1304 */
1305 public static String findEditTable(String tables) {
1306 if (!TextUtils.isEmpty(tables)) {
1307 // find the first word terminated by either a space or a comma
1308 int spacepos = tables.indexOf(' ');
1309 int commapos = tables.indexOf(',');
1310
1311 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
1312 return tables.substring(0, spacepos);
1313 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
1314 return tables.substring(0, commapos);
1315 }
1316 return tables;
1317 } else {
1318 throw new IllegalStateException("Invalid tables");
1319 }
1320 }
1321
1322 /**
1323 * Compiles an SQL statement into a reusable pre-compiled statement object.
1324 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
1325 * statement and fill in those values with {@link SQLiteProgram#bindString}
1326 * and {@link SQLiteProgram#bindLong} each time you want to run the
1327 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -07001328 *<p>
1329 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 *
1331 * @param sql The raw SQL statement, may contain ? for unknown values to be
1332 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001333 * @return A pre-compiled {@link SQLiteStatement} object. Note that
1334 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 */
1336 public SQLiteStatement compileStatement(String sql) throws SQLException {
Vasu Noriccd95442010-05-28 17:04:16 -07001337 verifyDbIsOpen();
Vasu Nori0732f792010-07-29 17:24:12 -07001338 return new SQLiteStatement(this, sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
1341 /**
1342 * Query the given URL, returning a {@link Cursor} over the result set.
1343 *
1344 * @param distinct true if you want each row to be unique, false otherwise.
1345 * @param table The table name to compile the query against.
1346 * @param columns A list of which columns to return. Passing null will
1347 * return all columns, which is discouraged to prevent reading
1348 * data from storage that isn't going to be used.
1349 * @param selection A filter declaring which rows to return, formatted as an
1350 * SQL WHERE clause (excluding the WHERE itself). Passing null
1351 * will return all rows for the given table.
1352 * @param selectionArgs You may include ?s in selection, which will be
1353 * replaced by the values from selectionArgs, in order that they
1354 * appear in the selection. The values will be bound as Strings.
1355 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1356 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1357 * will cause the rows to not be grouped.
1358 * @param having A filter declare which row groups to include in the cursor,
1359 * if row grouping is being used, formatted as an SQL HAVING
1360 * clause (excluding the HAVING itself). Passing null will cause
1361 * all row groups to be included, and is required when row
1362 * grouping is not being used.
1363 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1364 * (excluding the ORDER BY itself). Passing null will use the
1365 * default sort order, which may be unordered.
1366 * @param limit Limits the number of rows returned by the query,
1367 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001368 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1369 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 * @see Cursor
1371 */
1372 public Cursor query(boolean distinct, String table, String[] columns,
1373 String selection, String[] selectionArgs, String groupBy,
1374 String having, String orderBy, String limit) {
1375 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
1376 groupBy, having, orderBy, limit);
1377 }
1378
1379 /**
1380 * Query the given URL, returning a {@link Cursor} over the result set.
1381 *
1382 * @param cursorFactory the cursor factory to use, or null for the default factory
1383 * @param distinct true if you want each row to be unique, false otherwise.
1384 * @param table The table name to compile the query against.
1385 * @param columns A list of which columns to return. Passing null will
1386 * return all columns, which is discouraged to prevent reading
1387 * data from storage that isn't going to be used.
1388 * @param selection A filter declaring which rows to return, formatted as an
1389 * SQL WHERE clause (excluding the WHERE itself). Passing null
1390 * will return all rows for the given table.
1391 * @param selectionArgs You may include ?s in selection, which will be
1392 * replaced by the values from selectionArgs, in order that they
1393 * appear in the selection. The values will be bound as Strings.
1394 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1395 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1396 * will cause the rows to not be grouped.
1397 * @param having A filter declare which row groups to include in the cursor,
1398 * if row grouping is being used, formatted as an SQL HAVING
1399 * clause (excluding the HAVING itself). Passing null will cause
1400 * all row groups to be included, and is required when row
1401 * grouping is not being used.
1402 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1403 * (excluding the ORDER BY itself). Passing null will use the
1404 * default sort order, which may be unordered.
1405 * @param limit Limits the number of rows returned by the query,
1406 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001407 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1408 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * @see Cursor
1410 */
1411 public Cursor queryWithFactory(CursorFactory cursorFactory,
1412 boolean distinct, String table, String[] columns,
1413 String selection, String[] selectionArgs, String groupBy,
1414 String having, String orderBy, String limit) {
Vasu Noriccd95442010-05-28 17:04:16 -07001415 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 String sql = SQLiteQueryBuilder.buildQueryString(
1417 distinct, table, columns, selection, groupBy, having, orderBy, limit);
1418
1419 return rawQueryWithFactory(
1420 cursorFactory, sql, selectionArgs, findEditTable(table));
1421 }
1422
1423 /**
1424 * Query the given table, returning a {@link Cursor} over the result set.
1425 *
1426 * @param table The table name to compile the query against.
1427 * @param columns A list of which columns to return. Passing null will
1428 * return all columns, which is discouraged to prevent reading
1429 * data from storage that isn't going to be used.
1430 * @param selection A filter declaring which rows to return, formatted as an
1431 * SQL WHERE clause (excluding the WHERE itself). Passing null
1432 * will return all rows for the given table.
1433 * @param selectionArgs You may include ?s in selection, which will be
1434 * replaced by the values from selectionArgs, in order that they
1435 * appear in the selection. The values will be bound as Strings.
1436 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1437 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1438 * will cause the rows to not be grouped.
1439 * @param having A filter declare which row groups to include in the cursor,
1440 * if row grouping is being used, formatted as an SQL HAVING
1441 * clause (excluding the HAVING itself). Passing null will cause
1442 * all row groups to be included, and is required when row
1443 * grouping is not being used.
1444 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1445 * (excluding the ORDER BY itself). Passing null will use the
1446 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001447 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1448 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 * @see Cursor
1450 */
1451 public Cursor query(String table, String[] columns, String selection,
1452 String[] selectionArgs, String groupBy, String having,
1453 String orderBy) {
1454
1455 return query(false, table, columns, selection, selectionArgs, groupBy,
1456 having, orderBy, null /* limit */);
1457 }
1458
1459 /**
1460 * Query the given table, returning a {@link Cursor} over the result set.
1461 *
1462 * @param table The table name to compile the query against.
1463 * @param columns A list of which columns to return. Passing null will
1464 * return all columns, which is discouraged to prevent reading
1465 * data from storage that isn't going to be used.
1466 * @param selection A filter declaring which rows to return, formatted as an
1467 * SQL WHERE clause (excluding the WHERE itself). Passing null
1468 * will return all rows for the given table.
1469 * @param selectionArgs You may include ?s in selection, which will be
1470 * replaced by the values from selectionArgs, in order that they
1471 * appear in the selection. The values will be bound as Strings.
1472 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1473 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1474 * will cause the rows to not be grouped.
1475 * @param having A filter declare which row groups to include in the cursor,
1476 * if row grouping is being used, formatted as an SQL HAVING
1477 * clause (excluding the HAVING itself). Passing null will cause
1478 * all row groups to be included, and is required when row
1479 * grouping is not being used.
1480 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1481 * (excluding the ORDER BY itself). Passing null will use the
1482 * default sort order, which may be unordered.
1483 * @param limit Limits the number of rows returned by the query,
1484 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001485 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1486 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 * @see Cursor
1488 */
1489 public Cursor query(String table, String[] columns, String selection,
1490 String[] selectionArgs, String groupBy, String having,
1491 String orderBy, String limit) {
1492
1493 return query(false, table, columns, selection, selectionArgs, groupBy,
1494 having, orderBy, limit);
1495 }
1496
1497 /**
1498 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1499 *
1500 * @param sql the SQL query. The SQL string must not be ; terminated
1501 * @param selectionArgs You may include ?s in where clause in the query,
1502 * which will be replaced by the values from selectionArgs. The
1503 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001504 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1505 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 */
1507 public Cursor rawQuery(String sql, String[] selectionArgs) {
1508 return rawQueryWithFactory(null, sql, selectionArgs, null);
1509 }
1510
1511 /**
1512 * Runs the provided SQL and returns a cursor over the result set.
1513 *
1514 * @param cursorFactory the cursor factory to use, or null for the default factory
1515 * @param sql the SQL query. The SQL string must not be ; terminated
1516 * @param selectionArgs You may include ?s in where clause in the query,
1517 * which will be replaced by the values from selectionArgs. The
1518 * values will be bound as Strings.
1519 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001520 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1521 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 */
1523 public Cursor rawQueryWithFactory(
1524 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1525 String editTable) {
Vasu Noriccd95442010-05-28 17:04:16 -07001526 verifyDbIsOpen();
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -07001527 BlockGuard.getThreadPolicy().onReadFromDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 long timeStart = 0;
1529
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001530 if (Config.LOGV || mSlowQueryThreshold != -1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 timeStart = System.currentTimeMillis();
1532 }
1533
Vasu Nori6c354da2010-04-26 23:33:39 -07001534 SQLiteDatabase db = getDbConnection(sql);
1535 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001537 Cursor cursor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 try {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001539 cursor = driver.query(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 cursorFactory != null ? cursorFactory : mFactory,
1541 selectionArgs);
1542 } finally {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001543 if (Config.LOGV || mSlowQueryThreshold != -1) {
1544
Vasu Nori020e5342010-04-28 14:22:38 -07001545 // Force query execution
1546 int count = -1;
1547 if (cursor != null) {
1548 count = cursor.getCount();
1549 }
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 long duration = System.currentTimeMillis() - timeStart;
1552
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001553 if (Config.LOGV || duration >= mSlowQueryThreshold) {
1554 Log.v(SQLiteCursor.TAG,
1555 "query (" + duration + " ms): " + driver.toString() + ", args are "
1556 + (selectionArgs != null
1557 ? TextUtils.join(",", selectionArgs)
Vasu Nori020e5342010-04-28 14:22:38 -07001558 : "<null>") + ", count is " + count);
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001561 releaseDbConnection(db);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001563 return cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
1566 /**
1567 * Runs the provided SQL and returns a cursor over the result set.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001568 * The cursor will read an initial set of rows and the return to the caller.
1569 * It will continue to read in batches and send data changed notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 * when the later batches are ready.
1571 * @param sql the SQL query. The SQL string must not be ; terminated
1572 * @param selectionArgs You may include ?s in where clause in the query,
1573 * which will be replaced by the values from selectionArgs. The
1574 * values will be bound as Strings.
1575 * @param initialRead set the initial count of items to read from the cursor
1576 * @param maxRead set the count of items to read on each iteration after the first
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001577 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1578 * {@link Cursor}s are not synchronized, see the documentation for more details.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001579 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001580 * This work is incomplete and not fully tested or reviewed, so currently
1581 * hidden.
1582 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001584 public Cursor rawQuery(String sql, String[] selectionArgs,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 int initialRead, int maxRead) {
1586 SQLiteCursor c = (SQLiteCursor)rawQueryWithFactory(
1587 null, sql, selectionArgs, null);
1588 c.setLoadStyle(initialRead, maxRead);
1589 return c;
1590 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 /**
1593 * Convenience method for inserting a row into the database.
1594 *
1595 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001596 * @param nullColumnHack optional; may be <code>null</code>.
1597 * SQL doesn't allow inserting a completely empty row without
1598 * naming at least one column name. If your provided <code>values</code> is
1599 * empty, no column names are known and an empty row can't be inserted.
1600 * If not set to null, the <code>nullColumnHack</code> parameter
1601 * provides the name of nullable column name to explicitly insert a NULL into
1602 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 * @param values this map contains the initial column values for the
1604 * row. The keys should be the column names and the values the
1605 * column values
1606 * @return the row ID of the newly inserted row, or -1 if an error occurred
1607 */
1608 public long insert(String table, String nullColumnHack, ContentValues values) {
1609 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001610 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 } catch (SQLException e) {
1612 Log.e(TAG, "Error inserting " + values, e);
1613 return -1;
1614 }
1615 }
1616
1617 /**
1618 * Convenience method for inserting a row into the database.
1619 *
1620 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001621 * @param nullColumnHack optional; may be <code>null</code>.
1622 * SQL doesn't allow inserting a completely empty row without
1623 * naming at least one column name. If your provided <code>values</code> is
1624 * empty, no column names are known and an empty row can't be inserted.
1625 * If not set to null, the <code>nullColumnHack</code> parameter
1626 * provides the name of nullable column name to explicitly insert a NULL into
1627 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 * @param values this map contains the initial column values for the
1629 * row. The keys should be the column names and the values the
1630 * column values
1631 * @throws SQLException
1632 * @return the row ID of the newly inserted row, or -1 if an error occurred
1633 */
1634 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1635 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001636 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
1639 /**
1640 * Convenience method for replacing a row in the database.
1641 *
1642 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001643 * @param nullColumnHack optional; may be <code>null</code>.
1644 * SQL doesn't allow inserting a completely empty row without
1645 * naming at least one column name. If your provided <code>initialValues</code> is
1646 * empty, no column names are known and an empty row can't be inserted.
1647 * If not set to null, the <code>nullColumnHack</code> parameter
1648 * provides the name of nullable column name to explicitly insert a NULL into
1649 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001651 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 * @return the row ID of the newly inserted row, or -1 if an error occurred
1653 */
1654 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1655 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001656 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001657 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 } catch (SQLException e) {
1659 Log.e(TAG, "Error inserting " + initialValues, e);
1660 return -1;
1661 }
1662 }
1663
1664 /**
1665 * Convenience method for replacing a row in the database.
1666 *
1667 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001668 * @param nullColumnHack optional; may be <code>null</code>.
1669 * SQL doesn't allow inserting a completely empty row without
1670 * naming at least one column name. If your provided <code>initialValues</code> is
1671 * empty, no column names are known and an empty row can't be inserted.
1672 * If not set to null, the <code>nullColumnHack</code> parameter
1673 * provides the name of nullable column name to explicitly insert a NULL into
1674 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 * @param initialValues this map contains the initial column values for
1676 * the row. The key
1677 * @throws SQLException
1678 * @return the row ID of the newly inserted row, or -1 if an error occurred
1679 */
1680 public long replaceOrThrow(String table, String nullColumnHack,
1681 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001682 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001683 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685
1686 /**
1687 * General method for inserting a row into the database.
1688 *
1689 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001690 * @param nullColumnHack optional; may be <code>null</code>.
1691 * SQL doesn't allow inserting a completely empty row without
1692 * naming at least one column name. If your provided <code>initialValues</code> is
1693 * empty, no column names are known and an empty row can't be inserted.
1694 * If not set to null, the <code>nullColumnHack</code> parameter
1695 * provides the name of nullable column name to explicitly insert a NULL into
1696 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 * @param initialValues this map contains the initial column values for the
1698 * row. The keys should be the column names and the values the
1699 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001700 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001701 * @return the row ID of the newly inserted row
1702 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001703 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001704 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 */
1706 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001707 ContentValues initialValues, int conflictAlgorithm) {
Vasu Nori0732f792010-07-29 17:24:12 -07001708 StringBuilder sql = new StringBuilder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001710 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 sql.append(" INTO ");
1712 sql.append(table);
Vasu Nori0732f792010-07-29 17:24:12 -07001713 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714
Vasu Nori0732f792010-07-29 17:24:12 -07001715 Object[] bindArgs = null;
1716 int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
1717 if (size > 0) {
1718 bindArgs = new Object[size];
1719 int i = 0;
1720 for (String colName : initialValues.keySet()) {
1721 sql.append((i > 0) ? "," : "");
1722 sql.append(colName);
1723 bindArgs[i++] = initialValues.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 sql.append(')');
Vasu Nori0732f792010-07-29 17:24:12 -07001726 sql.append(" VALUES (");
1727 for (i = 0; i < size; i++) {
1728 sql.append((i > 0) ? ",?" : "?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
Vasu Nori0732f792010-07-29 17:24:12 -07001730 } else {
1731 sql.append(nullColumnHack + ") VALUES (NULL");
1732 }
1733 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734
Vasu Nori0732f792010-07-29 17:24:12 -07001735 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1736 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001737 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 } catch (SQLiteDatabaseCorruptException e) {
1739 onCorruption();
1740 throw e;
1741 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001742 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744 }
1745
1746 /**
1747 * Convenience method for deleting rows in the database.
1748 *
1749 * @param table the table to delete from
1750 * @param whereClause the optional WHERE clause to apply when deleting.
1751 * Passing null will delete all rows.
1752 * @return the number of rows affected if a whereClause is passed in, 0
1753 * otherwise. To remove all rows and get a count pass "1" as the
1754 * whereClause.
1755 */
1756 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Nori0732f792010-07-29 17:24:12 -07001757 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1758 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001760 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 } catch (SQLiteDatabaseCorruptException e) {
1762 onCorruption();
1763 throw e;
1764 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001765 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 }
1768
1769 /**
1770 * Convenience method for updating rows in the database.
1771 *
1772 * @param table the table to update in
1773 * @param values a map from column names to new column values. null is a
1774 * valid value that will be translated to NULL.
1775 * @param whereClause the optional WHERE clause to apply when updating.
1776 * Passing null will update all rows.
1777 * @return the number of rows affected
1778 */
1779 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001780 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 /**
1784 * Convenience method for updating rows in the database.
1785 *
1786 * @param table the table to update in
1787 * @param values a map from column names to new column values. null is a
1788 * valid value that will be translated to NULL.
1789 * @param whereClause the optional WHERE clause to apply when updating.
1790 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001791 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001794 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001795 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001796 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 throw new IllegalArgumentException("Empty values");
1798 }
1799
1800 StringBuilder sql = new StringBuilder(120);
1801 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001802 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 sql.append(table);
1804 sql.append(" SET ");
1805
Vasu Nori0732f792010-07-29 17:24:12 -07001806 // move all bind args to one array
Brian Muramatsu46a88512010-11-12 13:53:57 -08001807 int setValuesSize = values.size();
Vasu Nori0732f792010-07-29 17:24:12 -07001808 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1809 Object[] bindArgs = new Object[bindArgsSize];
1810 int i = 0;
1811 for (String colName : values.keySet()) {
1812 sql.append((i > 0) ? "," : "");
1813 sql.append(colName);
1814 bindArgs[i++] = values.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 sql.append("=?");
Vasu Nori0732f792010-07-29 17:24:12 -07001816 }
1817 if (whereArgs != null) {
1818 for (i = setValuesSize; i < bindArgsSize; i++) {
1819 bindArgs[i] = whereArgs[i - setValuesSize];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (!TextUtils.isEmpty(whereClause)) {
1823 sql.append(" WHERE ");
1824 sql.append(whereClause);
1825 }
1826
Vasu Nori0732f792010-07-29 17:24:12 -07001827 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001829 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 } catch (SQLiteDatabaseCorruptException e) {
1831 onCorruption();
1832 throw e;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001834 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 }
1837
1838 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001839 * Execute a single SQL statement that is NOT a SELECT
1840 * or any other SQL statement that returns data.
1841 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001842 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001843 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1844 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1845 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001846 * <p>
1847 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1848 * automatically managed by this class. So, do not set journal_mode
1849 * using "PRAGMA journal_mode'<value>" statement if your app is using
1850 * {@link #enableWriteAheadLogging()}
1851 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 *
Vasu Noriccd95442010-05-28 17:04:16 -07001853 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1854 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001855 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001857 public void execSQL(String sql) throws SQLException {
Vasu Norice38b982010-07-22 13:57:13 -07001858 int stmtType = DatabaseUtils.getSqlStatementType(sql);
1859 if (stmtType == DatabaseUtils.STATEMENT_ATTACH) {
Vasu Nori8d111032010-06-22 18:34:21 -07001860 disableWriteAheadLogging();
1861 }
Vasu Noric8e1f232010-04-13 15:05:09 -07001862 long timeStart = SystemClock.uptimeMillis();
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001863 logTimeStat(mLastSqlStatement, timeStart, GET_LOCK_LOG_PREFIX);
Vasu Norib83cb7c2010-09-14 13:36:01 -07001864 executeSql(sql, null);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001865
Vasu Nori24675612010-09-27 14:54:19 -07001866 if (stmtType == DatabaseUtils.STATEMENT_ATTACH) {
1867 mHasAttachedDbs = true;
1868 }
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001869 // Log commit statements along with the most recently executed
Vasu Norice38b982010-07-22 13:57:13 -07001870 // SQL statement for disambiguation.
1871 if (stmtType == DatabaseUtils.STATEMENT_COMMIT) {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001872 logTimeStat(mLastSqlStatement, timeStart, COMMIT_SQL);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001873 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001874 logTimeStat(sql, timeStart, null);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877
1878 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001879 * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
1880 * <p>
1881 * For INSERT statements, use any of the following instead.
1882 * <ul>
1883 * <li>{@link #insert(String, String, ContentValues)}</li>
1884 * <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
1885 * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
1886 * </ul>
1887 * <p>
1888 * For UPDATE statements, use any of the following instead.
1889 * <ul>
1890 * <li>{@link #update(String, ContentValues, String, String[])}</li>
1891 * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
1892 * </ul>
1893 * <p>
1894 * For DELETE statements, use any of the following instead.
1895 * <ul>
1896 * <li>{@link #delete(String, String, String[])}</li>
1897 * </ul>
1898 * <p>
1899 * For example, the following are good candidates for using this method:
1900 * <ul>
1901 * <li>ALTER TABLE</li>
1902 * <li>CREATE or DROP table / trigger / view / index / virtual table</li>
1903 * <li>REINDEX</li>
1904 * <li>RELEASE</li>
1905 * <li>SAVEPOINT</li>
1906 * <li>PRAGMA that returns no data</li>
1907 * </ul>
1908 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001909 * <p>
1910 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1911 * automatically managed by this class. So, do not set journal_mode
1912 * using "PRAGMA journal_mode'<value>" statement if your app is using
1913 * {@link #enableWriteAheadLogging()}
1914 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 *
Vasu Noriccd95442010-05-28 17:04:16 -07001916 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1917 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001919 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001921 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 if (bindArgs == null) {
1923 throw new IllegalArgumentException("Empty bindArgs");
1924 }
Vasu Norib83cb7c2010-09-14 13:36:01 -07001925 executeSql(sql, bindArgs);
Vasu Norice38b982010-07-22 13:57:13 -07001926 }
1927
Vasu Nori54025902010-09-14 12:14:26 -07001928 private int executeSql(String sql, Object[] bindArgs) throws SQLException {
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08001929 long timeStart = SystemClock.uptimeMillis();
Vasu Nori54025902010-09-14 12:14:26 -07001930 int n;
Vasu Nori0732f792010-07-29 17:24:12 -07001931 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 try {
Vasu Nori54025902010-09-14 12:14:26 -07001933 n = statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 } catch (SQLiteDatabaseCorruptException e) {
1935 onCorruption();
1936 throw e;
1937 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001938 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
Dan Egnor12311952009-11-23 14:47:45 -08001940 logTimeStat(sql, timeStart);
Vasu Nori54025902010-09-14 12:14:26 -07001941 return n;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
1943
1944 @Override
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001945 protected void finalize() throws Throwable {
1946 try {
1947 if (isOpen()) {
1948 Log.e(TAG, "close() was never explicitly called on database '" +
1949 mPath + "' ", mStackTrace);
1950 closeClosable();
1951 onAllReferencesReleased();
1952 releaseCustomFunctions();
1953 }
1954 } finally {
1955 super.finalize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 }
1958
1959 /**
Vasu Nori21343692010-06-03 16:01:39 -07001960 * Private constructor.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 *
1962 * @param path The full path to the database
1963 * @param factory The factory to use when creating cursors, may be NULL.
1964 * @param flags 0 or {@link #NO_LOCALIZED_COLLATORS}. If the database file already
1965 * exists, mFlags will be updated appropriately.
Vasu Nori21343692010-06-03 16:01:39 -07001966 * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite reports database
1967 * corruption. may be NULL.
Vasu Nori6c354da2010-04-26 23:33:39 -07001968 * @param connectionNum 0 for main database connection handle. 1..N for pooled database
1969 * connection handles.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 */
Vasu Nori21343692010-06-03 16:01:39 -07001971 private SQLiteDatabase(String path, CursorFactory factory, int flags,
Vasu Nori6c354da2010-04-26 23:33:39 -07001972 DatabaseErrorHandler errorHandler, short connectionNum) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 if (path == null) {
1974 throw new IllegalArgumentException("path should not be null");
1975 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001976 setMaxSqlCacheSize(DEFAULT_SQL_CACHE_SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 mFlags = flags;
1978 mPath = path;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001979 mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1);
Vasu Nori08b448e2010-03-03 10:05:16 -08001980 mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 mFactory = factory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 mPrograms = new WeakHashMap<SQLiteClosable,Object>();
Vasu Nori21343692010-06-03 16:01:39 -07001983 // Set the DatabaseErrorHandler to be used when SQLite reports corruption.
1984 // If the caller sets errorHandler = null, then use default errorhandler.
1985 mErrorHandler = (errorHandler == null) ? new DefaultDatabaseErrorHandler() : errorHandler;
Vasu Nori6c354da2010-04-26 23:33:39 -07001986 mConnectionNum = connectionNum;
Vasu Nori34ad57f02010-12-21 09:32:36 -08001987 /* sqlite soft heap limit http://www.sqlite.org/c3ref/soft_heap_limit64.html
1988 * set it to 4 times the default cursor window size.
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001989 * TODO what is an appropriate value, considering the WAL feature which could burn
Vasu Nori34ad57f02010-12-21 09:32:36 -08001990 * a lot of memory with many connections to the database. needs testing to figure out
1991 * optimal value for this.
1992 */
1993 int limit = Resources.getSystem().getInteger(
1994 com.android.internal.R.integer.config_cursorWindowSize) * 1024 * 4;
1995 native_setSqliteSoftHeapLimit(limit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
1998 /**
1999 * return whether the DB is opened as read only.
2000 * @return true if DB is opened as read only
2001 */
2002 public boolean isReadOnly() {
2003 return (mFlags & OPEN_READ_MASK) == OPEN_READONLY;
2004 }
2005
2006 /**
2007 * @return true if the DB is currently open (has not been closed)
2008 */
2009 public boolean isOpen() {
2010 return mNativeHandle != 0;
2011 }
2012
2013 public boolean needUpgrade(int newVersion) {
2014 return newVersion > getVersion();
2015 }
2016
2017 /**
2018 * Getter for the path to the database file.
2019 *
2020 * @return the path to our database file.
2021 */
2022 public final String getPath() {
2023 return mPath;
2024 }
2025
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002026 /* package */ void logTimeStat(String sql, long beginMillis) {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002027 logTimeStat(sql, beginMillis, null);
2028 }
2029
2030 /* package */ void logTimeStat(String sql, long beginMillis, String prefix) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08002031 // Keep track of the last statement executed here, as this is
2032 // the common funnel through which all methods of hitting
2033 // libsqlite eventually flow.
2034 mLastSqlStatement = sql;
2035
Dan Egnor12311952009-11-23 14:47:45 -08002036 // Sample fast queries in proportion to the time taken.
2037 // Quantize the % first, so the logged sampling probability
2038 // exactly equals the actual sampling rate for this query.
2039
2040 int samplePercent;
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002041 long durationMillis = SystemClock.uptimeMillis() - beginMillis;
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002042 if (durationMillis == 0 && prefix == GET_LOCK_LOG_PREFIX) {
2043 // The common case is locks being uncontended. Don't log those,
2044 // even at 1%, which is our default below.
2045 return;
2046 }
2047 if (sQueryLogTimeInMillis == 0) {
2048 sQueryLogTimeInMillis = SystemProperties.getInt("db.db_operation.threshold_ms", 500);
2049 }
2050 if (durationMillis >= sQueryLogTimeInMillis) {
Dan Egnor12311952009-11-23 14:47:45 -08002051 samplePercent = 100;
Vasu Norifb16cbd2010-07-25 16:38:48 -07002052 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002053 samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1;
Dan Egnor799f7212009-11-24 16:24:44 -08002054 if (mRandom.nextInt(100) >= samplePercent) return;
Dan Egnor12311952009-11-23 14:47:45 -08002055 }
2056
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002057 // Note: the prefix will be "COMMIT;" or "GETLOCK:" when non-null. We wait to do
2058 // it here so we avoid allocating in the common case.
2059 if (prefix != null) {
2060 sql = prefix + sql;
2061 }
2062
Dan Egnor12311952009-11-23 14:47:45 -08002063 if (sql.length() > QUERY_LOG_SQL_LENGTH) sql = sql.substring(0, QUERY_LOG_SQL_LENGTH);
2064
2065 // ActivityThread.currentPackageName() only returns non-null if the
2066 // current thread is an application main thread. This parameter tells
2067 // us whether an event loop is blocked, and if so, which app it is.
2068 //
2069 // Sadly, there's no fast way to determine app name if this is *not* a
2070 // main thread, or when we are invoked via Binder (e.g. ContentProvider).
2071 // Hopefully the full path to the database will be informative enough.
2072
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002073 String blockingPackage = AppGlobals.getInitialPackage();
Dan Egnor12311952009-11-23 14:47:45 -08002074 if (blockingPackage == null) blockingPackage = "";
2075
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002076 EventLog.writeEvent(
Brad Fitzpatrickd8330232010-02-19 10:59:01 -08002077 EVENT_DB_OPERATION,
2078 getPathForLogs(),
2079 sql,
2080 durationMillis,
2081 blockingPackage,
2082 samplePercent);
2083 }
2084
2085 /**
2086 * Removes email addresses from database filenames before they're
2087 * logged to the EventLog where otherwise apps could potentially
2088 * read them.
2089 */
2090 private String getPathForLogs() {
2091 if (mPathForLogs != null) {
2092 return mPathForLogs;
2093 }
2094 if (mPath == null) {
2095 return null;
2096 }
2097 if (mPath.indexOf('@') == -1) {
2098 mPathForLogs = mPath;
2099 } else {
2100 mPathForLogs = EMAIL_IN_DB_PATTERN.matcher(mPath).replaceAll("XX@YY");
2101 }
2102 return mPathForLogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 }
2104
2105 /**
2106 * Sets the locale for this database. Does nothing if this database has
2107 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
2108 * @throws SQLException if the locale could not be set. The most common reason
2109 * for this is that there is no collator available for the locale you requested.
2110 * In this case the database remains unchanged.
2111 */
2112 public void setLocale(Locale locale) {
2113 lock();
2114 try {
2115 native_setLocale(locale.toString(), mFlags);
2116 } finally {
2117 unlock();
2118 }
2119 }
2120
Vasu Noriccd95442010-05-28 17:04:16 -07002121 /* package */ void verifyDbIsOpen() {
Vasu Nori9463f292010-04-30 12:22:18 -07002122 if (!isOpen()) {
Vasu Nori75010102010-07-01 16:23:06 -07002123 throw new IllegalStateException("database " + getPath() + " (conn# " +
2124 mConnectionNum + ") already closed");
Vasu Nori9463f292010-04-30 12:22:18 -07002125 }
Vasu Noriccd95442010-05-28 17:04:16 -07002126 }
2127
2128 /* package */ void verifyLockOwner() {
2129 verifyDbIsOpen();
2130 if (mLockingEnabled && !isDbLockedByCurrentThread()) {
Vasu Nori9463f292010-04-30 12:22:18 -07002131 throw new IllegalStateException("Don't have database lock!");
2132 }
2133 }
2134
Vasu Norib729dcc2010-09-14 11:35:49 -07002135 /**
2136 * Adds the given SQL and its compiled-statement-id-returned-by-sqlite to the
2137 * cache of compiledQueries attached to 'this'.
2138 * <p>
2139 * If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL,
2140 * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current
2141 * mapping is NOT replaced with the new mapping).
2142 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002143 /* package */ synchronized void addToCompiledQueries(
2144 String sql, SQLiteCompiledSql compiledStatement) {
2145 // don't insert the new mapping if a mapping already exists
2146 if (mCompiledQueries.get(sql) != null) {
2147 return;
2148 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002149
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002150 int maxCacheSz = (mConnectionNum == 0) ? mCompiledQueries.maxSize() :
2151 mParentConnObj.mCompiledQueries.maxSize();
Brian Muramatsu46a88512010-11-12 13:53:57 -08002152
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002153 if (SQLiteDebug.DEBUG_SQL_CACHE) {
2154 boolean printWarning = (mConnectionNum == 0)
2155 ? (!mCacheFullWarning && mCompiledQueries.size() == maxCacheSz)
2156 : (!mParentConnObj.mCacheFullWarning &&
2157 mParentConnObj.mCompiledQueries.size() == maxCacheSz);
2158 if (printWarning) {
2159 /*
2160 * cache size is not enough for this app. log a warning.
2161 * chances are it is NOT using ? for bindargs - or cachesize is too small.
2162 */
2163 Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
2164 getPath() + ". Use setMaxSqlCacheSize() to increase cachesize. ");
2165 mCacheFullWarning = true;
2166 Log.d(TAG, "Here are the SQL statements in Cache of database: " + mPath);
2167 for (String s : mCompiledQueries.snapshot().keySet()) {
2168 Log.d(TAG, "Sql statement in Cache: " + s);
Vasu Nori74fb2682010-10-25 11:48:24 -07002169 }
Vasu Nori7301a232010-11-05 11:46:15 -07002170 }
Vasu Norib729dcc2010-09-14 11:35:49 -07002171 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002172 /* add the given SQLiteCompiledSql compiledStatement to cache.
2173 * no need to worry about the cache size - because {@link #mCompiledQueries}
2174 * self-limits its size.
2175 */
2176 mCompiledQueries.put(sql, compiledStatement);
Vasu Norib729dcc2010-09-14 11:35:49 -07002177 }
2178
2179 /** package-level access for testing purposes */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002180 /* package */ synchronized void deallocCachedSqlStatements() {
2181 for (SQLiteCompiledSql compiledSql : mCompiledQueries.snapshot().values()) {
2182 compiledSql.releaseSqlStatement();
Vasu Norib729dcc2010-09-14 11:35:49 -07002183 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002184 mCompiledQueries.evictAll();
Vasu Norib729dcc2010-09-14 11:35:49 -07002185 }
2186
2187 /**
2188 * From the compiledQueries cache, returns the compiled-statement-id for the given SQL.
2189 * Returns null, if not found in the cache.
2190 */
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002191 /* package */ synchronized SQLiteCompiledSql getCompiledStatementForSql(String sql) {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002192 return mCompiledQueries.get(sql);
Vasu Norib729dcc2010-09-14 11:35:49 -07002193 }
2194
Vasu Norie495d1f2010-01-06 16:34:19 -08002195 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002196 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08002197 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07002198 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07002199 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07002200 * If this method is called with smaller size than the current maximum value,
2201 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07002202 *<p>
2203 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08002204 *
Vasu Nori90a367262010-04-12 12:49:09 -07002205 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
2206 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or
Vasu Noribfe1dc22010-08-25 16:29:02 -07002207 * the value set with previous setMaxSqlCacheSize() call.
Vasu Norie495d1f2010-01-06 16:34:19 -08002208 */
Vasu Nori54025902010-09-14 12:14:26 -07002209 public void setMaxSqlCacheSize(int cacheSize) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002210 synchronized (this) {
2211 LruCache<String, SQLiteCompiledSql> oldCompiledQueries = mCompiledQueries;
Vasu Nori54025902010-09-14 12:14:26 -07002212 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002213 throw new IllegalStateException(
2214 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
2215 } else if (oldCompiledQueries != null && cacheSize < oldCompiledQueries.maxSize()) {
2216 throw new IllegalStateException("cannot set cacheSize to a value less than the "
2217 + "value set with previous setMaxSqlCacheSize() call.");
Vasu Nori54025902010-09-14 12:14:26 -07002218 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002219 mCompiledQueries = new LruCache<String, SQLiteCompiledSql>(cacheSize) {
2220 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08002221 protected void entryRemoved(boolean evicted, String key, SQLiteCompiledSql oldValue,
2222 SQLiteCompiledSql newValue) {
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002223 verifyLockOwner();
Jesse Wilson32c80a22011-02-25 17:28:41 -08002224 oldValue.releaseIfNotInUse();
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002225 }
2226 };
2227 if (oldCompiledQueries != null) {
2228 for (Map.Entry<String, SQLiteCompiledSql> entry
2229 : oldCompiledQueries.snapshot().entrySet()) {
2230 mCompiledQueries.put(entry.getKey(), entry.getValue());
2231 }
Vasu Nori24675612010-09-27 14:54:19 -07002232 }
Vasu Nori587423a2010-09-27 18:18:34 -07002233 }
2234 }
2235
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002236 /* package */ synchronized boolean isInStatementCache(String sql) {
2237 return mCompiledQueries.get(sql) != null;
2238 }
2239
2240 /* package */ synchronized void releaseCompiledSqlObj(
2241 String sql, SQLiteCompiledSql compiledSql) {
2242 if (mCompiledQueries.get(sql) == compiledSql) {
2243 // it is in cache - reset its inUse flag
2244 compiledSql.release();
2245 } else {
2246 // it is NOT in cache. finalize it.
2247 compiledSql.releaseSqlStatement();
2248 }
2249 }
2250
2251 private synchronized int getCacheHitNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002252 return mCompiledQueries.hitCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002253 }
2254
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002255 private synchronized int getCacheMissNum() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002256 return mCompiledQueries.missCount();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002257 }
2258
Jesse Wilsondfe515e2011-02-10 19:06:09 -08002259 private synchronized int getCachesize() {
Jesse Wilson9b5a9352011-02-10 11:19:09 -08002260 return mCompiledQueries.size();
Vasu Nori5e89ae22010-09-15 14:23:29 -07002261 }
2262
Vasu Nori6f37f832010-05-19 11:53:25 -07002263 /* package */ void finalizeStatementLater(int id) {
2264 if (!isOpen()) {
2265 // database already closed. this statement will already have been finalized.
2266 return;
2267 }
2268 synchronized(mClosedStatementIds) {
2269 if (mClosedStatementIds.contains(id)) {
2270 // this statement id is already queued up for finalization.
2271 return;
2272 }
2273 mClosedStatementIds.add(id);
2274 }
2275 }
2276
Vasu Nori83ff97d2011-01-30 12:47:55 -08002277 /* package */ boolean isInQueueOfStatementsToBeFinalized(int id) {
2278 if (!isOpen()) {
2279 // database already closed. this statement will already have been finalized.
2280 // return true so that the caller doesn't have to worry about finalizing this statement.
2281 return true;
2282 }
2283 synchronized(mClosedStatementIds) {
2284 return mClosedStatementIds.contains(id);
2285 }
2286 }
2287
Vasu Norice38b982010-07-22 13:57:13 -07002288 /* package */ void closePendingStatements() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002289 if (!isOpen()) {
2290 // since this database is already closed, no need to finalize anything.
2291 mClosedStatementIds.clear();
2292 return;
2293 }
2294 verifyLockOwner();
2295 /* to minimize synchronization on mClosedStatementIds, make a copy of the list */
2296 ArrayList<Integer> list = new ArrayList<Integer>(mClosedStatementIds.size());
2297 synchronized(mClosedStatementIds) {
2298 list.addAll(mClosedStatementIds);
2299 mClosedStatementIds.clear();
2300 }
2301 // finalize all the statements from the copied list
2302 int size = list.size();
2303 for (int i = 0; i < size; i++) {
2304 native_finalize(list.get(i));
2305 }
2306 }
2307
2308 /**
2309 * for testing only
Vasu Nori6f37f832010-05-19 11:53:25 -07002310 */
Vasu Norice38b982010-07-22 13:57:13 -07002311 /* package */ ArrayList<Integer> getQueuedUpStmtList() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002312 return mClosedStatementIds;
2313 }
2314
Vasu Nori6c354da2010-04-26 23:33:39 -07002315 /**
2316 * This method enables parallel execution of queries from multiple threads on the same database.
2317 * It does this by opening multiple handles to the database and using a different
2318 * database handle for each query.
2319 * <p>
2320 * If a transaction is in progress on one connection handle and say, a table is updated in the
2321 * transaction, then query on the same table on another connection handle will block for the
2322 * transaction to complete. But this method enables such queries to execute by having them
2323 * return old version of the data from the table. Most often it is the data that existed in the
2324 * table prior to the above transaction updates on that table.
2325 * <p>
2326 * Maximum number of simultaneous handles used to execute queries in parallel is
2327 * dependent upon the device memory and possibly other properties.
2328 * <p>
2329 * After calling this method, execution of queries in parallel is enabled as long as this
2330 * database handle is open. To disable execution of queries in parallel, database should
2331 * be closed and reopened.
2332 * <p>
2333 * If a query is part of a transaction, then it is executed on the same database handle the
2334 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07002335 * <p>
2336 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07002337 * possible. In such cases, a message is printed to logcat and false is returned.
2338 * <p>
2339 * This feature is not available for :memory: databases. In such cases,
2340 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07002341 * <p>
2342 * A typical way to use this method is the following:
2343 * <pre>
2344 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
2345 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
2346 * db.enableWriteAheadLogging();
2347 * </pre>
2348 * <p>
2349 * Writers should use {@link #beginTransactionNonExclusive()} or
2350 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
2351 * to start a trsnsaction.
2352 * Non-exclusive mode allows database file to be in readable by threads executing queries.
2353 * </p>
2354 *
Vasu Noria98cb262010-06-22 13:16:35 -07002355 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07002356 */
Vasu Noriffe06122010-09-27 12:32:57 -07002357 public boolean enableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002358 // make sure the database is not READONLY. WAL doesn't make sense for readonly-databases.
2359 if (isReadOnly()) {
2360 return false;
2361 }
2362 // acquire lock - no that no other thread is enabling WAL at the same time
2363 lock();
2364 try {
2365 if (mConnectionPool != null) {
2366 // already enabled
2367 return true;
2368 }
2369 if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
2370 Log.i(TAG, "can't enable WAL for memory databases.");
2371 return false;
2372 }
2373
2374 // make sure this database has NO attached databases because sqlite's write-ahead-logging
2375 // doesn't work for databases with attached databases
2376 if (mHasAttachedDbs) {
2377 if (Log.isLoggable(TAG, Log.DEBUG)) {
2378 Log.d(TAG,
2379 "this database: " + mPath + " has attached databases. can't enable WAL.");
2380 }
2381 return false;
2382 }
2383 mConnectionPool = new DatabaseConnectionPool(this);
2384 setJournalMode(mPath, "WAL");
2385 return true;
2386 } finally {
2387 unlock();
2388 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002389 }
2390
Vasu Nori2827d6d2010-07-04 00:26:18 -07002391 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07002392 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
2393 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07002394 */
Vasu Nori7b04c412010-07-20 10:31:21 -07002395 public void disableWriteAheadLogging() {
Paul Westbrookdae6d372011-02-17 10:59:56 -08002396 // grab database lock so that writeAheadLogging is not disabled from 2 different threads
2397 // at the same time
2398 lock();
2399 try {
2400 if (mConnectionPool == null) {
2401 return; // already disabled
2402 }
2403 mConnectionPool.close();
2404 setJournalMode(mPath, "TRUNCATE");
2405 mConnectionPool = null;
2406 } finally {
2407 unlock();
2408 }
Vasu Nori8d111032010-06-22 18:34:21 -07002409 }
2410
Vasu Nori65a88832010-07-16 15:14:08 -07002411 /* package */ SQLiteDatabase getDatabaseHandle(String sql) {
2412 if (isPooledConnection()) {
2413 // this is a pooled database connection
Vasu Norice38b982010-07-22 13:57:13 -07002414 // use it if it is open AND if I am not currently part of a transaction
2415 if (isOpen() && !amIInTransaction()) {
Vasu Nori65a88832010-07-16 15:14:08 -07002416 // TODO: use another connection from the pool
2417 // if this connection is currently in use by some other thread
2418 // AND if there are free connections in the pool
2419 return this;
2420 } else {
2421 // the pooled connection is not open! could have been closed either due
2422 // to corruption on this or some other connection to the database
2423 // OR, maybe the connection pool is disabled after this connection has been
2424 // allocated to me. try to get some other pooled or main database connection
2425 return getParentDbConnObj().getDbConnection(sql);
2426 }
2427 } else {
2428 // this is NOT a pooled connection. can we get one?
2429 return getDbConnection(sql);
2430 }
2431 }
2432
Vasu Nori6c354da2010-04-26 23:33:39 -07002433 /* package */ SQLiteDatabase createPoolConnection(short connectionNum) {
Vasu Nori65a88832010-07-16 15:14:08 -07002434 SQLiteDatabase db = openDatabase(mPath, mFactory, mFlags, mErrorHandler, connectionNum);
2435 db.mParentConnObj = this;
2436 return db;
2437 }
2438
2439 private synchronized SQLiteDatabase getParentDbConnObj() {
2440 return mParentConnObj;
Vasu Nori6c354da2010-04-26 23:33:39 -07002441 }
2442
2443 private boolean isPooledConnection() {
2444 return this.mConnectionNum > 0;
2445 }
2446
Vasu Nori2827d6d2010-07-04 00:26:18 -07002447 /* package */ SQLiteDatabase getDbConnection(String sql) {
Vasu Nori6c354da2010-04-26 23:33:39 -07002448 verifyDbIsOpen();
Vasu Noribfe1dc22010-08-25 16:29:02 -07002449 // this method should always be called with main database connection handle.
2450 // the only time when it is called with pooled database connection handle is
2451 // corruption occurs while trying to open a pooled database connection handle.
2452 // in that case, simply return 'this' handle
Vasu Nori65a88832010-07-16 15:14:08 -07002453 if (isPooledConnection()) {
Vasu Noribfe1dc22010-08-25 16:29:02 -07002454 return this;
Vasu Nori65a88832010-07-16 15:14:08 -07002455 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002456
2457 // use the current connection handle if
Vasu Norice38b982010-07-22 13:57:13 -07002458 // 1. if the caller is part of the ongoing transaction, if any
Vasu Nori65a88832010-07-16 15:14:08 -07002459 // 2. OR, if there is NO connection handle pool setup
Vasu Norice38b982010-07-22 13:57:13 -07002460 if (amIInTransaction() || mConnectionPool == null) {
Vasu Nori65a88832010-07-16 15:14:08 -07002461 return this;
Vasu Nori6c354da2010-04-26 23:33:39 -07002462 } else {
2463 // get a connection handle from the pool
2464 if (Log.isLoggable(TAG, Log.DEBUG)) {
2465 assert mConnectionPool != null;
Vasu Norice38b982010-07-22 13:57:13 -07002466 Log.i(TAG, mConnectionPool.toString());
Vasu Nori6c354da2010-04-26 23:33:39 -07002467 }
Vasu Nori65a88832010-07-16 15:14:08 -07002468 return mConnectionPool.get(sql);
Vasu Nori6c354da2010-04-26 23:33:39 -07002469 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002470 }
2471
2472 private void releaseDbConnection(SQLiteDatabase db) {
2473 // ignore this release call if
2474 // 1. the database is closed
2475 // 2. OR, if db is NOT a pooled connection handle
2476 // 3. OR, if the database being released is same as 'this' (this condition means
2477 // that we should always be releasing a pooled connection handle by calling this method
2478 // from the 'main' connection handle
2479 if (!isOpen() || !db.isPooledConnection() || (db == this)) {
2480 return;
2481 }
2482 if (Log.isLoggable(TAG, Log.DEBUG)) {
2483 assert isPooledConnection();
2484 assert mConnectionPool != null;
2485 Log.d(TAG, "releaseDbConnection threadid = " + Thread.currentThread().getId() +
2486 ", releasing # " + db.mConnectionNum + ", " + getPath());
2487 }
2488 mConnectionPool.release(db);
2489 }
2490
Vasu Norif3cf8a42010-03-23 11:41:44 -07002491 /**
2492 * this method is used to collect data about ALL open databases in the current process.
Vasu Nori0732f792010-07-29 17:24:12 -07002493 * bugreport is a user of this data.
Vasu Norif3cf8a42010-03-23 11:41:44 -07002494 */
Vasu Noric3849202010-03-09 10:47:25 -08002495 /* package */ static ArrayList<DbStats> getDbStats() {
2496 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Vasu Nori24675612010-09-27 14:54:19 -07002497 // make a local copy of mActiveDatabases - so that this method is not competing
2498 // for synchronization lock on mActiveDatabases
2499 ArrayList<WeakReference<SQLiteDatabase>> tempList;
2500 synchronized(mActiveDatabases) {
2501 tempList = (ArrayList<WeakReference<SQLiteDatabase>>)mActiveDatabases.clone();
2502 }
2503 for (WeakReference<SQLiteDatabase> w : tempList) {
2504 SQLiteDatabase db = w.get();
2505 if (db == null || !db.isOpen()) {
2506 continue;
2507 }
2508
2509 try {
2510 // get SQLITE_DBSTATUS_LOOKASIDE_USED for the db
2511 int lookasideUsed = db.native_getDbLookaside();
2512
2513 // get the lastnode of the dbname
2514 String path = db.getPath();
2515 int indx = path.lastIndexOf("/");
2516 String lastnode = path.substring((indx != -1) ? ++indx : 0);
2517
2518 // get list of attached dbs and for each db, get its size and pagesize
Vasu Noria017eda2011-01-27 10:52:55 -08002519 List<Pair<String, String>> attachedDbs = db.getAttachedDbs();
Vasu Nori24675612010-09-27 14:54:19 -07002520 if (attachedDbs == null) {
2521 continue;
2522 }
2523 for (int i = 0; i < attachedDbs.size(); i++) {
2524 Pair<String, String> p = attachedDbs.get(i);
2525 long pageCount = DatabaseUtils.longForQuery(db, "PRAGMA " + p.first
2526 + ".page_count;", null);
2527
2528 // first entry in the attached db list is always the main database
2529 // don't worry about prefixing the dbname with "main"
2530 String dbName;
2531 if (i == 0) {
2532 dbName = lastnode;
2533 } else {
2534 // lookaside is only relevant for the main db
2535 lookasideUsed = 0;
2536 dbName = " (attached) " + p.first;
2537 // if the attached db has a path, attach the lastnode from the path to above
2538 if (p.second.trim().length() > 0) {
2539 int idx = p.second.lastIndexOf("/");
2540 dbName += " : " + p.second.substring((idx != -1) ? ++idx : 0);
2541 }
2542 }
2543 if (pageCount > 0) {
2544 dbStatsList.add(new DbStats(dbName, pageCount, db.getPageSize(),
2545 lookasideUsed, db.getCacheHitNum(), db.getCacheMissNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002546 db.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002547 }
2548 }
2549 // if there are pooled connections, return the cache stats for them also.
2550 // while we are trying to query the pooled connections for stats, some other thread
2551 // could be disabling conneciton pool. so, grab a reference to the connection pool.
2552 DatabaseConnectionPool connPool = db.mConnectionPool;
2553 if (connPool != null) {
2554 for (SQLiteDatabase pDb : connPool.getConnectionList()) {
2555 dbStatsList.add(new DbStats("(pooled # " + pDb.mConnectionNum + ") "
2556 + lastnode, 0, 0, 0, pDb.getCacheHitNum(),
Vasu Nori00e40172010-11-29 11:03:23 -08002557 pDb.getCacheMissNum(), pDb.getCachesize()));
Vasu Nori24675612010-09-27 14:54:19 -07002558 }
2559 }
2560 } catch (SQLiteException e) {
2561 // ignore. we don't care about exceptions when we are taking adb
2562 // bugreport!
2563 }
2564 }
Vasu Noric3849202010-03-09 10:47:25 -08002565 return dbStatsList;
2566 }
2567
2568 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002569 * Returns list of full pathnames of all attached databases including the main database
2570 * by executing 'pragma database_list' on the database.
2571 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002572 * @return ArrayList of pairs of (database name, database file path) or null if the database
2573 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08002574 */
Vasu Noria017eda2011-01-27 10:52:55 -08002575 public List<Pair<String, String>> getAttachedDbs() {
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002576 if (!isOpen()) {
Vasu Norif3cf8a42010-03-23 11:41:44 -07002577 return null;
2578 }
Vasu Noric3849202010-03-09 10:47:25 -08002579 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Vasu Nori24675612010-09-27 14:54:19 -07002580 if (!mHasAttachedDbs) {
2581 // No attached databases.
2582 // There is a small window where attached databases exist but this flag is not set yet.
2583 // This can occur when this thread is in a race condition with another thread
2584 // that is executing the SQL statement: "attach database <blah> as <foo>"
2585 // If this thread is NOT ok with such a race condition (and thus possibly not receive
2586 // the entire list of attached databases), then the caller should ensure that no thread
2587 // is executing any SQL statements while a thread is calling this method.
2588 // Typically, this method is called when 'adb bugreport' is done or the caller wants to
2589 // collect stats on the database and all its attached databases.
2590 attachedDbs.add(new Pair<String, String>("main", mPath));
2591 return attachedDbs;
2592 }
2593 // has attached databases. query sqlite to get the list of attached databases.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002594 Cursor c = null;
2595 try {
2596 c = rawQuery("pragma database_list;", null);
2597 while (c.moveToNext()) {
2598 // sqlite returns a row for each database in the returned list of databases.
2599 // in each row,
2600 // 1st column is the database name such as main, or the database
2601 // name specified on the "ATTACH" command
2602 // 2nd column is the database file path.
2603 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
2604 }
2605 } finally {
2606 if (c != null) {
2607 c.close();
2608 }
Vasu Noric3849202010-03-09 10:47:25 -08002609 }
Vasu Noric3849202010-03-09 10:47:25 -08002610 return attachedDbs;
2611 }
2612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002614 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
2615 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002616 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07002617 *<p>
2618 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002619 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07002620 *<p>
2621 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002622 *
2623 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07002624 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002625 */
2626 public boolean isDatabaseIntegrityOk() {
Vasu Noriccd95442010-05-28 17:04:16 -07002627 verifyDbIsOpen();
Vasu Noria017eda2011-01-27 10:52:55 -08002628 List<Pair<String, String>> attachedDbs = null;
Vasu Noribfe1dc22010-08-25 16:29:02 -07002629 try {
2630 attachedDbs = getAttachedDbs();
2631 if (attachedDbs == null) {
2632 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
2633 "be retrieved. probably because the database is closed");
2634 }
2635 } catch (SQLiteException e) {
2636 // can't get attachedDb list. do integrity check on the main database
2637 attachedDbs = new ArrayList<Pair<String, String>>();
2638 attachedDbs.add(new Pair<String, String>("main", this.mPath));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002639 }
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002640 for (int i = 0; i < attachedDbs.size(); i++) {
2641 Pair<String, String> p = attachedDbs.get(i);
2642 SQLiteStatement prog = null;
2643 try {
2644 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
2645 String rslt = prog.simpleQueryForString();
2646 if (!rslt.equalsIgnoreCase("ok")) {
2647 // integrity_checker failed on main or attached databases
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002648 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
Vasu Noribfe1dc22010-08-25 16:29:02 -07002649 return false;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002650 }
2651 } finally {
2652 if (prog != null) prog.close();
2653 }
2654 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07002655 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002656 }
2657
2658 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 * Native call to open the database.
2660 *
2661 * @param path The full path to the database
2662 */
2663 private native void dbopen(String path, int flags);
2664
2665 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002666 * Native call to setup tracing of all SQL statements
Vasu Nori3ef94e22010-02-05 14:49:04 -08002667 *
2668 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002669 * @param connectionNum connection number: 0 - N, where the main database
2670 * connection handle is numbered 0 and the connection handles in the connection
2671 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002672 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002673 private native void enableSqlTracing(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002674
2675 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002676 * Native call to setup profiling of all SQL statements.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002677 * currently, sqlite's profiling = printing of execution-time
Vasu Noriccd95442010-05-28 17:04:16 -07002678 * (wall-clock time) of each of the SQL statements, as they
Vasu Nori3ef94e22010-02-05 14:49:04 -08002679 * are executed.
2680 *
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 enableSqlProfiling(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002687
2688 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 * Native call to set the locale. {@link #lock} must be held when calling
2690 * this method.
2691 * @throws SQLException
2692 */
Vasu Nori0732f792010-07-29 17:24:12 -07002693 private native void native_setLocale(String loc, int flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694
2695 /**
Vasu Noric3849202010-03-09 10:47:25 -08002696 * return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here
2697 * http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html
2698 * @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED
2699 */
2700 private native int native_getDbLookaside();
Vasu Nori6f37f832010-05-19 11:53:25 -07002701
2702 /**
2703 * finalizes the given statement id.
2704 *
2705 * @param statementId statement to be finzlied by sqlite
2706 */
2707 private final native void native_finalize(int statementId);
Vasu Nori34ad57f02010-12-21 09:32:36 -08002708
2709 /**
2710 * set sqlite soft heap limit
2711 * http://www.sqlite.org/c3ref/soft_heap_limit64.html
2712 */
2713 private native void native_setSqliteSoftHeapLimit(int softHeapLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714}