blob: 2f3dc066a1df05eaa992a5a801665fed3c788617 [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
Jeff Brown4c1241d2012-02-02 17:05:00 -080019import android.content.CancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentValues;
Jeff Brown75ea64f2012-01-25 19:37:13 -080021import android.content.OperationCanceledException;
Vasu Nori34ad57f02010-12-21 09:32:36 -080022import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.database.Cursor;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070024import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.database.DatabaseUtils;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070026import android.database.DefaultDatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.SQLException;
Vasu Noric3849202010-03-09 10:47:25 -080028import android.database.sqlite.SQLiteDebug.DbStats;
Jeff Browne5360fb2011-10-31 17:48:13 -070029import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070032import android.util.Log;
Vasu Noric3849202010-03-09 10:47:25 -080033import android.util.Pair;
Jeff Browne5360fb2011-10-31 17:48:13 -070034import android.util.Printer;
35
36import dalvik.system.CloseGuard;
37
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import java.io.File;
Jeff Brown79087e42012-03-01 19:52:44 -080039import java.io.FileFilter;
Vasu Noric3849202010-03-09 10:47:25 -080040import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import java.util.HashMap;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080042import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import java.util.Locale;
44import java.util.Map;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
47/**
48 * Exposes methods to manage a SQLite database.
Jeff Browne5360fb2011-10-31 17:48:13 -070049 *
50 * <p>
51 * SQLiteDatabase has methods to create, delete, execute SQL commands, and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 * perform other common database management tasks.
Jeff Browne5360fb2011-10-31 17:48:13 -070053 * </p><p>
54 * See the Notepad sample application in the SDK for an example of creating
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055 * and managing a database.
Jeff Browne5360fb2011-10-31 17:48:13 -070056 * </p><p>
57 * Database names must be unique within an application, not across all applications.
58 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059 *
60 * <h3>Localized Collation - ORDER BY</h3>
Jeff Browne5360fb2011-10-31 17:48:13 -070061 * <p>
62 * In addition to SQLite's default <code>BINARY</code> collator, Android supplies
63 * two more, <code>LOCALIZED</code>, which changes with the system's current locale,
64 * and <code>UNICODE</code>, which is the Unicode Collation Algorithm and not tailored
65 * to the current locale.
66 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 */
68public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070069 private static final String TAG = "SQLiteDatabase";
Jeff Browne5360fb2011-10-31 17:48:13 -070070
Jeff Hamilton082c2af2009-09-29 11:49:51 -070071 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Jeff Browne5360fb2011-10-31 17:48:13 -070073 // Stores reference to all databases opened in the current process.
74 // (The referent Object is not used at this time.)
75 // INVARIANT: Guarded by sActiveDatabases.
76 private static WeakHashMap<SQLiteDatabase, Object> sActiveDatabases =
77 new WeakHashMap<SQLiteDatabase, Object>();
78
79 // Thread-local for database sessions that belong to this database.
80 // Each thread has its own database session.
81 // INVARIANT: Immutable.
82 private final ThreadLocal<SQLiteSession> mThreadSession = new ThreadLocal<SQLiteSession>() {
83 @Override
84 protected SQLiteSession initialValue() {
85 return createSession();
86 }
87 };
88
89 // The optional factory to use when creating new Cursors. May be null.
90 // INVARIANT: Immutable.
91 private final CursorFactory mCursorFactory;
92
93 // Error handler to be used when SQLite returns corruption errors.
94 // INVARIANT: Immutable.
95 private final DatabaseErrorHandler mErrorHandler;
96
97 // Shared database state lock.
98 // This lock guards all of the shared state of the database, such as its
99 // configuration, whether it is open or closed, and so on. This lock should
100 // be held for as little time as possible.
101 //
102 // The lock MUST NOT be held while attempting to acquire database connections or
103 // while executing SQL statements on behalf of the client as it can lead to deadlock.
104 //
105 // It is ok to hold the lock while reconfiguring the connection pool or dumping
106 // statistics because those operations are non-reentrant and do not try to acquire
107 // connections that might be held by other threads.
108 //
109 // Basic rule: grab the lock, access or modify global state, release the lock, then
110 // do the required SQL work.
111 private final Object mLock = new Object();
112
113 // Warns if the database is finalized without being closed properly.
114 // INVARIANT: Guarded by mLock.
115 private final CloseGuard mCloseGuardLocked = CloseGuard.get();
116
117 // The database configuration.
118 // INVARIANT: Guarded by mLock.
119 private final SQLiteDatabaseConfiguration mConfigurationLocked;
120
121 // The connection pool for the database, null when closed.
122 // The pool itself is thread-safe, but the reference to it can only be acquired
123 // when the lock is held.
124 // INVARIANT: Guarded by mLock.
125 private SQLiteConnectionPool mConnectionPoolLocked;
126
127 // True if the database has attached databases.
128 // INVARIANT: Guarded by mLock.
129 private boolean mHasAttachedDbsLocked;
130
131 // True if the database is in WAL mode.
132 // INVARIANT: Guarded by mLock.
133 private boolean mIsWALEnabledLocked;
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700136 * When a constraint violation occurs, an immediate ROLLBACK occurs,
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800137 * thus ending the current transaction, and the command aborts with a
138 * return code of SQLITE_CONSTRAINT. If no transaction is active
139 * (other than the implied transaction that is created on every command)
Jeff Browne5360fb2011-10-31 17:48:13 -0700140 * then this algorithm works the same as ABORT.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800141 */
142 public static final int CONFLICT_ROLLBACK = 1;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700143
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800144 /**
145 * When a constraint violation occurs,no ROLLBACK is executed
146 * so changes from prior commands within the same transaction
147 * are preserved. This is the default behavior.
148 */
149 public static final int CONFLICT_ABORT = 2;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700150
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800151 /**
152 * When a constraint violation occurs, the command aborts with a return
153 * code SQLITE_CONSTRAINT. But any changes to the database that
154 * the command made prior to encountering the constraint violation
155 * are preserved and are not backed out.
156 */
157 public static final int CONFLICT_FAIL = 3;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700158
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800159 /**
160 * When a constraint violation occurs, the one row that contains
161 * the constraint violation is not inserted or changed.
162 * But the command continues executing normally. Other rows before and
163 * after the row that contained the constraint violation continue to be
164 * inserted or updated normally. No error is returned.
165 */
166 public static final int CONFLICT_IGNORE = 4;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700167
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800168 /**
169 * When a UNIQUE constraint violation occurs, the pre-existing rows that
170 * are causing the constraint violation are removed prior to inserting
171 * or updating the current row. Thus the insert or update always occurs.
172 * The command continues executing normally. No error is returned.
173 * If a NOT NULL constraint violation occurs, the NULL value is replaced
174 * by the default value for that column. If the column has no default
175 * value, then the ABORT algorithm is used. If a CHECK constraint
176 * violation occurs then the IGNORE algorithm is used. When this conflict
177 * resolution strategy deletes rows in order to satisfy a constraint,
178 * it does not invoke delete triggers on those rows.
Jeff Browne5360fb2011-10-31 17:48:13 -0700179 * This behavior might change in a future release.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800180 */
181 public static final int CONFLICT_REPLACE = 5;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700182
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800183 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700184 * Use the following when no conflict action is specified.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800185 */
186 public static final int CONFLICT_NONE = 0;
Jeff Browne5360fb2011-10-31 17:48:13 -0700187
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800188 private static final String[] CONFLICT_VALUES = new String[]
189 {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 /**
192 * Maximum Length Of A LIKE Or GLOB Pattern
193 * The pattern matching algorithm used in the default LIKE and GLOB implementation
194 * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
195 * the pattern) for certain pathological cases. To avoid denial-of-service attacks
196 * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
197 * The default value of this limit is 50000. A modern workstation can evaluate
198 * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
199 * The denial of service problem only comes into play when the pattern length gets
200 * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
201 * are at most a few dozen bytes in length, paranoid application developers may
202 * want to reduce this parameter to something in the range of a few hundred
203 * if they know that external users are able to generate arbitrary patterns.
204 */
205 public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
206
207 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700208 * Open flag: Flag for {@link #openDatabase} to open the database for reading and writing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 * If the disk is full, this may fail even before you actually write anything.
210 *
211 * {@more} Note that the value of this flag is 0, so it is the default.
212 */
213 public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
214
215 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700216 * Open flag: Flag for {@link #openDatabase} to open the database for reading only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 * This is the only reliable way to open a database if the disk may be full.
218 */
219 public static final int OPEN_READONLY = 0x00000001; // update native code if changing
220
221 private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
222
223 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700224 * Open flag: Flag for {@link #openDatabase} to open the database without support for
225 * localized collators.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 *
227 * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
228 * You must be consistent when using this flag to use the setting the database was
229 * created with. If this is set, {@link #setLocale} will do nothing.
230 */
231 public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
232
233 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700234 * Open flag: Flag for {@link #openDatabase} to create the database file if it does not
235 * already exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 */
237 public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
238
239 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700240 * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}.
Vasu Norib729dcc2010-09-14 11:35:49 -0700241 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700242 * Each prepared-statement is between 1K - 6K, depending on the complexity of the
243 * SQL statement & schema. A large SQL cache may use a significant amount of memory.
Vasu Norie495d1f2010-01-06 16:34:19 -0800244 */
Vasu Nori90a367262010-04-12 12:49:09 -0700245 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Norib729dcc2010-09-14 11:35:49 -0700246
Jeff Browne5360fb2011-10-31 17:48:13 -0700247 private SQLiteDatabase(String path, int openFlags, CursorFactory cursorFactory,
248 DatabaseErrorHandler errorHandler) {
249 mCursorFactory = cursorFactory;
250 mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
251 mConfigurationLocked = new SQLiteDatabaseConfiguration(path, openFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700253
Jeff Browne5360fb2011-10-31 17:48:13 -0700254 @Override
255 protected void finalize() throws Throwable {
256 try {
257 dispose(true);
258 } finally {
259 super.finalize();
260 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700261 }
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 @Override
264 protected void onAllReferencesReleased() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700265 dispose(false);
266 }
267
268 private void dispose(boolean finalized) {
269 final SQLiteConnectionPool pool;
270 synchronized (mLock) {
271 if (mCloseGuardLocked != null) {
272 if (finalized) {
273 mCloseGuardLocked.warnIfOpen();
274 }
275 mCloseGuardLocked.close();
276 }
277
278 pool = mConnectionPoolLocked;
279 mConnectionPoolLocked = null;
280 }
281
282 if (!finalized) {
283 synchronized (sActiveDatabases) {
284 sActiveDatabases.remove(this);
285 }
286
287 if (pool != null) {
288 pool.close();
289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291 }
292
293 /**
294 * Attempts to release memory that SQLite holds but does not require to
295 * operate properly. Typically this memory will come from the page cache.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700296 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 * @return the number of bytes actually released
298 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700299 public static int releaseMemory() {
300 return SQLiteGlobal.releaseMemory();
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 /**
304 * Control whether or not the SQLiteDatabase is made thread-safe by using locks
305 * around critical sections. This is pretty expensive, so if you know that your
306 * DB will only be used by a single thread then you should set this to false.
307 * The default is true.
308 * @param lockingEnabled set to true to enable locks, false otherwise
Jeff Browne5360fb2011-10-31 17:48:13 -0700309 *
310 * @deprecated This method now does nothing. Do not use.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700312 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 public void setLockingEnabled(boolean lockingEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315
316 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700317 * Gets a label to use when describing the database in log messages.
318 * @return The label.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700320 String getLabel() {
321 synchronized (mLock) {
322 return mConfigurationLocked.label;
323 }
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
Jeff Browne5360fb2011-10-31 17:48:13 -0700326 /**
327 * Sends a corruption message to the database error handler.
328 */
329 void onCorruption() {
330 EventLog.writeEvent(EVENT_DB_CORRUPT, getLabel());
Vasu Noriccd95442010-05-28 17:04:16 -0700331 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333
334 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700335 * Gets the {@link SQLiteSession} that belongs to this thread for this database.
336 * Once a thread has obtained a session, it will continue to obtain the same
337 * session even after the database has been closed (although the session will not
338 * be usable). However, a thread that does not already have a session cannot
339 * obtain one after the database has been closed.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700340 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700341 * The idea is that threads that have active connections to the database may still
342 * have work to complete even after the call to {@link #close}. Active database
343 * connections are not actually disposed until they are released by the threads
344 * that own them.
345 *
346 * @return The session, never null.
347 *
348 * @throws IllegalStateException if the thread does not yet have a session and
349 * the database is not open.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700351 SQLiteSession getThreadSession() {
352 return mThreadSession.get(); // initialValue() throws if database closed
Vasu Nori6d970252010-10-05 10:48:49 -0700353 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700354
Jeff Browne5360fb2011-10-31 17:48:13 -0700355 SQLiteSession createSession() {
356 final SQLiteConnectionPool pool;
357 synchronized (mLock) {
358 throwIfNotOpenLocked();
359 pool = mConnectionPoolLocked;
Vasu Nori6d970252010-10-05 10:48:49 -0700360 }
Jeff Browne5360fb2011-10-31 17:48:13 -0700361 return new SQLiteSession(pool);
Vasu Norid4608a32011-02-03 16:24:06 -0800362 }
363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700365 * Gets default connection flags that are appropriate for this thread, taking into
366 * account whether the thread is acting on behalf of the UI.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700368 * @param readOnly True if the connection should be read-only.
369 * @return The connection flags.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700371 int getThreadDefaultConnectionFlags(boolean readOnly) {
372 int flags = readOnly ? SQLiteConnectionPool.CONNECTION_FLAG_READ_ONLY :
373 SQLiteConnectionPool.CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY;
374 if (isMainThread()) {
375 flags |= SQLiteConnectionPool.CONNECTION_FLAG_INTERACTIVE;
376 }
377 return flags;
Vasu Nori16057fa2011-03-18 11:40:37 -0700378 }
379
Jeff Browne5360fb2011-10-31 17:48:13 -0700380 private static boolean isMainThread() {
381 // FIXME: There should be a better way to do this.
382 // Would also be nice to have something that would work across Binder calls.
383 Looper looper = Looper.myLooper();
384 return looper != null && looper == Looper.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386
387 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700388 * Begins a transaction in EXCLUSIVE mode.
389 * <p>
390 * Transactions can be nested.
391 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 * the work done in that transaction and all of the nested transactions will be committed or
393 * rolled back. The changes will be rolled back if any transaction is ended without being
394 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700395 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 * <p>Here is the standard idiom for transactions:
397 *
398 * <pre>
399 * db.beginTransaction();
400 * try {
401 * ...
402 * db.setTransactionSuccessful();
403 * } finally {
404 * db.endTransaction();
405 * }
406 * </pre>
407 */
408 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700409 beginTransaction(null /* transactionStatusCallback */, true);
410 }
411
412 /**
413 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
414 * the outer transaction is ended all of the work done in that transaction
415 * and all of the nested transactions will be committed or rolled back. The
416 * changes will be rolled back if any transaction is ended without being
417 * marked as clean (by calling setTransactionSuccessful). Otherwise they
418 * will be committed.
419 * <p>
420 * Here is the standard idiom for transactions:
421 *
422 * <pre>
423 * db.beginTransactionNonExclusive();
424 * try {
425 * ...
426 * db.setTransactionSuccessful();
427 * } finally {
428 * db.endTransaction();
429 * }
430 * </pre>
431 */
432 public void beginTransactionNonExclusive() {
433 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700434 }
435
436 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700437 * Begins a transaction in EXCLUSIVE mode.
438 * <p>
439 * Transactions can be nested.
440 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700441 * the work done in that transaction and all of the nested transactions will be committed or
442 * rolled back. The changes will be rolled back if any transaction is ended without being
443 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700444 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700445 * <p>Here is the standard idiom for transactions:
446 *
447 * <pre>
448 * db.beginTransactionWithListener(listener);
449 * try {
450 * ...
451 * db.setTransactionSuccessful();
452 * } finally {
453 * db.endTransaction();
454 * }
455 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700456 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700457 * @param transactionListener listener that should be notified when the transaction begins,
458 * commits, or is rolled back, either explicitly or by a call to
459 * {@link #yieldIfContendedSafely}.
460 */
461 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700462 beginTransaction(transactionListener, true);
463 }
464
465 /**
466 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
467 * the outer transaction is ended all of the work done in that transaction
468 * and all of the nested transactions will be committed or rolled back. The
469 * changes will be rolled back if any transaction is ended without being
470 * marked as clean (by calling setTransactionSuccessful). Otherwise they
471 * will be committed.
472 * <p>
473 * Here is the standard idiom for transactions:
474 *
475 * <pre>
476 * db.beginTransactionWithListenerNonExclusive(listener);
477 * try {
478 * ...
479 * db.setTransactionSuccessful();
480 * } finally {
481 * db.endTransaction();
482 * }
483 * </pre>
484 *
485 * @param transactionListener listener that should be notified when the
486 * transaction begins, commits, or is rolled back, either
487 * explicitly or by a call to {@link #yieldIfContendedSafely}.
488 */
489 public void beginTransactionWithListenerNonExclusive(
490 SQLiteTransactionListener transactionListener) {
491 beginTransaction(transactionListener, false);
492 }
493
494 private void beginTransaction(SQLiteTransactionListener transactionListener,
495 boolean exclusive) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700496 getThreadSession().beginTransaction(exclusive ? SQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
497 SQLiteSession.TRANSACTION_MODE_IMMEDIATE, transactionListener,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800498 getThreadDefaultConnectionFlags(false /*readOnly*/), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
501 /**
502 * End a transaction. See beginTransaction for notes about how to use this and when transactions
503 * are committed and rolled back.
504 */
505 public void endTransaction() {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800506 getThreadSession().endTransaction(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508
509 /**
510 * Marks the current transaction as successful. Do not do any more database work between
511 * calling this and calling endTransaction. Do as little non-database work as possible in that
512 * situation too. If any errors are encountered between this and endTransaction the transaction
513 * will still be committed.
514 *
515 * @throws IllegalStateException if the current thread is not in a transaction or the
516 * transaction is already marked as successful.
517 */
518 public void setTransactionSuccessful() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700519 getThreadSession().setTransactionSuccessful();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 }
521
522 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700523 * Returns true if the current thread has a transaction pending.
524 *
525 * @return True if the current thread is in a transaction.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 */
527 public boolean inTransaction() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700528 return getThreadSession().hasTransaction();
Vasu Norice38b982010-07-22 13:57:13 -0700529 }
530
531 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700532 * Returns true if the current thread is holding an active connection to the database.
Vasu Norice38b982010-07-22 13:57:13 -0700533 * <p>
Jeff Browne5360fb2011-10-31 17:48:13 -0700534 * The name of this method comes from a time when having an active connection
535 * to the database meant that the thread was holding an actual lock on the
536 * database. Nowadays, there is no longer a true "database lock" although threads
537 * may block if they cannot acquire a database connection to perform a
538 * particular operation.
539 * </p>
Vasu Norice38b982010-07-22 13:57:13 -0700540 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700541 * @return True if the current thread is holding an active connection to the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 */
543 public boolean isDbLockedByCurrentThread() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700544 return getThreadSession().hasConnection();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
547 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700548 * Always returns false.
549 * <p>
550 * There is no longer the concept of a database lock, so this method always returns false.
551 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700553 * @return False.
554 * @deprecated Always returns false. Do not use this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700556 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 public boolean isDbLockedByOtherThreads() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700558 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
560
561 /**
562 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
563 * successful so far. Do not call setTransactionSuccessful before calling this. When this
564 * returns a new transaction will have been created but not marked as successful.
565 * @return true if the transaction was yielded
566 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
567 * will not be yielded. Use yieldIfContendedSafely instead.
568 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700569 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700571 return yieldIfContendedHelper(false /* do not check yielding */,
572 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574
575 /**
576 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
577 * successful so far. Do not call setTransactionSuccessful before calling this. When this
578 * returns a new transaction will have been created but not marked as successful. This assumes
579 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700580 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * @return true if the transaction was yielded
582 */
583 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700584 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586
Fred Quintana5c7aede2009-08-27 21:41:27 -0700587 /**
588 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
589 * successful so far. Do not call setTransactionSuccessful before calling this. When this
590 * returns a new transaction will have been created but not marked as successful. This assumes
591 * that there are no nested transactions (beginTransaction has only been called once) and will
592 * throw an exception if that is not the case.
593 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
594 * the lock was actually yielded. This will allow other background threads to make some
595 * more progress than they would if we started the transaction immediately.
596 * @return true if the transaction was yielded
597 */
598 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
599 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
600 }
601
Jeff Browne5360fb2011-10-31 17:48:13 -0700602 private boolean yieldIfContendedHelper(boolean throwIfUnsafe, long sleepAfterYieldDelay) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800603 return getThreadSession().yieldTransaction(sleepAfterYieldDelay, throwIfUnsafe, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700607 * Deprecated.
Vasu Nori95675132010-07-21 16:24:40 -0700608 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 */
Vasu Nori95675132010-07-21 16:24:40 -0700610 @Deprecated
611 public Map<String, String> getSyncedTables() {
612 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 }
614
615 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 * Open the database according to the flags {@link #OPEN_READWRITE}
617 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
618 *
619 * <p>Sets the locale of the database to the the system's current locale.
620 * Call {@link #setLocale} if you would like something else.</p>
621 *
622 * @param path to database file to open and/or create
623 * @param factory an optional factory class that is called to instantiate a
624 * cursor when query is called, or null for default
625 * @param flags to control database access mode
626 * @return the newly opened database
627 * @throws SQLiteException if the database cannot be opened
628 */
629 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700630 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
631 }
632
633 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700634 * Open the database according to the flags {@link #OPEN_READWRITE}
635 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
636 *
637 * <p>Sets the locale of the database to the the system's current locale.
638 * Call {@link #setLocale} if you would like something else.</p>
639 *
640 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
641 * used to handle corruption when sqlite reports database corruption.</p>
642 *
643 * @param path to database file to open and/or create
644 * @param factory an optional factory class that is called to instantiate a
645 * cursor when query is called, or null for default
646 * @param flags to control database access mode
647 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
648 * when sqlite reports database corruption
649 * @return the newly opened database
650 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700651 */
652 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
653 DatabaseErrorHandler errorHandler) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700654 SQLiteDatabase db = new SQLiteDatabase(path, flags, factory, errorHandler);
655 db.open();
656 return db;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700657 }
658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 /**
660 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
661 */
662 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
663 return openOrCreateDatabase(file.getPath(), factory);
664 }
665
666 /**
667 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
668 */
669 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
670 return openDatabase(path, factory, CREATE_IF_NECESSARY);
671 }
672
673 /**
Vasu Nori6c354da2010-04-26 23:33:39 -0700674 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700675 */
676 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
677 DatabaseErrorHandler errorHandler) {
678 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
679 }
680
Jeff Brown559d0642012-02-29 10:19:12 -0800681 /**
Jeff Brown79087e42012-03-01 19:52:44 -0800682 * Deletes a database including its journal file and other auxiliary files
683 * that may have been created by the database engine.
684 *
685 * @param file The database file path.
686 * @return True if the database was successfully deleted.
687 */
688 public static boolean deleteDatabase(File file) {
689 if (file == null) {
690 throw new IllegalArgumentException("file must not be null");
691 }
692
693 boolean deleted = false;
694 deleted |= file.delete();
695 deleted |= new File(file.getPath() + "-journal").delete();
696 deleted |= new File(file.getPath() + "-shm").delete();
697 deleted |= new File(file.getPath() + "-wal").delete();
698
699 File dir = file.getParentFile();
700 if (dir != null) {
701 final String prefix = file.getName() + "-mj";
702 final FileFilter filter = new FileFilter() {
703 @Override
704 public boolean accept(File candidate) {
705 return candidate.getName().startsWith(prefix);
706 }
707 };
708 for (File masterJournal : dir.listFiles(filter)) {
709 deleted |= masterJournal.delete();
710 }
711 }
712 return deleted;
713 }
714
715 /**
Jeff Brown559d0642012-02-29 10:19:12 -0800716 * Reopens the database in read-write mode.
717 * If the database is already read-write, does nothing.
718 *
719 * @throws SQLiteException if the database could not be reopened as requested, in which
720 * case it remains open in read only mode.
721 * @throws IllegalStateException if the database is not open.
722 *
723 * @see #isReadOnly()
724 * @hide
725 */
726 public void reopenReadWrite() {
727 synchronized (mLock) {
728 throwIfNotOpenLocked();
729
730 if (!isReadOnlyLocked()) {
731 return; // nothing to do
732 }
733
734 // Reopen the database in read-write mode.
735 final int oldOpenFlags = mConfigurationLocked.openFlags;
736 mConfigurationLocked.openFlags = (mConfigurationLocked.openFlags & ~OPEN_READ_MASK)
737 | OPEN_READWRITE;
738 try {
739 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
740 } catch (RuntimeException ex) {
741 mConfigurationLocked.openFlags = oldOpenFlags;
742 throw ex;
743 }
744 }
745 }
746
Jeff Browne5360fb2011-10-31 17:48:13 -0700747 private void open() {
748 try {
749 try {
750 openInner();
751 } catch (SQLiteDatabaseCorruptException ex) {
752 onCorruption();
753 openInner();
754 }
Jeff Browne5360fb2011-10-31 17:48:13 -0700755 } catch (SQLiteException ex) {
756 Log.e(TAG, "Failed to open database '" + getLabel() + "'.", ex);
757 close();
758 throw ex;
759 }
760 }
761
762 private void openInner() {
763 synchronized (mLock) {
764 assert mConnectionPoolLocked == null;
765 mConnectionPoolLocked = SQLiteConnectionPool.open(mConfigurationLocked);
766 mCloseGuardLocked.open("close");
767 }
768
769 synchronized (sActiveDatabases) {
770 sActiveDatabases.put(this, null);
771 }
772 }
773
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700774 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 * Create a memory backed SQLite database. Its contents will be destroyed
776 * when the database is closed.
777 *
778 * <p>Sets the locale of the database to the the system's current locale.
779 * Call {@link #setLocale} if you would like something else.</p>
780 *
781 * @param factory an optional factory class that is called to instantiate a
782 * cursor when query is called
783 * @return a SQLiteDatabase object, or null if the database can't be created
784 */
785 public static SQLiteDatabase create(CursorFactory factory) {
786 // This is a magic string with special meaning for SQLite.
Jeff Browne5360fb2011-10-31 17:48:13 -0700787 return openDatabase(SQLiteDatabaseConfiguration.MEMORY_DB_PATH,
788 factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
790
791 /**
792 * Close the database.
793 */
794 public void close() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700795 dispose(false);
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400796 }
797
798 /**
799 * Registers a CustomFunction callback as a function that can be called from
Jeff Browne5360fb2011-10-31 17:48:13 -0700800 * SQLite database triggers.
801 *
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400802 * @param name the name of the sqlite3 function
803 * @param numArgs the number of arguments for the function
804 * @param function callback to call when the function is executed
805 * @hide
806 */
807 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700808 // Create wrapper (also validates arguments).
809 SQLiteCustomFunction wrapper = new SQLiteCustomFunction(name, numArgs, function);
810
811 synchronized (mLock) {
812 throwIfNotOpenLocked();
813 mConfigurationLocked.customFunctions.add(wrapper);
814 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400815 }
816 }
817
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400818 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 * Gets the database version.
820 *
821 * @return the database version
822 */
823 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -0700824 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826
827 /**
828 * Sets the database version.
829 *
830 * @param version the new database version
831 */
832 public void setVersion(int version) {
833 execSQL("PRAGMA user_version = " + version);
834 }
835
836 /**
837 * Returns the maximum size the database may grow to.
838 *
839 * @return the new maximum database size
840 */
841 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700842 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
843 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845
846 /**
847 * Sets the maximum size the database will grow to. The maximum size cannot
848 * be set below the current size.
849 *
850 * @param numBytes the maximum database size, in bytes
851 * @return the new maximum database size
852 */
853 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -0700854 long pageSize = getPageSize();
855 long numPages = numBytes / pageSize;
856 // If numBytes isn't a multiple of pageSize, bump up a page
857 if ((numBytes % pageSize) != 0) {
858 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -0700859 }
Vasu Noriccd95442010-05-28 17:04:16 -0700860 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
861 null);
862 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
865 /**
866 * Returns the current database page size, in bytes.
867 *
868 * @return the database page size, in bytes
869 */
870 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700871 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
873
874 /**
875 * Sets the database page size. The page size must be a power of two. This
876 * method does not work if any data has been written to the database file,
877 * and must be called right after the database has been created.
878 *
879 * @param numBytes the database page size, in bytes
880 */
881 public void setPageSize(long numBytes) {
882 execSQL("PRAGMA page_size = " + numBytes);
883 }
884
885 /**
886 * Mark this table as syncable. When an update occurs in this table the
887 * _sync_dirty field will be set to ensure proper syncing operation.
888 *
889 * @param table the table to mark as syncable
890 * @param deletedTable The deleted table that corresponds to the
891 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -0700892 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 */
Vasu Nori95675132010-07-21 16:24:40 -0700894 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897
898 /**
899 * Mark this table as syncable, with the _sync_dirty residing in another
900 * table. When an update occurs in this table the _sync_dirty field of the
901 * row in updateTable with the _id in foreignKey will be set to
902 * ensure proper syncing operation.
903 *
904 * @param table an update on this table will trigger a sync time removal
905 * @param foreignKey this is the column in table whose value is an _id in
906 * updateTable
907 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -0700908 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 */
Vasu Nori95675132010-07-21 16:24:40 -0700910 @Deprecated
911 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913
914 /**
915 * Finds the name of the first table, which is editable.
916 *
917 * @param tables a list of tables
918 * @return the first table listed
919 */
920 public static String findEditTable(String tables) {
921 if (!TextUtils.isEmpty(tables)) {
922 // find the first word terminated by either a space or a comma
923 int spacepos = tables.indexOf(' ');
924 int commapos = tables.indexOf(',');
925
926 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
927 return tables.substring(0, spacepos);
928 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
929 return tables.substring(0, commapos);
930 }
931 return tables;
932 } else {
933 throw new IllegalStateException("Invalid tables");
934 }
935 }
936
937 /**
938 * Compiles an SQL statement into a reusable pre-compiled statement object.
939 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
940 * statement and fill in those values with {@link SQLiteProgram#bindString}
941 * and {@link SQLiteProgram#bindLong} each time you want to run the
942 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -0700943 *<p>
944 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 *
946 * @param sql The raw SQL statement, may contain ? for unknown values to be
947 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700948 * @return A pre-compiled {@link SQLiteStatement} object. Note that
949 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 */
951 public SQLiteStatement compileStatement(String sql) throws SQLException {
Jeff Browne5360fb2011-10-31 17:48:13 -0700952 throwIfNotOpen(); // fail fast
Vasu Nori0732f792010-07-29 17:24:12 -0700953 return new SQLiteStatement(this, sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
956 /**
957 * Query the given URL, returning a {@link Cursor} over the result set.
958 *
959 * @param distinct true if you want each row to be unique, false otherwise.
960 * @param table The table name to compile the query against.
961 * @param columns A list of which columns to return. Passing null will
962 * return all columns, which is discouraged to prevent reading
963 * data from storage that isn't going to be used.
964 * @param selection A filter declaring which rows to return, formatted as an
965 * SQL WHERE clause (excluding the WHERE itself). Passing null
966 * will return all rows for the given table.
967 * @param selectionArgs You may include ?s in selection, which will be
968 * replaced by the values from selectionArgs, in order that they
969 * appear in the selection. The values will be bound as Strings.
970 * @param groupBy A filter declaring how to group rows, formatted as an SQL
971 * GROUP BY clause (excluding the GROUP BY itself). Passing null
972 * will cause the rows to not be grouped.
973 * @param having A filter declare which row groups to include in the cursor,
974 * if row grouping is being used, formatted as an SQL HAVING
975 * clause (excluding the HAVING itself). Passing null will cause
976 * all row groups to be included, and is required when row
977 * grouping is not being used.
978 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
979 * (excluding the ORDER BY itself). Passing null will use the
980 * default sort order, which may be unordered.
981 * @param limit Limits the number of rows returned by the query,
982 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700983 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
984 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 * @see Cursor
986 */
987 public Cursor query(boolean distinct, String table, String[] columns,
988 String selection, String[] selectionArgs, String groupBy,
989 String having, String orderBy, String limit) {
990 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800991 groupBy, having, orderBy, limit, null);
992 }
993
994 /**
995 * Query the given URL, returning a {@link Cursor} over the result set.
996 *
997 * @param distinct true if you want each row to be unique, false otherwise.
998 * @param table The table name to compile the query against.
999 * @param columns A list of which columns to return. Passing null will
1000 * return all columns, which is discouraged to prevent reading
1001 * data from storage that isn't going to be used.
1002 * @param selection A filter declaring which rows to return, formatted as an
1003 * SQL WHERE clause (excluding the WHERE itself). Passing null
1004 * will return all rows for the given table.
1005 * @param selectionArgs You may include ?s in selection, which will be
1006 * replaced by the values from selectionArgs, in order that they
1007 * appear in the selection. The values will be bound as Strings.
1008 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1009 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1010 * will cause the rows to not be grouped.
1011 * @param having A filter declare which row groups to include in the cursor,
1012 * if row grouping is being used, formatted as an SQL HAVING
1013 * clause (excluding the HAVING itself). Passing null will cause
1014 * all row groups to be included, and is required when row
1015 * grouping is not being used.
1016 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1017 * (excluding the ORDER BY itself). Passing null will use the
1018 * default sort order, which may be unordered.
1019 * @param limit Limits the number of rows returned by the query,
1020 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Brown4c1241d2012-02-02 17:05:00 -08001021 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001022 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1023 * when the query is executed.
1024 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1025 * {@link Cursor}s are not synchronized, see the documentation for more details.
1026 * @see Cursor
1027 */
1028 public Cursor query(boolean distinct, String table, String[] columns,
1029 String selection, String[] selectionArgs, String groupBy,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001030 String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001031 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001032 groupBy, having, orderBy, limit, cancellationSignal);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034
1035 /**
1036 * Query the given URL, returning a {@link Cursor} over the result set.
1037 *
1038 * @param cursorFactory the cursor factory to use, or null for the default factory
1039 * @param distinct true if you want each row to be unique, false otherwise.
1040 * @param table The table name to compile the query against.
1041 * @param columns A list of which columns to return. Passing null will
1042 * return all columns, which is discouraged to prevent reading
1043 * data from storage that isn't going to be used.
1044 * @param selection A filter declaring which rows to return, formatted as an
1045 * SQL WHERE clause (excluding the WHERE itself). Passing null
1046 * will return all rows for the given table.
1047 * @param selectionArgs You may include ?s in selection, which will be
1048 * replaced by the values from selectionArgs, in order that they
1049 * appear in the selection. The values will be bound as Strings.
1050 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1051 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1052 * will cause the rows to not be grouped.
1053 * @param having A filter declare which row groups to include in the cursor,
1054 * if row grouping is being used, formatted as an SQL HAVING
1055 * clause (excluding the HAVING itself). Passing null will cause
1056 * all row groups to be included, and is required when row
1057 * grouping is not being used.
1058 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1059 * (excluding the ORDER BY itself). Passing null will use the
1060 * default sort order, which may be unordered.
1061 * @param limit Limits the number of rows returned by the query,
1062 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001063 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1064 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 * @see Cursor
1066 */
1067 public Cursor queryWithFactory(CursorFactory cursorFactory,
1068 boolean distinct, String table, String[] columns,
1069 String selection, String[] selectionArgs, String groupBy,
1070 String having, String orderBy, String limit) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001071 return queryWithFactory(cursorFactory, distinct, table, columns, selection,
1072 selectionArgs, groupBy, having, orderBy, limit, null);
1073 }
1074
1075 /**
1076 * Query the given URL, returning a {@link Cursor} over the result set.
1077 *
1078 * @param cursorFactory the cursor factory to use, or null for the default factory
1079 * @param distinct true if you want each row to be unique, false otherwise.
1080 * @param table The table name to compile the query against.
1081 * @param columns A list of which columns to return. Passing null will
1082 * return all columns, which is discouraged to prevent reading
1083 * data from storage that isn't going to be used.
1084 * @param selection A filter declaring which rows to return, formatted as an
1085 * SQL WHERE clause (excluding the WHERE itself). Passing null
1086 * will return all rows for the given table.
1087 * @param selectionArgs You may include ?s in selection, which will be
1088 * replaced by the values from selectionArgs, in order that they
1089 * appear in the selection. The values will be bound as Strings.
1090 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1091 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1092 * will cause the rows to not be grouped.
1093 * @param having A filter declare which row groups to include in the cursor,
1094 * if row grouping is being used, formatted as an SQL HAVING
1095 * clause (excluding the HAVING itself). Passing null will cause
1096 * all row groups to be included, and is required when row
1097 * grouping is not being used.
1098 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1099 * (excluding the ORDER BY itself). Passing null will use the
1100 * default sort order, which may be unordered.
1101 * @param limit Limits the number of rows returned by the query,
1102 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Brown4c1241d2012-02-02 17:05:00 -08001103 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001104 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1105 * when the query is executed.
1106 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1107 * {@link Cursor}s are not synchronized, see the documentation for more details.
1108 * @see Cursor
1109 */
1110 public Cursor queryWithFactory(CursorFactory cursorFactory,
1111 boolean distinct, String table, String[] columns,
1112 String selection, String[] selectionArgs, String groupBy,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001113 String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001114 throwIfNotOpen(); // fail fast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 String sql = SQLiteQueryBuilder.buildQueryString(
1116 distinct, table, columns, selection, groupBy, having, orderBy, limit);
1117
Jeff Brown75ea64f2012-01-25 19:37:13 -08001118 return rawQueryWithFactory(cursorFactory, sql, selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001119 findEditTable(table), cancellationSignal);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121
1122 /**
1123 * Query the given table, returning a {@link Cursor} over the result set.
1124 *
1125 * @param table The table name to compile the query against.
1126 * @param columns A list of which columns to return. Passing null will
1127 * return all columns, which is discouraged to prevent reading
1128 * data from storage that isn't going to be used.
1129 * @param selection A filter declaring which rows to return, formatted as an
1130 * SQL WHERE clause (excluding the WHERE itself). Passing null
1131 * will return all rows for the given table.
1132 * @param selectionArgs You may include ?s in selection, which will be
1133 * replaced by the values from selectionArgs, in order that they
1134 * appear in the selection. The values will be bound as Strings.
1135 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1136 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1137 * will cause the rows to not be grouped.
1138 * @param having A filter declare which row groups to include in the cursor,
1139 * if row grouping is being used, formatted as an SQL HAVING
1140 * clause (excluding the HAVING itself). Passing null will cause
1141 * all row groups to be included, and is required when row
1142 * grouping is not being used.
1143 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1144 * (excluding the ORDER BY itself). Passing null will use the
1145 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001146 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1147 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 * @see Cursor
1149 */
1150 public Cursor query(String table, String[] columns, String selection,
1151 String[] selectionArgs, String groupBy, String having,
1152 String orderBy) {
1153
1154 return query(false, table, columns, selection, selectionArgs, groupBy,
1155 having, orderBy, null /* limit */);
1156 }
1157
1158 /**
1159 * Query the given table, returning a {@link Cursor} over the result set.
1160 *
1161 * @param table The table name to compile the query against.
1162 * @param columns A list of which columns to return. Passing null will
1163 * return all columns, which is discouraged to prevent reading
1164 * data from storage that isn't going to be used.
1165 * @param selection A filter declaring which rows to return, formatted as an
1166 * SQL WHERE clause (excluding the WHERE itself). Passing null
1167 * will return all rows for the given table.
1168 * @param selectionArgs You may include ?s in selection, which will be
1169 * replaced by the values from selectionArgs, in order that they
1170 * appear in the selection. The values will be bound as Strings.
1171 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1172 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1173 * will cause the rows to not be grouped.
1174 * @param having A filter declare which row groups to include in the cursor,
1175 * if row grouping is being used, formatted as an SQL HAVING
1176 * clause (excluding the HAVING itself). Passing null will cause
1177 * all row groups to be included, and is required when row
1178 * grouping is not being used.
1179 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1180 * (excluding the ORDER BY itself). Passing null will use the
1181 * default sort order, which may be unordered.
1182 * @param limit Limits the number of rows returned by the query,
1183 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001184 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1185 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 * @see Cursor
1187 */
1188 public Cursor query(String table, String[] columns, String selection,
1189 String[] selectionArgs, String groupBy, String having,
1190 String orderBy, String limit) {
1191
1192 return query(false, table, columns, selection, selectionArgs, groupBy,
1193 having, orderBy, limit);
1194 }
1195
1196 /**
1197 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1198 *
1199 * @param sql the SQL query. The SQL string must not be ; terminated
1200 * @param selectionArgs You may include ?s in where clause in the query,
1201 * which will be replaced by the values from selectionArgs. The
1202 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001203 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1204 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 */
1206 public Cursor rawQuery(String sql, String[] selectionArgs) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001207 return rawQueryWithFactory(null, sql, selectionArgs, null, null);
1208 }
1209
1210 /**
1211 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1212 *
1213 * @param sql the SQL query. The SQL string must not be ; terminated
1214 * @param selectionArgs You may include ?s in where clause in the query,
1215 * which will be replaced by the values from selectionArgs. The
1216 * values will be bound as Strings.
Jeff Brown4c1241d2012-02-02 17:05:00 -08001217 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001218 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1219 * when the query is executed.
1220 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1221 * {@link Cursor}s are not synchronized, see the documentation for more details.
1222 */
1223 public Cursor rawQuery(String sql, String[] selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001224 CancellationSignal cancellationSignal) {
1225 return rawQueryWithFactory(null, sql, selectionArgs, null, cancellationSignal);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227
1228 /**
1229 * Runs the provided SQL and returns a cursor over the result set.
1230 *
1231 * @param cursorFactory the cursor factory to use, or null for the default factory
1232 * @param sql the SQL query. The SQL string must not be ; terminated
1233 * @param selectionArgs You may include ?s in where clause in the query,
1234 * which will be replaced by the values from selectionArgs. The
1235 * values will be bound as Strings.
1236 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001237 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1238 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 */
1240 public Cursor rawQueryWithFactory(
1241 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1242 String editTable) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001243 return rawQueryWithFactory(cursorFactory, sql, selectionArgs, editTable, null);
1244 }
1245
1246 /**
1247 * Runs the provided SQL and returns a cursor over the result set.
1248 *
1249 * @param cursorFactory the cursor factory to use, or null for the default factory
1250 * @param sql the SQL query. The SQL string must not be ; terminated
1251 * @param selectionArgs You may include ?s in where clause in the query,
1252 * which will be replaced by the values from selectionArgs. The
1253 * values will be bound as Strings.
1254 * @param editTable the name of the first table, which is editable
Jeff Brown4c1241d2012-02-02 17:05:00 -08001255 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001256 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1257 * when the query is executed.
1258 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1259 * {@link Cursor}s are not synchronized, see the documentation for more details.
1260 */
1261 public Cursor rawQueryWithFactory(
1262 CursorFactory cursorFactory, String sql, String[] selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001263 String editTable, CancellationSignal cancellationSignal) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001264 throwIfNotOpen(); // fail fast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265
Jeff Brown75ea64f2012-01-25 19:37:13 -08001266 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, editTable,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001267 cancellationSignal);
Jeff Browne5360fb2011-10-31 17:48:13 -07001268 return driver.query(cursorFactory != null ? cursorFactory : mCursorFactory,
1269 selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271
1272 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 * Convenience method for inserting a row into the database.
1274 *
1275 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001276 * @param nullColumnHack optional; may be <code>null</code>.
1277 * SQL doesn't allow inserting a completely empty row without
1278 * naming at least one column name. If your provided <code>values</code> is
1279 * empty, no column names are known and an empty row can't be inserted.
1280 * If not set to null, the <code>nullColumnHack</code> parameter
1281 * provides the name of nullable column name to explicitly insert a NULL into
1282 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * @param values this map contains the initial column values for the
1284 * row. The keys should be the column names and the values the
1285 * column values
1286 * @return the row ID of the newly inserted row, or -1 if an error occurred
1287 */
1288 public long insert(String table, String nullColumnHack, ContentValues values) {
1289 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001290 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 } catch (SQLException e) {
1292 Log.e(TAG, "Error inserting " + values, e);
1293 return -1;
1294 }
1295 }
1296
1297 /**
1298 * Convenience method for inserting a row into the database.
1299 *
1300 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001301 * @param nullColumnHack optional; may be <code>null</code>.
1302 * SQL doesn't allow inserting a completely empty row without
1303 * naming at least one column name. If your provided <code>values</code> is
1304 * empty, no column names are known and an empty row can't be inserted.
1305 * If not set to null, the <code>nullColumnHack</code> parameter
1306 * provides the name of nullable column name to explicitly insert a NULL into
1307 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * @param values this map contains the initial column values for the
1309 * row. The keys should be the column names and the values the
1310 * column values
1311 * @throws SQLException
1312 * @return the row ID of the newly inserted row, or -1 if an error occurred
1313 */
1314 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1315 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001316 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
1318
1319 /**
1320 * Convenience method for replacing a row in the database.
1321 *
1322 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001323 * @param nullColumnHack optional; may be <code>null</code>.
1324 * SQL doesn't allow inserting a completely empty row without
1325 * naming at least one column name. If your provided <code>initialValues</code> is
1326 * empty, no column names are known and an empty row can't be inserted.
1327 * If not set to null, the <code>nullColumnHack</code> parameter
1328 * provides the name of nullable column name to explicitly insert a NULL into
1329 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001331 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 * @return the row ID of the newly inserted row, or -1 if an error occurred
1333 */
1334 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1335 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001336 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001337 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 } catch (SQLException e) {
1339 Log.e(TAG, "Error inserting " + initialValues, e);
1340 return -1;
1341 }
1342 }
1343
1344 /**
1345 * Convenience method for replacing a row in the database.
1346 *
1347 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001348 * @param nullColumnHack optional; may be <code>null</code>.
1349 * SQL doesn't allow inserting a completely empty row without
1350 * naming at least one column name. If your provided <code>initialValues</code> is
1351 * empty, no column names are known and an empty row can't be inserted.
1352 * If not set to null, the <code>nullColumnHack</code> parameter
1353 * provides the name of nullable column name to explicitly insert a NULL into
1354 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * @param initialValues this map contains the initial column values for
1356 * the row. The key
1357 * @throws SQLException
1358 * @return the row ID of the newly inserted row, or -1 if an error occurred
1359 */
1360 public long replaceOrThrow(String table, String nullColumnHack,
1361 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001362 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001363 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365
1366 /**
1367 * General method for inserting a row into the database.
1368 *
1369 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001370 * @param nullColumnHack optional; may be <code>null</code>.
1371 * SQL doesn't allow inserting a completely empty row without
1372 * naming at least one column name. If your provided <code>initialValues</code> is
1373 * empty, no column names are known and an empty row can't be inserted.
1374 * If not set to null, the <code>nullColumnHack</code> parameter
1375 * provides the name of nullable column name to explicitly insert a NULL into
1376 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 * @param initialValues this map contains the initial column values for the
1378 * row. The keys should be the column names and the values the
1379 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001380 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001381 * @return the row ID of the newly inserted row
1382 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001383 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001384 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 */
1386 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001387 ContentValues initialValues, int conflictAlgorithm) {
Vasu Nori0732f792010-07-29 17:24:12 -07001388 StringBuilder sql = new StringBuilder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001390 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 sql.append(" INTO ");
1392 sql.append(table);
Vasu Nori0732f792010-07-29 17:24:12 -07001393 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
Vasu Nori0732f792010-07-29 17:24:12 -07001395 Object[] bindArgs = null;
1396 int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
1397 if (size > 0) {
1398 bindArgs = new Object[size];
1399 int i = 0;
1400 for (String colName : initialValues.keySet()) {
1401 sql.append((i > 0) ? "," : "");
1402 sql.append(colName);
1403 bindArgs[i++] = initialValues.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 sql.append(')');
Vasu Nori0732f792010-07-29 17:24:12 -07001406 sql.append(" VALUES (");
1407 for (i = 0; i < size; i++) {
1408 sql.append((i > 0) ? ",?" : "?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
Vasu Nori0732f792010-07-29 17:24:12 -07001410 } else {
1411 sql.append(nullColumnHack + ") VALUES (NULL");
1412 }
1413 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414
Vasu Nori0732f792010-07-29 17:24:12 -07001415 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1416 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001417 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001419 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 }
1422
1423 /**
1424 * Convenience method for deleting rows in the database.
1425 *
1426 * @param table the table to delete from
1427 * @param whereClause the optional WHERE clause to apply when deleting.
1428 * Passing null will delete all rows.
1429 * @return the number of rows affected if a whereClause is passed in, 0
1430 * otherwise. To remove all rows and get a count pass "1" as the
1431 * whereClause.
1432 */
1433 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Nori0732f792010-07-29 17:24:12 -07001434 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1435 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001437 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001439 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 }
1442
1443 /**
1444 * Convenience method for updating rows in the database.
1445 *
1446 * @param table the table to update in
1447 * @param values a map from column names to new column values. null is a
1448 * valid value that will be translated to NULL.
1449 * @param whereClause the optional WHERE clause to apply when updating.
1450 * Passing null will update all rows.
1451 * @return the number of rows affected
1452 */
1453 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001454 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 /**
1458 * Convenience method for updating rows in the database.
1459 *
1460 * @param table the table to update in
1461 * @param values a map from column names to new column values. null is a
1462 * valid value that will be translated to NULL.
1463 * @param whereClause the optional WHERE clause to apply when updating.
1464 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001465 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001468 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001469 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001470 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 throw new IllegalArgumentException("Empty values");
1472 }
1473
1474 StringBuilder sql = new StringBuilder(120);
1475 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001476 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 sql.append(table);
1478 sql.append(" SET ");
1479
Vasu Nori0732f792010-07-29 17:24:12 -07001480 // move all bind args to one array
Brian Muramatsu46a88512010-11-12 13:53:57 -08001481 int setValuesSize = values.size();
Vasu Nori0732f792010-07-29 17:24:12 -07001482 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1483 Object[] bindArgs = new Object[bindArgsSize];
1484 int i = 0;
1485 for (String colName : values.keySet()) {
1486 sql.append((i > 0) ? "," : "");
1487 sql.append(colName);
1488 bindArgs[i++] = values.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 sql.append("=?");
Vasu Nori0732f792010-07-29 17:24:12 -07001490 }
1491 if (whereArgs != null) {
1492 for (i = setValuesSize; i < bindArgsSize; i++) {
1493 bindArgs[i] = whereArgs[i - setValuesSize];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 if (!TextUtils.isEmpty(whereClause)) {
1497 sql.append(" WHERE ");
1498 sql.append(whereClause);
1499 }
1500
Vasu Nori0732f792010-07-29 17:24:12 -07001501 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001503 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001505 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
1508
1509 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001510 * Execute a single SQL statement that is NOT a SELECT
1511 * or any other SQL statement that returns data.
1512 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001513 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001514 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1515 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1516 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001517 * <p>
1518 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1519 * automatically managed by this class. So, do not set journal_mode
1520 * using "PRAGMA journal_mode'<value>" statement if your app is using
1521 * {@link #enableWriteAheadLogging()}
1522 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 *
Vasu Noriccd95442010-05-28 17:04:16 -07001524 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1525 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001526 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001528 public void execSQL(String sql) throws SQLException {
Vasu Nori16057fa2011-03-18 11:40:37 -07001529 executeSql(sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531
1532 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001533 * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
1534 * <p>
1535 * For INSERT statements, use any of the following instead.
1536 * <ul>
1537 * <li>{@link #insert(String, String, ContentValues)}</li>
1538 * <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
1539 * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
1540 * </ul>
1541 * <p>
1542 * For UPDATE statements, use any of the following instead.
1543 * <ul>
1544 * <li>{@link #update(String, ContentValues, String, String[])}</li>
1545 * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
1546 * </ul>
1547 * <p>
1548 * For DELETE statements, use any of the following instead.
1549 * <ul>
1550 * <li>{@link #delete(String, String, String[])}</li>
1551 * </ul>
1552 * <p>
1553 * For example, the following are good candidates for using this method:
1554 * <ul>
1555 * <li>ALTER TABLE</li>
1556 * <li>CREATE or DROP table / trigger / view / index / virtual table</li>
1557 * <li>REINDEX</li>
1558 * <li>RELEASE</li>
1559 * <li>SAVEPOINT</li>
1560 * <li>PRAGMA that returns no data</li>
1561 * </ul>
1562 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001563 * <p>
1564 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1565 * automatically managed by this class. So, do not set journal_mode
1566 * using "PRAGMA journal_mode'<value>" statement if your app is using
1567 * {@link #enableWriteAheadLogging()}
1568 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 *
Vasu Noriccd95442010-05-28 17:04:16 -07001570 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1571 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001573 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001575 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if (bindArgs == null) {
1577 throw new IllegalArgumentException("Empty bindArgs");
1578 }
Vasu Norib83cb7c2010-09-14 13:36:01 -07001579 executeSql(sql, bindArgs);
Vasu Norice38b982010-07-22 13:57:13 -07001580 }
1581
Vasu Nori54025902010-09-14 12:14:26 -07001582 private int executeSql(String sql, Object[] bindArgs) throws SQLException {
Vasu Noricc1eaf62011-03-14 19:22:16 -07001583 if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001584 boolean disableWal = false;
1585 synchronized (mLock) {
1586 if (!mHasAttachedDbsLocked) {
1587 mHasAttachedDbsLocked = true;
1588 disableWal = true;
1589 }
1590 }
1591 if (disableWal) {
1592 disableWriteAheadLogging();
1593 }
Vasu Noricc1eaf62011-03-14 19:22:16 -07001594 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001595
Vasu Nori0732f792010-07-29 17:24:12 -07001596 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 try {
Vasu Nori16057fa2011-03-18 11:40:37 -07001598 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001600 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001605 * Returns true if the database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001607 * @return True if database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 */
1609 public boolean isReadOnly() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001610 synchronized (mLock) {
1611 return isReadOnlyLocked();
1612 }
1613 }
1614
1615 private boolean isReadOnlyLocked() {
1616 return (mConfigurationLocked.openFlags & OPEN_READ_MASK) == OPEN_READONLY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
1619 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001620 * Returns true if the database is in-memory db.
1621 *
1622 * @return True if the database is in-memory.
1623 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001625 public boolean isInMemoryDatabase() {
1626 synchronized (mLock) {
1627 return mConfigurationLocked.isInMemoryDb();
1628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 }
1630
Jeff Browne5360fb2011-10-31 17:48:13 -07001631 /**
1632 * Returns true if the database is currently open.
1633 *
1634 * @return True if the database is currently open (has not been closed).
1635 */
1636 public boolean isOpen() {
1637 synchronized (mLock) {
1638 return mConnectionPoolLocked != null;
1639 }
1640 }
1641
1642 /**
1643 * Returns true if the new version code is greater than the current database version.
1644 *
1645 * @param newVersion The new version code.
1646 * @return True if the new version code is greater than the current database version.
1647 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 public boolean needUpgrade(int newVersion) {
1649 return newVersion > getVersion();
1650 }
1651
1652 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001653 * Gets the path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001655 * @return The path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 */
1657 public final String getPath() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001658 synchronized (mLock) {
1659 return mConfigurationLocked.path;
Christopher Tatead9e8b12011-10-05 17:49:26 -07001660 }
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001661 }
1662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 /**
1664 * Sets the locale for this database. Does nothing if this database has
1665 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
Jeff Browne5360fb2011-10-31 17:48:13 -07001666 *
1667 * @param locale The new locale.
1668 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 * @throws SQLException if the locale could not be set. The most common reason
1670 * for this is that there is no collator available for the locale you requested.
1671 * In this case the database remains unchanged.
1672 */
1673 public void setLocale(Locale locale) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001674 if (locale == null) {
1675 throw new IllegalArgumentException("locale must not be null.");
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001676 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001677
Jeff Browne5360fb2011-10-31 17:48:13 -07001678 synchronized (mLock) {
1679 throwIfNotOpenLocked();
1680 mConfigurationLocked.locale = locale;
1681 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Vasu Norib729dcc2010-09-14 11:35:49 -07001682 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001683 }
1684
Vasu Norie495d1f2010-01-06 16:34:19 -08001685 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001686 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08001687 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07001688 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07001689 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07001690 * If this method is called with smaller size than the current maximum value,
1691 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07001692 *<p>
1693 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08001694 *
Vasu Nori90a367262010-04-12 12:49:09 -07001695 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
Jeff Browne5360fb2011-10-31 17:48:13 -07001696 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE}.
Vasu Norie495d1f2010-01-06 16:34:19 -08001697 */
Vasu Nori54025902010-09-14 12:14:26 -07001698 public void setMaxSqlCacheSize(int cacheSize) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001699 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
1700 throw new IllegalStateException(
1701 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
Vasu Nori587423a2010-09-27 18:18:34 -07001702 }
Vasu Nori587423a2010-09-27 18:18:34 -07001703
Jeff Browne5360fb2011-10-31 17:48:13 -07001704 synchronized (mLock) {
1705 throwIfNotOpenLocked();
1706 mConfigurationLocked.maxSqlCacheSize = cacheSize;
1707 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001708 }
1709 }
1710
Vasu Nori6c354da2010-04-26 23:33:39 -07001711 /**
1712 * This method enables parallel execution of queries from multiple threads on the same database.
1713 * It does this by opening multiple handles to the database and using a different
1714 * database handle for each query.
1715 * <p>
1716 * If a transaction is in progress on one connection handle and say, a table is updated in the
1717 * transaction, then query on the same table on another connection handle will block for the
1718 * transaction to complete. But this method enables such queries to execute by having them
1719 * return old version of the data from the table. Most often it is the data that existed in the
1720 * table prior to the above transaction updates on that table.
1721 * <p>
1722 * Maximum number of simultaneous handles used to execute queries in parallel is
1723 * dependent upon the device memory and possibly other properties.
1724 * <p>
1725 * After calling this method, execution of queries in parallel is enabled as long as this
1726 * database handle is open. To disable execution of queries in parallel, database should
1727 * be closed and reopened.
1728 * <p>
1729 * If a query is part of a transaction, then it is executed on the same database handle the
1730 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07001731 * <p>
1732 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07001733 * possible. In such cases, a message is printed to logcat and false is returned.
1734 * <p>
1735 * This feature is not available for :memory: databases. In such cases,
1736 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07001737 * <p>
1738 * A typical way to use this method is the following:
1739 * <pre>
1740 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
1741 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
1742 * db.enableWriteAheadLogging();
1743 * </pre>
1744 * <p>
1745 * Writers should use {@link #beginTransactionNonExclusive()} or
1746 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
1747 * to start a trsnsaction.
1748 * Non-exclusive mode allows database file to be in readable by threads executing queries.
1749 * </p>
1750 *
Vasu Noria98cb262010-06-22 13:16:35 -07001751 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07001752 */
Vasu Noriffe06122010-09-27 12:32:57 -07001753 public boolean enableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001754 synchronized (mLock) {
1755 throwIfNotOpenLocked();
1756
1757 if (mIsWALEnabledLocked) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001758 return true;
1759 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001760
1761 if (isReadOnlyLocked()) {
1762 // WAL doesn't make sense for readonly-databases.
1763 // TODO: True, but connection pooling does still make sense...
1764 return false;
1765 }
1766
1767 if (mConfigurationLocked.isInMemoryDb()) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001768 Log.i(TAG, "can't enable WAL for memory databases.");
1769 return false;
1770 }
1771
1772 // make sure this database has NO attached databases because sqlite's write-ahead-logging
1773 // doesn't work for databases with attached databases
Jeff Browne5360fb2011-10-31 17:48:13 -07001774 if (mHasAttachedDbsLocked) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001775 if (Log.isLoggable(TAG, Log.DEBUG)) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001776 Log.d(TAG, "this database: " + mConfigurationLocked.label
1777 + " has attached databases. can't enable WAL.");
Paul Westbrookdae6d372011-02-17 10:59:56 -08001778 }
1779 return false;
1780 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001781
1782 mIsWALEnabledLocked = true;
Jeff Brown5936ff02012-02-29 21:03:20 -08001783 mConfigurationLocked.maxConnectionPoolSize = SQLiteGlobal.getWALConnectionPoolSize();
1784 mConfigurationLocked.journalMode = "WAL";
Jeff Browne5360fb2011-10-31 17:48:13 -07001785 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Paul Westbrookdae6d372011-02-17 10:59:56 -08001786 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001787 return true;
Vasu Nori6c354da2010-04-26 23:33:39 -07001788 }
1789
Vasu Nori2827d6d2010-07-04 00:26:18 -07001790 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07001791 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
1792 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07001793 */
Vasu Nori7b04c412010-07-20 10:31:21 -07001794 public void disableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001795 synchronized (mLock) {
1796 throwIfNotOpenLocked();
1797
1798 if (!mIsWALEnabledLocked) {
1799 return;
Paul Westbrookdae6d372011-02-17 10:59:56 -08001800 }
Vasu Nori8d111032010-06-22 18:34:21 -07001801
Jeff Browne5360fb2011-10-31 17:48:13 -07001802 mIsWALEnabledLocked = false;
1803 mConfigurationLocked.maxConnectionPoolSize = 1;
Jeff Brown5936ff02012-02-29 21:03:20 -08001804 mConfigurationLocked.journalMode = SQLiteGlobal.getDefaultJournalMode();
Jeff Browne5360fb2011-10-31 17:48:13 -07001805 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Vasu Nori65a88832010-07-16 15:14:08 -07001806 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001807 }
1808
Vasu Norif3cf8a42010-03-23 11:41:44 -07001809 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001810 * Collect statistics about all open databases in the current process.
1811 * Used by bug report.
Vasu Norif3cf8a42010-03-23 11:41:44 -07001812 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001813 static ArrayList<DbStats> getDbStats() {
Vasu Noric3849202010-03-09 10:47:25 -08001814 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001815 for (SQLiteDatabase db : getActiveDatabases()) {
1816 db.collectDbStats(dbStatsList);
Vasu Nori24675612010-09-27 14:54:19 -07001817 }
Vasu Noric3849202010-03-09 10:47:25 -08001818 return dbStatsList;
1819 }
1820
Jeff Browne5360fb2011-10-31 17:48:13 -07001821 private void collectDbStats(ArrayList<DbStats> dbStatsList) {
1822 synchronized (mLock) {
1823 if (mConnectionPoolLocked != null) {
1824 mConnectionPoolLocked.collectDbStats(dbStatsList);
1825 }
1826 }
1827 }
1828
1829 private static ArrayList<SQLiteDatabase> getActiveDatabases() {
1830 ArrayList<SQLiteDatabase> databases = new ArrayList<SQLiteDatabase>();
1831 synchronized (sActiveDatabases) {
1832 databases.addAll(sActiveDatabases.keySet());
1833 }
1834 return databases;
1835 }
1836
1837 /**
1838 * Dump detailed information about all open databases in the current process.
1839 * Used by bug report.
1840 */
Jeff Browna9be4152012-01-18 15:29:57 -08001841 static void dumpAll(Printer printer, boolean verbose) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001842 for (SQLiteDatabase db : getActiveDatabases()) {
Jeff Browna9be4152012-01-18 15:29:57 -08001843 db.dump(printer, verbose);
Jeff Browne5360fb2011-10-31 17:48:13 -07001844 }
1845 }
1846
Jeff Browna9be4152012-01-18 15:29:57 -08001847 private void dump(Printer printer, boolean verbose) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001848 synchronized (mLock) {
1849 if (mConnectionPoolLocked != null) {
1850 printer.println("");
Jeff Browna9be4152012-01-18 15:29:57 -08001851 mConnectionPoolLocked.dump(printer, verbose);
Jeff Browne5360fb2011-10-31 17:48:13 -07001852 }
1853 }
1854 }
1855
Vasu Noric3849202010-03-09 10:47:25 -08001856 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001857 * Returns list of full pathnames of all attached databases including the main database
1858 * by executing 'pragma database_list' on the database.
1859 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001860 * @return ArrayList of pairs of (database name, database file path) or null if the database
1861 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08001862 */
Vasu Noria017eda2011-01-27 10:52:55 -08001863 public List<Pair<String, String>> getAttachedDbs() {
Vasu Noric3849202010-03-09 10:47:25 -08001864 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001865 synchronized (mLock) {
1866 if (mConnectionPoolLocked == null) {
1867 return null; // not open
1868 }
1869
1870 if (!mHasAttachedDbsLocked) {
1871 // No attached databases.
1872 // There is a small window where attached databases exist but this flag is not
1873 // set yet. This can occur when this thread is in a race condition with another
1874 // thread that is executing the SQL statement: "attach database <blah> as <foo>"
1875 // If this thread is NOT ok with such a race condition (and thus possibly not
1876 // receivethe entire list of attached databases), then the caller should ensure
1877 // that no thread is executing any SQL statements while a thread is calling this
1878 // method. Typically, this method is called when 'adb bugreport' is done or the
1879 // caller wants to collect stats on the database and all its attached databases.
1880 attachedDbs.add(new Pair<String, String>("main", mConfigurationLocked.path));
1881 return attachedDbs;
1882 }
Vasu Nori24675612010-09-27 14:54:19 -07001883 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001884
Vasu Nori24675612010-09-27 14:54:19 -07001885 // has attached databases. query sqlite to get the list of attached databases.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001886 Cursor c = null;
1887 try {
1888 c = rawQuery("pragma database_list;", null);
1889 while (c.moveToNext()) {
1890 // sqlite returns a row for each database in the returned list of databases.
1891 // in each row,
1892 // 1st column is the database name such as main, or the database
1893 // name specified on the "ATTACH" command
1894 // 2nd column is the database file path.
1895 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
1896 }
1897 } finally {
1898 if (c != null) {
1899 c.close();
1900 }
Vasu Noric3849202010-03-09 10:47:25 -08001901 }
Vasu Noric3849202010-03-09 10:47:25 -08001902 return attachedDbs;
1903 }
1904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001906 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
1907 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001908 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07001909 *<p>
1910 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001911 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07001912 *<p>
1913 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001914 *
1915 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07001916 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001917 */
1918 public boolean isDatabaseIntegrityOk() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001919 throwIfNotOpen(); // fail fast
1920
Vasu Noria017eda2011-01-27 10:52:55 -08001921 List<Pair<String, String>> attachedDbs = null;
Vasu Noribfe1dc22010-08-25 16:29:02 -07001922 try {
1923 attachedDbs = getAttachedDbs();
1924 if (attachedDbs == null) {
1925 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
1926 "be retrieved. probably because the database is closed");
1927 }
1928 } catch (SQLiteException e) {
1929 // can't get attachedDb list. do integrity check on the main database
1930 attachedDbs = new ArrayList<Pair<String, String>>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001931 attachedDbs.add(new Pair<String, String>("main", getPath()));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001932 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001933
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001934 for (int i = 0; i < attachedDbs.size(); i++) {
1935 Pair<String, String> p = attachedDbs.get(i);
1936 SQLiteStatement prog = null;
1937 try {
1938 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
1939 String rslt = prog.simpleQueryForString();
1940 if (!rslt.equalsIgnoreCase("ok")) {
1941 // integrity_checker failed on main or attached databases
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001942 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
Vasu Noribfe1dc22010-08-25 16:29:02 -07001943 return false;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001944 }
1945 } finally {
1946 if (prog != null) prog.close();
1947 }
1948 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07001949 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001950 }
1951
Jeff Browne5360fb2011-10-31 17:48:13 -07001952 @Override
1953 public String toString() {
1954 return "SQLiteDatabase: " + getPath();
1955 }
1956
1957 private void throwIfNotOpen() {
1958 synchronized (mConnectionPoolLocked) {
1959 throwIfNotOpenLocked();
1960 }
1961 }
1962
1963 private void throwIfNotOpenLocked() {
1964 if (mConnectionPoolLocked == null) {
1965 throw new IllegalStateException("The database '" + mConfigurationLocked.label
1966 + "' is not open.");
1967 }
1968 }
Vasu Nori3ef94e22010-02-05 14:49:04 -08001969
1970 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001971 * Used to allow returning sub-classes of {@link Cursor} when calling query.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001973 public interface CursorFactory {
1974 /**
1975 * See {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
1976 */
1977 public Cursor newCursor(SQLiteDatabase db,
1978 SQLiteCursorDriver masterQuery, String editTable,
1979 SQLiteQuery query);
1980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981
1982 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001983 * A callback interface for a custom sqlite3 function.
1984 * This can be used to create a function that can be called from
1985 * sqlite3 database triggers.
1986 * @hide
Vasu Noric3849202010-03-09 10:47:25 -08001987 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001988 public interface CustomFunction {
1989 public void callback(String[] args);
1990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991}