blob: 049a615f8dc2fab247880403979319845ae0ca94 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.database.Cursor;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070023import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.database.DatabaseUtils;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070025import android.database.DefaultDatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.database.SQLException;
Vasu Noric3849202010-03-09 10:47:25 -080027import android.database.sqlite.SQLiteDebug.DbStats;
Jeff Browne5360fb2011-10-31 17:48:13 -070028import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070031import android.util.Log;
Vasu Noric3849202010-03-09 10:47:25 -080032import android.util.Pair;
Jeff Browne5360fb2011-10-31 17:48:13 -070033import android.util.Printer;
34
35import dalvik.system.CloseGuard;
36
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import java.io.File;
Jeff Brown79087e42012-03-01 19:52:44 -080038import java.io.FileFilter;
Vasu Noric3849202010-03-09 10:47:25 -080039import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import java.util.HashMap;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080041import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.util.Locale;
43import java.util.Map;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
46/**
47 * Exposes methods to manage a SQLite database.
Jeff Browne5360fb2011-10-31 17:48:13 -070048 *
49 * <p>
50 * SQLiteDatabase has methods to create, delete, execute SQL commands, and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 * perform other common database management tasks.
Jeff Browne5360fb2011-10-31 17:48:13 -070052 * </p><p>
53 * See the Notepad sample application in the SDK for an example of creating
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 * and managing a database.
Jeff Browne5360fb2011-10-31 17:48:13 -070055 * </p><p>
56 * Database names must be unique within an application, not across all applications.
57 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 *
59 * <h3>Localized Collation - ORDER BY</h3>
Jeff Browne5360fb2011-10-31 17:48:13 -070060 * <p>
61 * In addition to SQLite's default <code>BINARY</code> collator, Android supplies
62 * two more, <code>LOCALIZED</code>, which changes with the system's current locale,
63 * and <code>UNICODE</code>, which is the Unicode Collation Algorithm and not tailored
64 * to the current locale.
65 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 */
Jeff Brownbaefdfa2012-03-05 10:33:13 -080067public final class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070068 private static final String TAG = "SQLiteDatabase";
Jeff Browne5360fb2011-10-31 17:48:13 -070069
Jeff Hamilton082c2af2009-09-29 11:49:51 -070070 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Jeff Browne5360fb2011-10-31 17:48:13 -070072 // Stores reference to all databases opened in the current process.
73 // (The referent Object is not used at this time.)
74 // INVARIANT: Guarded by sActiveDatabases.
75 private static WeakHashMap<SQLiteDatabase, Object> sActiveDatabases =
76 new WeakHashMap<SQLiteDatabase, Object>();
77
78 // Thread-local for database sessions that belong to this database.
79 // Each thread has its own database session.
80 // INVARIANT: Immutable.
81 private final ThreadLocal<SQLiteSession> mThreadSession = new ThreadLocal<SQLiteSession>() {
82 @Override
83 protected SQLiteSession initialValue() {
84 return createSession();
85 }
86 };
87
88 // The optional factory to use when creating new Cursors. May be null.
89 // INVARIANT: Immutable.
90 private final CursorFactory mCursorFactory;
91
92 // Error handler to be used when SQLite returns corruption errors.
93 // INVARIANT: Immutable.
94 private final DatabaseErrorHandler mErrorHandler;
95
96 // Shared database state lock.
97 // This lock guards all of the shared state of the database, such as its
98 // configuration, whether it is open or closed, and so on. This lock should
99 // be held for as little time as possible.
100 //
101 // The lock MUST NOT be held while attempting to acquire database connections or
102 // while executing SQL statements on behalf of the client as it can lead to deadlock.
103 //
104 // It is ok to hold the lock while reconfiguring the connection pool or dumping
105 // statistics because those operations are non-reentrant and do not try to acquire
106 // connections that might be held by other threads.
107 //
108 // Basic rule: grab the lock, access or modify global state, release the lock, then
109 // do the required SQL work.
110 private final Object mLock = new Object();
111
112 // Warns if the database is finalized without being closed properly.
113 // INVARIANT: Guarded by mLock.
114 private final CloseGuard mCloseGuardLocked = CloseGuard.get();
115
116 // The database configuration.
117 // INVARIANT: Guarded by mLock.
118 private final SQLiteDatabaseConfiguration mConfigurationLocked;
119
120 // The connection pool for the database, null when closed.
121 // The pool itself is thread-safe, but the reference to it can only be acquired
122 // when the lock is held.
123 // INVARIANT: Guarded by mLock.
124 private SQLiteConnectionPool mConnectionPoolLocked;
125
126 // True if the database has attached databases.
127 // INVARIANT: Guarded by mLock.
128 private boolean mHasAttachedDbsLocked;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700131 * When a constraint violation occurs, an immediate ROLLBACK occurs,
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800132 * thus ending the current transaction, and the command aborts with a
133 * return code of SQLITE_CONSTRAINT. If no transaction is active
134 * (other than the implied transaction that is created on every command)
Jeff Browne5360fb2011-10-31 17:48:13 -0700135 * then this algorithm works the same as ABORT.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800136 */
137 public static final int CONFLICT_ROLLBACK = 1;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700138
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800139 /**
140 * When a constraint violation occurs,no ROLLBACK is executed
141 * so changes from prior commands within the same transaction
142 * are preserved. This is the default behavior.
143 */
144 public static final int CONFLICT_ABORT = 2;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700145
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800146 /**
147 * When a constraint violation occurs, the command aborts with a return
148 * code SQLITE_CONSTRAINT. But any changes to the database that
149 * the command made prior to encountering the constraint violation
150 * are preserved and are not backed out.
151 */
152 public static final int CONFLICT_FAIL = 3;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700153
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800154 /**
155 * When a constraint violation occurs, the one row that contains
156 * the constraint violation is not inserted or changed.
157 * But the command continues executing normally. Other rows before and
158 * after the row that contained the constraint violation continue to be
159 * inserted or updated normally. No error is returned.
160 */
161 public static final int CONFLICT_IGNORE = 4;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700162
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800163 /**
164 * When a UNIQUE constraint violation occurs, the pre-existing rows that
165 * are causing the constraint violation are removed prior to inserting
166 * or updating the current row. Thus the insert or update always occurs.
167 * The command continues executing normally. No error is returned.
168 * If a NOT NULL constraint violation occurs, the NULL value is replaced
169 * by the default value for that column. If the column has no default
170 * value, then the ABORT algorithm is used. If a CHECK constraint
171 * violation occurs then the IGNORE algorithm is used. When this conflict
172 * resolution strategy deletes rows in order to satisfy a constraint,
173 * it does not invoke delete triggers on those rows.
Jeff Browne5360fb2011-10-31 17:48:13 -0700174 * This behavior might change in a future release.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800175 */
176 public static final int CONFLICT_REPLACE = 5;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700177
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800178 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700179 * Use the following when no conflict action is specified.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800180 */
181 public static final int CONFLICT_NONE = 0;
Jeff Browne5360fb2011-10-31 17:48:13 -0700182
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800183 private static final String[] CONFLICT_VALUES = new String[]
184 {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 /**
187 * Maximum Length Of A LIKE Or GLOB Pattern
188 * The pattern matching algorithm used in the default LIKE and GLOB implementation
189 * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
190 * the pattern) for certain pathological cases. To avoid denial-of-service attacks
191 * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
192 * The default value of this limit is 50000. A modern workstation can evaluate
193 * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
194 * The denial of service problem only comes into play when the pattern length gets
195 * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
196 * are at most a few dozen bytes in length, paranoid application developers may
197 * want to reduce this parameter to something in the range of a few hundred
198 * if they know that external users are able to generate arbitrary patterns.
199 */
200 public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
201
202 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700203 * Open flag: Flag for {@link #openDatabase} to open the database for reading and writing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 * If the disk is full, this may fail even before you actually write anything.
205 *
206 * {@more} Note that the value of this flag is 0, so it is the default.
207 */
208 public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
209
210 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700211 * Open flag: Flag for {@link #openDatabase} to open the database for reading only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 * This is the only reliable way to open a database if the disk may be full.
213 */
214 public static final int OPEN_READONLY = 0x00000001; // update native code if changing
215
216 private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
217
218 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700219 * Open flag: Flag for {@link #openDatabase} to open the database without support for
220 * localized collators.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 *
222 * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
223 * You must be consistent when using this flag to use the setting the database was
224 * created with. If this is set, {@link #setLocale} will do nothing.
225 */
226 public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
227
228 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700229 * Open flag: Flag for {@link #openDatabase} to create the database file if it does not
230 * already exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 */
232 public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
233
234 /**
Jeff Brown47847f32012-03-22 19:13:11 -0700235 * Open flag: Flag for {@link #openDatabase} to open the database file with
236 * write-ahead logging enabled by default. Using this flag is more efficient
237 * than calling {@link #enableWriteAheadLogging}.
238 *
239 * Write-ahead logging cannot be used with read-only databases so the value of
240 * this flag is ignored if the database is opened read-only.
241 *
242 * @see #enableWriteAheadLogging
243 */
244 public static final int ENABLE_WRITE_AHEAD_LOGGING = 0x20000000;
245
246 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700247 * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}.
Vasu Norib729dcc2010-09-14 11:35:49 -0700248 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700249 * Each prepared-statement is between 1K - 6K, depending on the complexity of the
250 * SQL statement & schema. A large SQL cache may use a significant amount of memory.
Vasu Norie495d1f2010-01-06 16:34:19 -0800251 */
Vasu Nori90a367262010-04-12 12:49:09 -0700252 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Norib729dcc2010-09-14 11:35:49 -0700253
Jeff Browne5360fb2011-10-31 17:48:13 -0700254 private SQLiteDatabase(String path, int openFlags, CursorFactory cursorFactory,
255 DatabaseErrorHandler errorHandler) {
256 mCursorFactory = cursorFactory;
257 mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
258 mConfigurationLocked = new SQLiteDatabaseConfiguration(path, openFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700260
Jeff Browne5360fb2011-10-31 17:48:13 -0700261 @Override
262 protected void finalize() throws Throwable {
263 try {
264 dispose(true);
265 } finally {
266 super.finalize();
267 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700268 }
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 @Override
271 protected void onAllReferencesReleased() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700272 dispose(false);
273 }
274
275 private void dispose(boolean finalized) {
276 final SQLiteConnectionPool pool;
277 synchronized (mLock) {
278 if (mCloseGuardLocked != null) {
279 if (finalized) {
280 mCloseGuardLocked.warnIfOpen();
281 }
282 mCloseGuardLocked.close();
283 }
284
285 pool = mConnectionPoolLocked;
286 mConnectionPoolLocked = null;
287 }
288
289 if (!finalized) {
290 synchronized (sActiveDatabases) {
291 sActiveDatabases.remove(this);
292 }
293
294 if (pool != null) {
295 pool.close();
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298 }
299
300 /**
301 * Attempts to release memory that SQLite holds but does not require to
302 * operate properly. Typically this memory will come from the page cache.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700303 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * @return the number of bytes actually released
305 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700306 public static int releaseMemory() {
307 return SQLiteGlobal.releaseMemory();
308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309
310 /**
311 * Control whether or not the SQLiteDatabase is made thread-safe by using locks
312 * around critical sections. This is pretty expensive, so if you know that your
313 * DB will only be used by a single thread then you should set this to false.
314 * The default is true.
315 * @param lockingEnabled set to true to enable locks, false otherwise
Jeff Browne5360fb2011-10-31 17:48:13 -0700316 *
317 * @deprecated This method now does nothing. Do not use.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700319 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 public void setLockingEnabled(boolean lockingEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322
323 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700324 * Gets a label to use when describing the database in log messages.
325 * @return The label.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700327 String getLabel() {
328 synchronized (mLock) {
329 return mConfigurationLocked.label;
330 }
331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332
Jeff Browne5360fb2011-10-31 17:48:13 -0700333 /**
334 * Sends a corruption message to the database error handler.
335 */
336 void onCorruption() {
337 EventLog.writeEvent(EVENT_DB_CORRUPT, getLabel());
Vasu Noriccd95442010-05-28 17:04:16 -0700338 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340
341 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700342 * Gets the {@link SQLiteSession} that belongs to this thread for this database.
343 * Once a thread has obtained a session, it will continue to obtain the same
344 * session even after the database has been closed (although the session will not
345 * be usable). However, a thread that does not already have a session cannot
346 * obtain one after the database has been closed.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700347 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700348 * The idea is that threads that have active connections to the database may still
349 * have work to complete even after the call to {@link #close}. Active database
350 * connections are not actually disposed until they are released by the threads
351 * that own them.
352 *
353 * @return The session, never null.
354 *
355 * @throws IllegalStateException if the thread does not yet have a session and
356 * the database is not open.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700358 SQLiteSession getThreadSession() {
359 return mThreadSession.get(); // initialValue() throws if database closed
Vasu Nori6d970252010-10-05 10:48:49 -0700360 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700361
Jeff Browne5360fb2011-10-31 17:48:13 -0700362 SQLiteSession createSession() {
363 final SQLiteConnectionPool pool;
364 synchronized (mLock) {
365 throwIfNotOpenLocked();
366 pool = mConnectionPoolLocked;
Vasu Nori6d970252010-10-05 10:48:49 -0700367 }
Jeff Browne5360fb2011-10-31 17:48:13 -0700368 return new SQLiteSession(pool);
Vasu Norid4608a32011-02-03 16:24:06 -0800369 }
370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700372 * Gets default connection flags that are appropriate for this thread, taking into
373 * account whether the thread is acting on behalf of the UI.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700375 * @param readOnly True if the connection should be read-only.
376 * @return The connection flags.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700378 int getThreadDefaultConnectionFlags(boolean readOnly) {
379 int flags = readOnly ? SQLiteConnectionPool.CONNECTION_FLAG_READ_ONLY :
380 SQLiteConnectionPool.CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY;
381 if (isMainThread()) {
382 flags |= SQLiteConnectionPool.CONNECTION_FLAG_INTERACTIVE;
383 }
384 return flags;
Vasu Nori16057fa2011-03-18 11:40:37 -0700385 }
386
Jeff Browne5360fb2011-10-31 17:48:13 -0700387 private static boolean isMainThread() {
388 // FIXME: There should be a better way to do this.
389 // Would also be nice to have something that would work across Binder calls.
390 Looper looper = Looper.myLooper();
391 return looper != null && looper == Looper.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 }
393
394 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700395 * Begins a transaction in EXCLUSIVE mode.
396 * <p>
397 * Transactions can be nested.
398 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 * the work done in that transaction and all of the nested transactions will be committed or
400 * rolled back. The changes will be rolled back if any transaction is ended without being
401 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700402 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 * <p>Here is the standard idiom for transactions:
404 *
405 * <pre>
406 * db.beginTransaction();
407 * try {
408 * ...
409 * db.setTransactionSuccessful();
410 * } finally {
411 * db.endTransaction();
412 * }
413 * </pre>
414 */
415 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700416 beginTransaction(null /* transactionStatusCallback */, true);
417 }
418
419 /**
420 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
421 * the outer transaction is ended all of the work done in that transaction
422 * and all of the nested transactions will be committed or rolled back. The
423 * changes will be rolled back if any transaction is ended without being
424 * marked as clean (by calling setTransactionSuccessful). Otherwise they
425 * will be committed.
426 * <p>
427 * Here is the standard idiom for transactions:
428 *
429 * <pre>
430 * db.beginTransactionNonExclusive();
431 * try {
432 * ...
433 * db.setTransactionSuccessful();
434 * } finally {
435 * db.endTransaction();
436 * }
437 * </pre>
438 */
439 public void beginTransactionNonExclusive() {
440 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700441 }
442
443 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700444 * Begins a transaction in EXCLUSIVE mode.
445 * <p>
446 * Transactions can be nested.
447 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700448 * the work done in that transaction and all of the nested transactions will be committed or
449 * rolled back. The changes will be rolled back if any transaction is ended without being
450 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700451 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700452 * <p>Here is the standard idiom for transactions:
453 *
454 * <pre>
455 * db.beginTransactionWithListener(listener);
456 * try {
457 * ...
458 * db.setTransactionSuccessful();
459 * } finally {
460 * db.endTransaction();
461 * }
462 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700463 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700464 * @param transactionListener listener that should be notified when the transaction begins,
465 * commits, or is rolled back, either explicitly or by a call to
466 * {@link #yieldIfContendedSafely}.
467 */
468 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700469 beginTransaction(transactionListener, true);
470 }
471
472 /**
473 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
474 * the outer transaction is ended all of the work done in that transaction
475 * and all of the nested transactions will be committed or rolled back. The
476 * changes will be rolled back if any transaction is ended without being
477 * marked as clean (by calling setTransactionSuccessful). Otherwise they
478 * will be committed.
479 * <p>
480 * Here is the standard idiom for transactions:
481 *
482 * <pre>
483 * db.beginTransactionWithListenerNonExclusive(listener);
484 * try {
485 * ...
486 * db.setTransactionSuccessful();
487 * } finally {
488 * db.endTransaction();
489 * }
490 * </pre>
491 *
492 * @param transactionListener listener that should be notified when the
493 * transaction begins, commits, or is rolled back, either
494 * explicitly or by a call to {@link #yieldIfContendedSafely}.
495 */
496 public void beginTransactionWithListenerNonExclusive(
497 SQLiteTransactionListener transactionListener) {
498 beginTransaction(transactionListener, false);
499 }
500
501 private void beginTransaction(SQLiteTransactionListener transactionListener,
502 boolean exclusive) {
Jeff Brown03bd3022012-03-06 13:48:56 -0800503 acquireReference();
504 try {
505 getThreadSession().beginTransaction(
506 exclusive ? SQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
507 SQLiteSession.TRANSACTION_MODE_IMMEDIATE,
508 transactionListener,
509 getThreadDefaultConnectionFlags(false /*readOnly*/), null);
510 } finally {
511 releaseReference();
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
514
515 /**
516 * End a transaction. See beginTransaction for notes about how to use this and when transactions
517 * are committed and rolled back.
518 */
519 public void endTransaction() {
Jeff Brown03bd3022012-03-06 13:48:56 -0800520 acquireReference();
521 try {
522 getThreadSession().endTransaction(null);
523 } finally {
524 releaseReference();
525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 }
527
528 /**
529 * Marks the current transaction as successful. Do not do any more database work between
530 * calling this and calling endTransaction. Do as little non-database work as possible in that
531 * situation too. If any errors are encountered between this and endTransaction the transaction
532 * will still be committed.
533 *
534 * @throws IllegalStateException if the current thread is not in a transaction or the
535 * transaction is already marked as successful.
536 */
537 public void setTransactionSuccessful() {
Jeff Brown03bd3022012-03-06 13:48:56 -0800538 acquireReference();
539 try {
540 getThreadSession().setTransactionSuccessful();
541 } finally {
542 releaseReference();
543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
545
546 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700547 * Returns true if the current thread has a transaction pending.
548 *
549 * @return True if the current thread is in a transaction.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 */
551 public boolean inTransaction() {
Jeff Brown03bd3022012-03-06 13:48:56 -0800552 acquireReference();
553 try {
554 return getThreadSession().hasTransaction();
555 } finally {
556 releaseReference();
557 }
Vasu Norice38b982010-07-22 13:57:13 -0700558 }
559
560 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700561 * Returns true if the current thread is holding an active connection to the database.
Vasu Norice38b982010-07-22 13:57:13 -0700562 * <p>
Jeff Browne5360fb2011-10-31 17:48:13 -0700563 * The name of this method comes from a time when having an active connection
564 * to the database meant that the thread was holding an actual lock on the
565 * database. Nowadays, there is no longer a true "database lock" although threads
566 * may block if they cannot acquire a database connection to perform a
567 * particular operation.
568 * </p>
Vasu Norice38b982010-07-22 13:57:13 -0700569 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700570 * @return True if the current thread is holding an active connection to the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 */
572 public boolean isDbLockedByCurrentThread() {
Jeff Brown03bd3022012-03-06 13:48:56 -0800573 acquireReference();
574 try {
575 return getThreadSession().hasConnection();
576 } finally {
577 releaseReference();
578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580
581 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700582 * Always returns false.
583 * <p>
584 * There is no longer the concept of a database lock, so this method always returns false.
585 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700587 * @return False.
588 * @deprecated Always returns false. Do not use this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700590 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 public boolean isDbLockedByOtherThreads() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700592 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
594
595 /**
596 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
597 * successful so far. Do not call setTransactionSuccessful before calling this. When this
598 * returns a new transaction will have been created but not marked as successful.
599 * @return true if the transaction was yielded
600 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
601 * will not be yielded. Use yieldIfContendedSafely instead.
602 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700603 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700605 return yieldIfContendedHelper(false /* do not check yielding */,
606 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
608
609 /**
610 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
611 * successful so far. Do not call setTransactionSuccessful before calling this. When this
612 * returns a new transaction will have been created but not marked as successful. This assumes
613 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700614 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 * @return true if the transaction was yielded
616 */
617 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700618 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620
Fred Quintana5c7aede2009-08-27 21:41:27 -0700621 /**
622 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
623 * successful so far. Do not call setTransactionSuccessful before calling this. When this
624 * returns a new transaction will have been created but not marked as successful. This assumes
625 * that there are no nested transactions (beginTransaction has only been called once) and will
626 * throw an exception if that is not the case.
627 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
628 * the lock was actually yielded. This will allow other background threads to make some
629 * more progress than they would if we started the transaction immediately.
630 * @return true if the transaction was yielded
631 */
632 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
633 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
634 }
635
Jeff Browne5360fb2011-10-31 17:48:13 -0700636 private boolean yieldIfContendedHelper(boolean throwIfUnsafe, long sleepAfterYieldDelay) {
Jeff Brown03bd3022012-03-06 13:48:56 -0800637 acquireReference();
638 try {
639 return getThreadSession().yieldTransaction(sleepAfterYieldDelay, throwIfUnsafe, null);
640 } finally {
641 releaseReference();
642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 }
644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700646 * Deprecated.
Vasu Nori95675132010-07-21 16:24:40 -0700647 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 */
Vasu Nori95675132010-07-21 16:24:40 -0700649 @Deprecated
650 public Map<String, String> getSyncedTables() {
651 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
653
654 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * Open the database according to the flags {@link #OPEN_READWRITE}
656 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
657 *
658 * <p>Sets the locale of the database to the the system's current locale.
659 * Call {@link #setLocale} if you would like something else.</p>
660 *
661 * @param path to database file to open and/or create
662 * @param factory an optional factory class that is called to instantiate a
663 * cursor when query is called, or null for default
664 * @param flags to control database access mode
665 * @return the newly opened database
666 * @throws SQLiteException if the database cannot be opened
667 */
668 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Jeff Brown47847f32012-03-22 19:13:11 -0700669 return openDatabase(path, factory, flags, null);
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700670 }
671
672 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700673 * Open the database according to the flags {@link #OPEN_READWRITE}
674 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
675 *
676 * <p>Sets the locale of the database to the the system's current locale.
677 * Call {@link #setLocale} if you would like something else.</p>
678 *
679 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
680 * used to handle corruption when sqlite reports database corruption.</p>
681 *
682 * @param path to database file to open and/or create
683 * @param factory an optional factory class that is called to instantiate a
684 * cursor when query is called, or null for default
685 * @param flags to control database access mode
686 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
687 * when sqlite reports database corruption
688 * @return the newly opened database
689 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700690 */
691 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
692 DatabaseErrorHandler errorHandler) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700693 SQLiteDatabase db = new SQLiteDatabase(path, flags, factory, errorHandler);
694 db.open();
695 return db;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700696 }
697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 /**
699 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
700 */
701 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
702 return openOrCreateDatabase(file.getPath(), factory);
703 }
704
705 /**
706 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
707 */
708 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
Jeff Brown47847f32012-03-22 19:13:11 -0700709 return openDatabase(path, factory, CREATE_IF_NECESSARY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
712 /**
Vasu Nori6c354da2010-04-26 23:33:39 -0700713 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700714 */
715 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
716 DatabaseErrorHandler errorHandler) {
717 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
718 }
719
Jeff Brown559d0642012-02-29 10:19:12 -0800720 /**
Jeff Brown79087e42012-03-01 19:52:44 -0800721 * Deletes a database including its journal file and other auxiliary files
722 * that may have been created by the database engine.
723 *
724 * @param file The database file path.
725 * @return True if the database was successfully deleted.
726 */
727 public static boolean deleteDatabase(File file) {
728 if (file == null) {
729 throw new IllegalArgumentException("file must not be null");
730 }
731
732 boolean deleted = false;
733 deleted |= file.delete();
734 deleted |= new File(file.getPath() + "-journal").delete();
735 deleted |= new File(file.getPath() + "-shm").delete();
736 deleted |= new File(file.getPath() + "-wal").delete();
737
738 File dir = file.getParentFile();
739 if (dir != null) {
740 final String prefix = file.getName() + "-mj";
741 final FileFilter filter = new FileFilter() {
742 @Override
743 public boolean accept(File candidate) {
744 return candidate.getName().startsWith(prefix);
745 }
746 };
747 for (File masterJournal : dir.listFiles(filter)) {
748 deleted |= masterJournal.delete();
749 }
750 }
751 return deleted;
752 }
753
754 /**
Jeff Brown559d0642012-02-29 10:19:12 -0800755 * Reopens the database in read-write mode.
756 * If the database is already read-write, does nothing.
757 *
758 * @throws SQLiteException if the database could not be reopened as requested, in which
759 * case it remains open in read only mode.
760 * @throws IllegalStateException if the database is not open.
761 *
762 * @see #isReadOnly()
763 * @hide
764 */
765 public void reopenReadWrite() {
766 synchronized (mLock) {
767 throwIfNotOpenLocked();
768
769 if (!isReadOnlyLocked()) {
770 return; // nothing to do
771 }
772
773 // Reopen the database in read-write mode.
774 final int oldOpenFlags = mConfigurationLocked.openFlags;
775 mConfigurationLocked.openFlags = (mConfigurationLocked.openFlags & ~OPEN_READ_MASK)
776 | OPEN_READWRITE;
777 try {
778 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
779 } catch (RuntimeException ex) {
780 mConfigurationLocked.openFlags = oldOpenFlags;
781 throw ex;
782 }
783 }
784 }
785
Jeff Browne5360fb2011-10-31 17:48:13 -0700786 private void open() {
787 try {
788 try {
789 openInner();
790 } catch (SQLiteDatabaseCorruptException ex) {
791 onCorruption();
792 openInner();
793 }
Jeff Browne5360fb2011-10-31 17:48:13 -0700794 } catch (SQLiteException ex) {
795 Log.e(TAG, "Failed to open database '" + getLabel() + "'.", ex);
796 close();
797 throw ex;
798 }
799 }
800
801 private void openInner() {
802 synchronized (mLock) {
803 assert mConnectionPoolLocked == null;
804 mConnectionPoolLocked = SQLiteConnectionPool.open(mConfigurationLocked);
805 mCloseGuardLocked.open("close");
806 }
807
808 synchronized (sActiveDatabases) {
809 sActiveDatabases.put(this, null);
810 }
811 }
812
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700813 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 * Create a memory backed SQLite database. Its contents will be destroyed
815 * when the database is closed.
816 *
817 * <p>Sets the locale of the database to the the system's current locale.
818 * Call {@link #setLocale} if you would like something else.</p>
819 *
820 * @param factory an optional factory class that is called to instantiate a
821 * cursor when query is called
822 * @return a SQLiteDatabase object, or null if the database can't be created
823 */
824 public static SQLiteDatabase create(CursorFactory factory) {
825 // This is a magic string with special meaning for SQLite.
Jeff Browne5360fb2011-10-31 17:48:13 -0700826 return openDatabase(SQLiteDatabaseConfiguration.MEMORY_DB_PATH,
827 factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829
830 /**
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400831 * Registers a CustomFunction callback as a function that can be called from
Jeff Browne5360fb2011-10-31 17:48:13 -0700832 * SQLite database triggers.
833 *
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400834 * @param name the name of the sqlite3 function
835 * @param numArgs the number of arguments for the function
836 * @param function callback to call when the function is executed
837 * @hide
838 */
839 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700840 // Create wrapper (also validates arguments).
841 SQLiteCustomFunction wrapper = new SQLiteCustomFunction(name, numArgs, function);
842
843 synchronized (mLock) {
844 throwIfNotOpenLocked();
Jeff Browne67ca422012-03-21 17:24:05 -0700845
Jeff Browne5360fb2011-10-31 17:48:13 -0700846 mConfigurationLocked.customFunctions.add(wrapper);
Jeff Browne67ca422012-03-21 17:24:05 -0700847 try {
848 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
849 } catch (RuntimeException ex) {
850 mConfigurationLocked.customFunctions.remove(wrapper);
851 throw ex;
852 }
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400853 }
854 }
855
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400856 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 * Gets the database version.
858 *
859 * @return the database version
860 */
861 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -0700862 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
865 /**
866 * Sets the database version.
867 *
868 * @param version the new database version
869 */
870 public void setVersion(int version) {
871 execSQL("PRAGMA user_version = " + version);
872 }
873
874 /**
875 * Returns the maximum size the database may grow to.
876 *
877 * @return the new maximum database size
878 */
879 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700880 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
881 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883
884 /**
885 * Sets the maximum size the database will grow to. The maximum size cannot
886 * be set below the current size.
887 *
888 * @param numBytes the maximum database size, in bytes
889 * @return the new maximum database size
890 */
891 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -0700892 long pageSize = getPageSize();
893 long numPages = numBytes / pageSize;
894 // If numBytes isn't a multiple of pageSize, bump up a page
895 if ((numBytes % pageSize) != 0) {
896 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -0700897 }
Vasu Noriccd95442010-05-28 17:04:16 -0700898 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
899 null);
900 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
902
903 /**
904 * Returns the current database page size, in bytes.
905 *
906 * @return the database page size, in bytes
907 */
908 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700909 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911
912 /**
913 * Sets the database page size. The page size must be a power of two. This
914 * method does not work if any data has been written to the database file,
915 * and must be called right after the database has been created.
916 *
917 * @param numBytes the database page size, in bytes
918 */
919 public void setPageSize(long numBytes) {
920 execSQL("PRAGMA page_size = " + numBytes);
921 }
922
923 /**
924 * Mark this table as syncable. When an update occurs in this table the
925 * _sync_dirty field will be set to ensure proper syncing operation.
926 *
927 * @param table the table to mark as syncable
928 * @param deletedTable The deleted table that corresponds to the
929 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -0700930 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 */
Vasu Nori95675132010-07-21 16:24:40 -0700932 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935
936 /**
937 * Mark this table as syncable, with the _sync_dirty residing in another
938 * table. When an update occurs in this table the _sync_dirty field of the
939 * row in updateTable with the _id in foreignKey will be set to
940 * ensure proper syncing operation.
941 *
942 * @param table an update on this table will trigger a sync time removal
943 * @param foreignKey this is the column in table whose value is an _id in
944 * updateTable
945 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -0700946 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 */
Vasu Nori95675132010-07-21 16:24:40 -0700948 @Deprecated
949 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951
952 /**
953 * Finds the name of the first table, which is editable.
954 *
955 * @param tables a list of tables
956 * @return the first table listed
957 */
958 public static String findEditTable(String tables) {
959 if (!TextUtils.isEmpty(tables)) {
960 // find the first word terminated by either a space or a comma
961 int spacepos = tables.indexOf(' ');
962 int commapos = tables.indexOf(',');
963
964 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
965 return tables.substring(0, spacepos);
966 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
967 return tables.substring(0, commapos);
968 }
969 return tables;
970 } else {
971 throw new IllegalStateException("Invalid tables");
972 }
973 }
974
975 /**
976 * Compiles an SQL statement into a reusable pre-compiled statement object.
977 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
978 * statement and fill in those values with {@link SQLiteProgram#bindString}
979 * and {@link SQLiteProgram#bindLong} each time you want to run the
980 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -0700981 *<p>
982 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 *
984 * @param sql The raw SQL statement, may contain ? for unknown values to be
985 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700986 * @return A pre-compiled {@link SQLiteStatement} object. Note that
987 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 */
989 public SQLiteStatement compileStatement(String sql) throws SQLException {
Jeff Brown03bd3022012-03-06 13:48:56 -0800990 acquireReference();
991 try {
992 return new SQLiteStatement(this, sql, null);
993 } finally {
994 releaseReference();
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
997
998 /**
999 * Query the given URL, returning a {@link Cursor} over the result set.
1000 *
1001 * @param distinct true if you want each row to be unique, false otherwise.
1002 * @param table The table name to compile the query against.
1003 * @param columns A list of which columns to return. Passing null will
1004 * return all columns, which is discouraged to prevent reading
1005 * data from storage that isn't going to be used.
1006 * @param selection A filter declaring which rows to return, formatted as an
1007 * SQL WHERE clause (excluding the WHERE itself). Passing null
1008 * will return all rows for the given table.
1009 * @param selectionArgs You may include ?s in selection, which will be
1010 * replaced by the values from selectionArgs, in order that they
1011 * appear in the selection. The values will be bound as Strings.
1012 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1013 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1014 * will cause the rows to not be grouped.
1015 * @param having A filter declare which row groups to include in the cursor,
1016 * if row grouping is being used, formatted as an SQL HAVING
1017 * clause (excluding the HAVING itself). Passing null will cause
1018 * all row groups to be included, and is required when row
1019 * grouping is not being used.
1020 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1021 * (excluding the ORDER BY itself). Passing null will use the
1022 * default sort order, which may be unordered.
1023 * @param limit Limits the number of rows returned by the query,
1024 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001025 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1026 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 * @see Cursor
1028 */
1029 public Cursor query(boolean distinct, String table, String[] columns,
1030 String selection, String[] selectionArgs, String groupBy,
1031 String having, String orderBy, String limit) {
1032 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
Jeff Brown75ea64f2012-01-25 19:37:13 -08001033 groupBy, having, orderBy, limit, null);
1034 }
1035
1036 /**
1037 * Query the given URL, returning a {@link Cursor} over the result set.
1038 *
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 Brown4c1241d2012-02-02 17:05:00 -08001063 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001064 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1065 * when the query is executed.
1066 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1067 * {@link Cursor}s are not synchronized, see the documentation for more details.
1068 * @see Cursor
1069 */
1070 public Cursor query(boolean distinct, String table, String[] columns,
1071 String selection, String[] selectionArgs, String groupBy,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001072 String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001073 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001074 groupBy, having, orderBy, limit, cancellationSignal);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
1077 /**
1078 * Query the given URL, returning a {@link Cursor} over the result set.
1079 *
1080 * @param cursorFactory the cursor factory to use, or null for the default factory
1081 * @param distinct true if you want each row to be unique, false otherwise.
1082 * @param table The table name to compile the query against.
1083 * @param columns A list of which columns to return. Passing null will
1084 * return all columns, which is discouraged to prevent reading
1085 * data from storage that isn't going to be used.
1086 * @param selection A filter declaring which rows to return, formatted as an
1087 * SQL WHERE clause (excluding the WHERE itself). Passing null
1088 * will return all rows for the given table.
1089 * @param selectionArgs You may include ?s in selection, which will be
1090 * replaced by the values from selectionArgs, in order that they
1091 * appear in the selection. The values will be bound as Strings.
1092 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1093 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1094 * will cause the rows to not be grouped.
1095 * @param having A filter declare which row groups to include in the cursor,
1096 * if row grouping is being used, formatted as an SQL HAVING
1097 * clause (excluding the HAVING itself). Passing null will cause
1098 * all row groups to be included, and is required when row
1099 * grouping is not being used.
1100 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1101 * (excluding the ORDER BY itself). Passing null will use the
1102 * default sort order, which may be unordered.
1103 * @param limit Limits the number of rows returned by the query,
1104 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001105 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1106 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 * @see Cursor
1108 */
1109 public Cursor queryWithFactory(CursorFactory cursorFactory,
1110 boolean distinct, String table, String[] columns,
1111 String selection, String[] selectionArgs, String groupBy,
1112 String having, String orderBy, String limit) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001113 return queryWithFactory(cursorFactory, distinct, table, columns, selection,
1114 selectionArgs, groupBy, having, orderBy, limit, null);
1115 }
1116
1117 /**
1118 * Query the given URL, returning a {@link Cursor} over the result set.
1119 *
1120 * @param cursorFactory the cursor factory to use, or null for the default factory
1121 * @param distinct true if you want each row to be unique, false otherwise.
1122 * @param table The table name to compile the query against.
1123 * @param columns A list of which columns to return. Passing null will
1124 * return all columns, which is discouraged to prevent reading
1125 * data from storage that isn't going to be used.
1126 * @param selection A filter declaring which rows to return, formatted as an
1127 * SQL WHERE clause (excluding the WHERE itself). Passing null
1128 * will return all rows for the given table.
1129 * @param selectionArgs You may include ?s in selection, which will be
1130 * replaced by the values from selectionArgs, in order that they
1131 * appear in the selection. The values will be bound as Strings.
1132 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1133 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1134 * will cause the rows to not be grouped.
1135 * @param having A filter declare which row groups to include in the cursor,
1136 * if row grouping is being used, formatted as an SQL HAVING
1137 * clause (excluding the HAVING itself). Passing null will cause
1138 * all row groups to be included, and is required when row
1139 * grouping is not being used.
1140 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1141 * (excluding the ORDER BY itself). Passing null will use the
1142 * default sort order, which may be unordered.
1143 * @param limit Limits the number of rows returned by the query,
1144 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Brown4c1241d2012-02-02 17:05:00 -08001145 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001146 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1147 * when the query is executed.
1148 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1149 * {@link Cursor}s are not synchronized, see the documentation for more details.
1150 * @see Cursor
1151 */
1152 public Cursor queryWithFactory(CursorFactory cursorFactory,
1153 boolean distinct, String table, String[] columns,
1154 String selection, String[] selectionArgs, String groupBy,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001155 String having, String orderBy, String limit, CancellationSignal cancellationSignal) {
Jeff Brown03bd3022012-03-06 13:48:56 -08001156 acquireReference();
1157 try {
1158 String sql = SQLiteQueryBuilder.buildQueryString(
1159 distinct, table, columns, selection, groupBy, having, orderBy, limit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160
Jeff Brown03bd3022012-03-06 13:48:56 -08001161 return rawQueryWithFactory(cursorFactory, sql, selectionArgs,
1162 findEditTable(table), cancellationSignal);
1163 } finally {
1164 releaseReference();
1165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167
1168 /**
1169 * Query the given table, returning a {@link Cursor} over the result set.
1170 *
1171 * @param table The table name to compile the query against.
1172 * @param columns A list of which columns to return. Passing null will
1173 * return all columns, which is discouraged to prevent reading
1174 * data from storage that isn't going to be used.
1175 * @param selection A filter declaring which rows to return, formatted as an
1176 * SQL WHERE clause (excluding the WHERE itself). Passing null
1177 * will return all rows for the given table.
1178 * @param selectionArgs You may include ?s in selection, which will be
1179 * replaced by the values from selectionArgs, in order that they
1180 * appear in the selection. The values will be bound as Strings.
1181 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1182 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1183 * will cause the rows to not be grouped.
1184 * @param having A filter declare which row groups to include in the cursor,
1185 * if row grouping is being used, formatted as an SQL HAVING
1186 * clause (excluding the HAVING itself). Passing null will cause
1187 * all row groups to be included, and is required when row
1188 * grouping is not being used.
1189 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1190 * (excluding the ORDER BY itself). Passing null will use the
1191 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001192 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1193 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 * @see Cursor
1195 */
1196 public Cursor query(String table, String[] columns, String selection,
1197 String[] selectionArgs, String groupBy, String having,
1198 String orderBy) {
1199
1200 return query(false, table, columns, selection, selectionArgs, groupBy,
1201 having, orderBy, null /* limit */);
1202 }
1203
1204 /**
1205 * Query the given table, returning a {@link Cursor} over the result set.
1206 *
1207 * @param table The table name to compile the query against.
1208 * @param columns A list of which columns to return. Passing null will
1209 * return all columns, which is discouraged to prevent reading
1210 * data from storage that isn't going to be used.
1211 * @param selection A filter declaring which rows to return, formatted as an
1212 * SQL WHERE clause (excluding the WHERE itself). Passing null
1213 * will return all rows for the given table.
1214 * @param selectionArgs You may include ?s in selection, which will be
1215 * replaced by the values from selectionArgs, in order that they
1216 * appear in the selection. The values will be bound as Strings.
1217 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1218 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1219 * will cause the rows to not be grouped.
1220 * @param having A filter declare which row groups to include in the cursor,
1221 * if row grouping is being used, formatted as an SQL HAVING
1222 * clause (excluding the HAVING itself). Passing null will cause
1223 * all row groups to be included, and is required when row
1224 * grouping is not being used.
1225 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1226 * (excluding the ORDER BY itself). Passing null will use the
1227 * default sort order, which may be unordered.
1228 * @param limit Limits the number of rows returned by the query,
1229 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001230 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1231 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 * @see Cursor
1233 */
1234 public Cursor query(String table, String[] columns, String selection,
1235 String[] selectionArgs, String groupBy, String having,
1236 String orderBy, String limit) {
1237
1238 return query(false, table, columns, selection, selectionArgs, groupBy,
1239 having, orderBy, limit);
1240 }
1241
1242 /**
1243 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1244 *
1245 * @param sql the SQL query. The SQL string must not be ; terminated
1246 * @param selectionArgs You may include ?s in where clause in the query,
1247 * which will be replaced by the values from selectionArgs. The
1248 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001249 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1250 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 */
1252 public Cursor rawQuery(String sql, String[] selectionArgs) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001253 return rawQueryWithFactory(null, sql, selectionArgs, null, null);
1254 }
1255
1256 /**
1257 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1258 *
1259 * @param sql the SQL query. The SQL string must not be ; terminated
1260 * @param selectionArgs You may include ?s in where clause in the query,
1261 * which will be replaced by the values from selectionArgs. The
1262 * values will be bound as Strings.
Jeff Brown4c1241d2012-02-02 17:05:00 -08001263 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001264 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1265 * when the query is executed.
1266 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1267 * {@link Cursor}s are not synchronized, see the documentation for more details.
1268 */
1269 public Cursor rawQuery(String sql, String[] selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001270 CancellationSignal cancellationSignal) {
1271 return rawQueryWithFactory(null, sql, selectionArgs, null, cancellationSignal);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
1273
1274 /**
1275 * Runs the provided SQL and returns a cursor over the result set.
1276 *
1277 * @param cursorFactory the cursor factory to use, or null for the default factory
1278 * @param sql the SQL query. The SQL string must not be ; terminated
1279 * @param selectionArgs You may include ?s in where clause in the query,
1280 * which will be replaced by the values from selectionArgs. The
1281 * values will be bound as Strings.
1282 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001283 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1284 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 */
1286 public Cursor rawQueryWithFactory(
1287 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1288 String editTable) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001289 return rawQueryWithFactory(cursorFactory, sql, selectionArgs, editTable, null);
1290 }
1291
1292 /**
1293 * Runs the provided SQL and returns a cursor over the result set.
1294 *
1295 * @param cursorFactory the cursor factory to use, or null for the default factory
1296 * @param sql the SQL query. The SQL string must not be ; terminated
1297 * @param selectionArgs You may include ?s in where clause in the query,
1298 * which will be replaced by the values from selectionArgs. The
1299 * values will be bound as Strings.
1300 * @param editTable the name of the first table, which is editable
Jeff Brown4c1241d2012-02-02 17:05:00 -08001301 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001302 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1303 * when the query is executed.
1304 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1305 * {@link Cursor}s are not synchronized, see the documentation for more details.
1306 */
1307 public Cursor rawQueryWithFactory(
1308 CursorFactory cursorFactory, String sql, String[] selectionArgs,
Jeff Brown4c1241d2012-02-02 17:05:00 -08001309 String editTable, CancellationSignal cancellationSignal) {
Jeff Brown03bd3022012-03-06 13:48:56 -08001310 acquireReference();
1311 try {
1312 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, editTable,
1313 cancellationSignal);
1314 return driver.query(cursorFactory != null ? cursorFactory : mCursorFactory,
1315 selectionArgs);
1316 } finally {
1317 releaseReference();
1318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
1321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 * Convenience method for inserting a row into the database.
1323 *
1324 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001325 * @param nullColumnHack optional; may be <code>null</code>.
1326 * SQL doesn't allow inserting a completely empty row without
1327 * naming at least one column name. If your provided <code>values</code> is
1328 * empty, no column names are known and an empty row can't be inserted.
1329 * If not set to null, the <code>nullColumnHack</code> parameter
1330 * provides the name of nullable column name to explicitly insert a NULL into
1331 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 * @param values this map contains the initial column values for the
1333 * row. The keys should be the column names and the values the
1334 * column values
1335 * @return the row ID of the newly inserted row, or -1 if an error occurred
1336 */
1337 public long insert(String table, String nullColumnHack, ContentValues values) {
1338 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001339 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 } catch (SQLException e) {
1341 Log.e(TAG, "Error inserting " + values, e);
1342 return -1;
1343 }
1344 }
1345
1346 /**
1347 * Convenience method for inserting a row into the database.
1348 *
1349 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001350 * @param nullColumnHack optional; may be <code>null</code>.
1351 * SQL doesn't allow inserting a completely empty row without
1352 * naming at least one column name. If your provided <code>values</code> is
1353 * empty, no column names are known and an empty row can't be inserted.
1354 * If not set to null, the <code>nullColumnHack</code> parameter
1355 * provides the name of nullable column name to explicitly insert a NULL into
1356 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 * @param values this map contains the initial column values for the
1358 * row. The keys should be the column names and the values the
1359 * column values
1360 * @throws SQLException
1361 * @return the row ID of the newly inserted row, or -1 if an error occurred
1362 */
1363 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1364 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001365 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
1367
1368 /**
1369 * Convenience method for replacing a row in the database.
1370 *
1371 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001372 * @param nullColumnHack optional; may be <code>null</code>.
1373 * SQL doesn't allow inserting a completely empty row without
1374 * naming at least one column name. If your provided <code>initialValues</code> is
1375 * empty, no column names are known and an empty row can't be inserted.
1376 * If not set to null, the <code>nullColumnHack</code> parameter
1377 * provides the name of nullable column name to explicitly insert a NULL into
1378 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001380 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 * @return the row ID of the newly inserted row, or -1 if an error occurred
1382 */
1383 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1384 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001385 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001386 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 } catch (SQLException e) {
1388 Log.e(TAG, "Error inserting " + initialValues, e);
1389 return -1;
1390 }
1391 }
1392
1393 /**
1394 * Convenience method for replacing a row in the database.
1395 *
1396 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001397 * @param nullColumnHack optional; may be <code>null</code>.
1398 * SQL doesn't allow inserting a completely empty row without
1399 * naming at least one column name. If your provided <code>initialValues</code> is
1400 * empty, no column names are known and an empty row can't be inserted.
1401 * If not set to null, the <code>nullColumnHack</code> parameter
1402 * provides the name of nullable column name to explicitly insert a NULL into
1403 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 * @param initialValues this map contains the initial column values for
1405 * the row. The key
1406 * @throws SQLException
1407 * @return the row ID of the newly inserted row, or -1 if an error occurred
1408 */
1409 public long replaceOrThrow(String table, String nullColumnHack,
1410 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001411 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001412 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414
1415 /**
1416 * General method for inserting a row into the database.
1417 *
1418 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001419 * @param nullColumnHack optional; may be <code>null</code>.
1420 * SQL doesn't allow inserting a completely empty row without
1421 * naming at least one column name. If your provided <code>initialValues</code> is
1422 * empty, no column names are known and an empty row can't be inserted.
1423 * If not set to null, the <code>nullColumnHack</code> parameter
1424 * provides the name of nullable column name to explicitly insert a NULL into
1425 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 * @param initialValues this map contains the initial column values for the
1427 * row. The keys should be the column names and the values the
1428 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001429 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001430 * @return the row ID of the newly inserted row
1431 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001432 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001433 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 */
1435 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001436 ContentValues initialValues, int conflictAlgorithm) {
Jeff Brown03bd3022012-03-06 13:48:56 -08001437 acquireReference();
1438 try {
1439 StringBuilder sql = new StringBuilder();
1440 sql.append("INSERT");
1441 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
1442 sql.append(" INTO ");
1443 sql.append(table);
1444 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445
Jeff Brown03bd3022012-03-06 13:48:56 -08001446 Object[] bindArgs = null;
1447 int size = (initialValues != null && initialValues.size() > 0)
1448 ? initialValues.size() : 0;
1449 if (size > 0) {
1450 bindArgs = new Object[size];
1451 int i = 0;
1452 for (String colName : initialValues.keySet()) {
1453 sql.append((i > 0) ? "," : "");
1454 sql.append(colName);
1455 bindArgs[i++] = initialValues.get(colName);
1456 }
1457 sql.append(')');
1458 sql.append(" VALUES (");
1459 for (i = 0; i < size; i++) {
1460 sql.append((i > 0) ? ",?" : "?");
1461 }
1462 } else {
1463 sql.append(nullColumnHack + ") VALUES (NULL");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466
Jeff Brown03bd3022012-03-06 13:48:56 -08001467 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1468 try {
1469 return statement.executeInsert();
1470 } finally {
1471 statement.close();
1472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 } finally {
Jeff Brown03bd3022012-03-06 13:48:56 -08001474 releaseReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476 }
1477
1478 /**
1479 * Convenience method for deleting rows in the database.
1480 *
1481 * @param table the table to delete from
1482 * @param whereClause the optional WHERE clause to apply when deleting.
1483 * Passing null will delete all rows.
1484 * @return the number of rows affected if a whereClause is passed in, 0
1485 * otherwise. To remove all rows and get a count pass "1" as the
1486 * whereClause.
1487 */
1488 public int delete(String table, String whereClause, String[] whereArgs) {
Jeff Brown03bd3022012-03-06 13:48:56 -08001489 acquireReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 try {
Jeff Brown03bd3022012-03-06 13:48:56 -08001491 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1492 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
1493 try {
1494 return statement.executeUpdateDelete();
1495 } finally {
1496 statement.close();
1497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 } finally {
Jeff Brown03bd3022012-03-06 13:48:56 -08001499 releaseReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501 }
1502
1503 /**
1504 * Convenience method for updating rows in the database.
1505 *
1506 * @param table the table to update in
1507 * @param values a map from column names to new column values. null is a
1508 * valid value that will be translated to NULL.
1509 * @param whereClause the optional WHERE clause to apply when updating.
1510 * Passing null will update all rows.
1511 * @return the number of rows affected
1512 */
1513 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001514 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 /**
1518 * Convenience method for updating rows in the database.
1519 *
1520 * @param table the table to update in
1521 * @param values a map from column names to new column values. null is a
1522 * valid value that will be translated to NULL.
1523 * @param whereClause the optional WHERE clause to apply when updating.
1524 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001525 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001528 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001529 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001530 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 throw new IllegalArgumentException("Empty values");
1532 }
1533
Jeff Brown03bd3022012-03-06 13:48:56 -08001534 acquireReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 try {
Jeff Brown03bd3022012-03-06 13:48:56 -08001536 StringBuilder sql = new StringBuilder(120);
1537 sql.append("UPDATE ");
1538 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
1539 sql.append(table);
1540 sql.append(" SET ");
1541
1542 // move all bind args to one array
1543 int setValuesSize = values.size();
1544 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1545 Object[] bindArgs = new Object[bindArgsSize];
1546 int i = 0;
1547 for (String colName : values.keySet()) {
1548 sql.append((i > 0) ? "," : "");
1549 sql.append(colName);
1550 bindArgs[i++] = values.get(colName);
1551 sql.append("=?");
1552 }
1553 if (whereArgs != null) {
1554 for (i = setValuesSize; i < bindArgsSize; i++) {
1555 bindArgs[i] = whereArgs[i - setValuesSize];
1556 }
1557 }
1558 if (!TextUtils.isEmpty(whereClause)) {
1559 sql.append(" WHERE ");
1560 sql.append(whereClause);
1561 }
1562
1563 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1564 try {
1565 return statement.executeUpdateDelete();
1566 } finally {
1567 statement.close();
1568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 } finally {
Jeff Brown03bd3022012-03-06 13:48:56 -08001570 releaseReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572 }
1573
1574 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001575 * Execute a single SQL statement that is NOT a SELECT
1576 * or any other SQL statement that returns data.
1577 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001578 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001579 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1580 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1581 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001582 * <p>
1583 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1584 * automatically managed by this class. So, do not set journal_mode
1585 * using "PRAGMA journal_mode'<value>" statement if your app is using
1586 * {@link #enableWriteAheadLogging()}
1587 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 *
Vasu Noriccd95442010-05-28 17:04:16 -07001589 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1590 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001591 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001593 public void execSQL(String sql) throws SQLException {
Vasu Nori16057fa2011-03-18 11:40:37 -07001594 executeSql(sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
1596
1597 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001598 * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
1599 * <p>
1600 * For INSERT statements, use any of the following instead.
1601 * <ul>
1602 * <li>{@link #insert(String, String, ContentValues)}</li>
1603 * <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
1604 * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
1605 * </ul>
1606 * <p>
1607 * For UPDATE statements, use any of the following instead.
1608 * <ul>
1609 * <li>{@link #update(String, ContentValues, String, String[])}</li>
1610 * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
1611 * </ul>
1612 * <p>
1613 * For DELETE statements, use any of the following instead.
1614 * <ul>
1615 * <li>{@link #delete(String, String, String[])}</li>
1616 * </ul>
1617 * <p>
1618 * For example, the following are good candidates for using this method:
1619 * <ul>
1620 * <li>ALTER TABLE</li>
1621 * <li>CREATE or DROP table / trigger / view / index / virtual table</li>
1622 * <li>REINDEX</li>
1623 * <li>RELEASE</li>
1624 * <li>SAVEPOINT</li>
1625 * <li>PRAGMA that returns no data</li>
1626 * </ul>
1627 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001628 * <p>
1629 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1630 * automatically managed by this class. So, do not set journal_mode
1631 * using "PRAGMA journal_mode'<value>" statement if your app is using
1632 * {@link #enableWriteAheadLogging()}
1633 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 *
Vasu Noriccd95442010-05-28 17:04:16 -07001635 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1636 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001638 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001640 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (bindArgs == null) {
1642 throw new IllegalArgumentException("Empty bindArgs");
1643 }
Vasu Norib83cb7c2010-09-14 13:36:01 -07001644 executeSql(sql, bindArgs);
Vasu Norice38b982010-07-22 13:57:13 -07001645 }
1646
Vasu Nori54025902010-09-14 12:14:26 -07001647 private int executeSql(String sql, Object[] bindArgs) throws SQLException {
Jeff Brown03bd3022012-03-06 13:48:56 -08001648 acquireReference();
1649 try {
1650 if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
1651 boolean disableWal = false;
1652 synchronized (mLock) {
1653 if (!mHasAttachedDbsLocked) {
1654 mHasAttachedDbsLocked = true;
1655 disableWal = true;
1656 }
1657 }
1658 if (disableWal) {
1659 disableWriteAheadLogging();
Jeff Browne5360fb2011-10-31 17:48:13 -07001660 }
1661 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001662
Jeff Brown03bd3022012-03-06 13:48:56 -08001663 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
1664 try {
1665 return statement.executeUpdateDelete();
1666 } finally {
1667 statement.close();
1668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 } finally {
Jeff Brown03bd3022012-03-06 13:48:56 -08001670 releaseReference();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001675 * Returns true if the database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001677 * @return True if database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 */
1679 public boolean isReadOnly() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001680 synchronized (mLock) {
1681 return isReadOnlyLocked();
1682 }
1683 }
1684
1685 private boolean isReadOnlyLocked() {
1686 return (mConfigurationLocked.openFlags & OPEN_READ_MASK) == OPEN_READONLY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688
1689 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001690 * Returns true if the database is in-memory db.
1691 *
1692 * @return True if the database is in-memory.
1693 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001695 public boolean isInMemoryDatabase() {
1696 synchronized (mLock) {
1697 return mConfigurationLocked.isInMemoryDb();
1698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700
Jeff Browne5360fb2011-10-31 17:48:13 -07001701 /**
1702 * Returns true if the database is currently open.
1703 *
1704 * @return True if the database is currently open (has not been closed).
1705 */
1706 public boolean isOpen() {
1707 synchronized (mLock) {
1708 return mConnectionPoolLocked != null;
1709 }
1710 }
1711
1712 /**
1713 * Returns true if the new version code is greater than the current database version.
1714 *
1715 * @param newVersion The new version code.
1716 * @return True if the new version code is greater than the current database version.
1717 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 public boolean needUpgrade(int newVersion) {
1719 return newVersion > getVersion();
1720 }
1721
1722 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001723 * Gets the path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001725 * @return The path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 */
1727 public final String getPath() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001728 synchronized (mLock) {
1729 return mConfigurationLocked.path;
Christopher Tatead9e8b12011-10-05 17:49:26 -07001730 }
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 /**
1734 * Sets the locale for this database. Does nothing if this database has
Jeff Brown1d9f7422012-03-15 14:32:32 -07001735 * the {@link #NO_LOCALIZED_COLLATORS} flag set or was opened read only.
Jeff Browne5360fb2011-10-31 17:48:13 -07001736 *
1737 * @param locale The new locale.
1738 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 * @throws SQLException if the locale could not be set. The most common reason
1740 * for this is that there is no collator available for the locale you requested.
1741 * In this case the database remains unchanged.
1742 */
1743 public void setLocale(Locale locale) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001744 if (locale == null) {
1745 throw new IllegalArgumentException("locale must not be null.");
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001746 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001747
Jeff Browne5360fb2011-10-31 17:48:13 -07001748 synchronized (mLock) {
1749 throwIfNotOpenLocked();
Jeff Browne67ca422012-03-21 17:24:05 -07001750
1751 final Locale oldLocale = mConfigurationLocked.locale;
Jeff Browne5360fb2011-10-31 17:48:13 -07001752 mConfigurationLocked.locale = locale;
Jeff Browne67ca422012-03-21 17:24:05 -07001753 try {
1754 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
1755 } catch (RuntimeException ex) {
1756 mConfigurationLocked.locale = oldLocale;
1757 throw ex;
1758 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001759 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001760 }
1761
Vasu Norie495d1f2010-01-06 16:34:19 -08001762 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001763 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08001764 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07001765 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07001766 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07001767 * If this method is called with smaller size than the current maximum value,
1768 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07001769 *<p>
1770 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08001771 *
Vasu Nori90a367262010-04-12 12:49:09 -07001772 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
Jeff Browne5360fb2011-10-31 17:48:13 -07001773 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE}.
Vasu Norie495d1f2010-01-06 16:34:19 -08001774 */
Vasu Nori54025902010-09-14 12:14:26 -07001775 public void setMaxSqlCacheSize(int cacheSize) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001776 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
1777 throw new IllegalStateException(
1778 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
Vasu Nori587423a2010-09-27 18:18:34 -07001779 }
Vasu Nori587423a2010-09-27 18:18:34 -07001780
Jeff Browne5360fb2011-10-31 17:48:13 -07001781 synchronized (mLock) {
1782 throwIfNotOpenLocked();
Jeff Browne67ca422012-03-21 17:24:05 -07001783
1784 final int oldMaxSqlCacheSize = mConfigurationLocked.maxSqlCacheSize;
Jeff Browne5360fb2011-10-31 17:48:13 -07001785 mConfigurationLocked.maxSqlCacheSize = cacheSize;
Jeff Browne67ca422012-03-21 17:24:05 -07001786 try {
1787 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
1788 } catch (RuntimeException ex) {
1789 mConfigurationLocked.maxSqlCacheSize = oldMaxSqlCacheSize;
1790 throw ex;
1791 }
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001792 }
1793 }
1794
Vasu Nori6c354da2010-04-26 23:33:39 -07001795 /**
Jeff Brown47847f32012-03-22 19:13:11 -07001796 * This method enables parallel execution of queries from multiple threads on the
1797 * same database. It does this by opening multiple connections to the database
1798 * and using a different database connection for each query. The database
1799 * journal mode is also changed to enable writes to proceed concurrently with reads.
Vasu Nori6c354da2010-04-26 23:33:39 -07001800 * <p>
Jeff Brown47847f32012-03-22 19:13:11 -07001801 * When write-ahead logging is not enabled (the default), it is not possible for
1802 * reads and writes to occur on the database at the same time. Before modifying the
1803 * database, the writer implicitly acquires an exclusive lock on the database which
1804 * prevents readers from accessing the database until the write is completed.
1805 * </p><p>
1806 * In contrast, when write-ahead logging is enabled (by calling this method), write
1807 * operations occur in a separate log file which allows reads to proceed concurrently.
1808 * While a write is in progress, readers on other threads will perceive the state
1809 * of the database as it was before the write began. When the write completes, readers
1810 * on other threads will then perceive the new state of the database.
1811 * </p><p>
1812 * It is a good idea to enable write-ahead logging whenever a database will be
1813 * concurrently accessed and modified by multiple threads at the same time.
1814 * However, write-ahead logging uses significantly more memory than ordinary
1815 * journaling because there are multiple connections to the same database.
1816 * So if a database will only be used by a single thread, or if optimizing
1817 * concurrency is not very important, then write-ahead logging should be disabled.
1818 * </p><p>
1819 * After calling this method, execution of queries in parallel is enabled as long as
1820 * the database remains open. To disable execution of queries in parallel, either
1821 * call {@link #disableWriteAheadLogging} or close the database and reopen it.
1822 * </p><p>
1823 * The maximum number of connections used to execute queries in parallel is
Vasu Nori6c354da2010-04-26 23:33:39 -07001824 * dependent upon the device memory and possibly other properties.
Jeff Brown47847f32012-03-22 19:13:11 -07001825 * </p><p>
Vasu Nori6c354da2010-04-26 23:33:39 -07001826 * If a query is part of a transaction, then it is executed on the same database handle the
1827 * transaction was begun.
Jeff Brown47847f32012-03-22 19:13:11 -07001828 * </p><p>
Vasu Nori6c354da2010-04-26 23:33:39 -07001829 * Writers should use {@link #beginTransactionNonExclusive()} or
1830 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
Jeff Brown47847f32012-03-22 19:13:11 -07001831 * to start a transaction. Non-exclusive mode allows database file to be in readable
1832 * by other threads executing queries.
1833 * </p><p>
1834 * If the database has any attached databases, then execution of queries in parallel is NOT
1835 * possible. Likewise, write-ahead logging is not supported for read-only databases
1836 * or memory databases. In such cases, {@link #enableWriteAheadLogging} returns false.
1837 * </p><p>
1838 * The best way to enable write-ahead logging is to pass the
1839 * {@link #ENABLE_WRITE_AHEAD_LOGGING} flag to {@link #openDatabase}. This is
1840 * more efficient than calling {@link #enableWriteAheadLogging}.
1841 * <code><pre>
1842 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
1843 * SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
1844 * myDatabaseErrorHandler);
1845 * db.enableWriteAheadLogging();
1846 * </pre></code>
1847 * </p><p>
1848 * Another way to enable write-ahead logging is to call {@link #enableWriteAheadLogging}
1849 * after opening the database.
1850 * <code><pre>
1851 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
1852 * SQLiteDatabase.CREATE_IF_NECESSARY, myDatabaseErrorHandler);
1853 * db.enableWriteAheadLogging();
1854 * </pre></code>
1855 * </p><p>
1856 * See also <a href="http://sqlite.org/wal.html">SQLite Write-Ahead Logging</a> for
1857 * more details about how write-ahead logging works.
Vasu Nori6c354da2010-04-26 23:33:39 -07001858 * </p>
1859 *
Jeff Brown47847f32012-03-22 19:13:11 -07001860 * @return True if write-ahead logging is enabled.
Jeff Browne67ca422012-03-21 17:24:05 -07001861 *
Jean-Baptiste Queru73644772012-03-21 19:24:32 -07001862 * @throws IllegalStateException if there are transactions in progress at the
Jeff Browne67ca422012-03-21 17:24:05 -07001863 * time this method is called. WAL mode can only be changed when there are no
1864 * transactions in progress.
Jeff Brown47847f32012-03-22 19:13:11 -07001865 *
1866 * @see #ENABLE_WRITE_AHEAD_LOGGING
1867 * @see #disableWriteAheadLogging
Vasu Nori6c354da2010-04-26 23:33:39 -07001868 */
Vasu Noriffe06122010-09-27 12:32:57 -07001869 public boolean enableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001870 synchronized (mLock) {
1871 throwIfNotOpenLocked();
1872
Jeff Brown47847f32012-03-22 19:13:11 -07001873 if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001874 return true;
1875 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001876
1877 if (isReadOnlyLocked()) {
1878 // WAL doesn't make sense for readonly-databases.
1879 // TODO: True, but connection pooling does still make sense...
1880 return false;
1881 }
1882
1883 if (mConfigurationLocked.isInMemoryDb()) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001884 Log.i(TAG, "can't enable WAL for memory databases.");
1885 return false;
1886 }
1887
1888 // make sure this database has NO attached databases because sqlite's write-ahead-logging
1889 // doesn't work for databases with attached databases
Jeff Browne5360fb2011-10-31 17:48:13 -07001890 if (mHasAttachedDbsLocked) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001891 if (Log.isLoggable(TAG, Log.DEBUG)) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001892 Log.d(TAG, "this database: " + mConfigurationLocked.label
1893 + " has attached databases. can't enable WAL.");
Paul Westbrookdae6d372011-02-17 10:59:56 -08001894 }
1895 return false;
1896 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001897
Jeff Brown47847f32012-03-22 19:13:11 -07001898 mConfigurationLocked.openFlags |= ENABLE_WRITE_AHEAD_LOGGING;
Jeff Browne67ca422012-03-21 17:24:05 -07001899 try {
1900 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
1901 } catch (RuntimeException ex) {
Jeff Brown47847f32012-03-22 19:13:11 -07001902 mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
Jeff Browne67ca422012-03-21 17:24:05 -07001903 throw ex;
1904 }
Paul Westbrookdae6d372011-02-17 10:59:56 -08001905 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001906 return true;
Vasu Nori6c354da2010-04-26 23:33:39 -07001907 }
1908
Vasu Nori2827d6d2010-07-04 00:26:18 -07001909 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07001910 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
Jeff Browne67ca422012-03-21 17:24:05 -07001911 *
Jean-Baptiste Queru73644772012-03-21 19:24:32 -07001912 * @throws IllegalStateException if there are transactions in progress at the
Jeff Browne67ca422012-03-21 17:24:05 -07001913 * time this method is called. WAL mode can only be changed when there are no
1914 * transactions in progress.
Jeff Brown47847f32012-03-22 19:13:11 -07001915 *
1916 * @see #enableWriteAheadLogging
Vasu Nori2827d6d2010-07-04 00:26:18 -07001917 */
Vasu Nori7b04c412010-07-20 10:31:21 -07001918 public void disableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001919 synchronized (mLock) {
1920 throwIfNotOpenLocked();
1921
Jeff Brown47847f32012-03-22 19:13:11 -07001922 if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) == 0) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001923 return;
Paul Westbrookdae6d372011-02-17 10:59:56 -08001924 }
Vasu Nori8d111032010-06-22 18:34:21 -07001925
Jeff Brown47847f32012-03-22 19:13:11 -07001926 mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
Jeff Browne67ca422012-03-21 17:24:05 -07001927 try {
1928 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
1929 } catch (RuntimeException ex) {
Jeff Brown47847f32012-03-22 19:13:11 -07001930 mConfigurationLocked.openFlags |= ENABLE_WRITE_AHEAD_LOGGING;
Jeff Browne67ca422012-03-21 17:24:05 -07001931 throw ex;
1932 }
Vasu Nori65a88832010-07-16 15:14:08 -07001933 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001934 }
1935
Vasu Norif3cf8a42010-03-23 11:41:44 -07001936 /**
Jeff Brown47847f32012-03-22 19:13:11 -07001937 * Returns true if write-ahead logging has been enabled for this database.
1938 *
1939 * @return True if write-ahead logging has been enabled for this database.
1940 *
1941 * @see #enableWriteAheadLogging
1942 * @see #ENABLE_WRITE_AHEAD_LOGGING
1943 */
1944 public boolean isWriteAheadLoggingEnabled() {
1945 synchronized (mLock) {
1946 throwIfNotOpenLocked();
1947
1948 return (mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0;
1949 }
1950 }
1951
1952 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001953 * Collect statistics about all open databases in the current process.
1954 * Used by bug report.
Vasu Norif3cf8a42010-03-23 11:41:44 -07001955 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001956 static ArrayList<DbStats> getDbStats() {
Vasu Noric3849202010-03-09 10:47:25 -08001957 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001958 for (SQLiteDatabase db : getActiveDatabases()) {
1959 db.collectDbStats(dbStatsList);
Vasu Nori24675612010-09-27 14:54:19 -07001960 }
Vasu Noric3849202010-03-09 10:47:25 -08001961 return dbStatsList;
1962 }
1963
Jeff Browne5360fb2011-10-31 17:48:13 -07001964 private void collectDbStats(ArrayList<DbStats> dbStatsList) {
1965 synchronized (mLock) {
1966 if (mConnectionPoolLocked != null) {
1967 mConnectionPoolLocked.collectDbStats(dbStatsList);
1968 }
1969 }
1970 }
1971
1972 private static ArrayList<SQLiteDatabase> getActiveDatabases() {
1973 ArrayList<SQLiteDatabase> databases = new ArrayList<SQLiteDatabase>();
1974 synchronized (sActiveDatabases) {
1975 databases.addAll(sActiveDatabases.keySet());
1976 }
1977 return databases;
1978 }
1979
1980 /**
1981 * Dump detailed information about all open databases in the current process.
1982 * Used by bug report.
1983 */
Jeff Browna9be4152012-01-18 15:29:57 -08001984 static void dumpAll(Printer printer, boolean verbose) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001985 for (SQLiteDatabase db : getActiveDatabases()) {
Jeff Browna9be4152012-01-18 15:29:57 -08001986 db.dump(printer, verbose);
Jeff Browne5360fb2011-10-31 17:48:13 -07001987 }
1988 }
1989
Jeff Browna9be4152012-01-18 15:29:57 -08001990 private void dump(Printer printer, boolean verbose) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001991 synchronized (mLock) {
1992 if (mConnectionPoolLocked != null) {
1993 printer.println("");
Jeff Browna9be4152012-01-18 15:29:57 -08001994 mConnectionPoolLocked.dump(printer, verbose);
Jeff Browne5360fb2011-10-31 17:48:13 -07001995 }
1996 }
1997 }
1998
Vasu Noric3849202010-03-09 10:47:25 -08001999 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002000 * Returns list of full pathnames of all attached databases including the main database
2001 * by executing 'pragma database_list' on the database.
2002 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002003 * @return ArrayList of pairs of (database name, database file path) or null if the database
2004 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08002005 */
Vasu Noria017eda2011-01-27 10:52:55 -08002006 public List<Pair<String, String>> getAttachedDbs() {
Vasu Noric3849202010-03-09 10:47:25 -08002007 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Jeff Browne5360fb2011-10-31 17:48:13 -07002008 synchronized (mLock) {
2009 if (mConnectionPoolLocked == null) {
2010 return null; // not open
2011 }
2012
2013 if (!mHasAttachedDbsLocked) {
2014 // No attached databases.
2015 // There is a small window where attached databases exist but this flag is not
2016 // set yet. This can occur when this thread is in a race condition with another
2017 // thread that is executing the SQL statement: "attach database <blah> as <foo>"
2018 // If this thread is NOT ok with such a race condition (and thus possibly not
2019 // receivethe entire list of attached databases), then the caller should ensure
2020 // that no thread is executing any SQL statements while a thread is calling this
2021 // method. Typically, this method is called when 'adb bugreport' is done or the
2022 // caller wants to collect stats on the database and all its attached databases.
2023 attachedDbs.add(new Pair<String, String>("main", mConfigurationLocked.path));
2024 return attachedDbs;
2025 }
Jeff Brown03bd3022012-03-06 13:48:56 -08002026
2027 acquireReference();
Vasu Nori24675612010-09-27 14:54:19 -07002028 }
Jeff Browne5360fb2011-10-31 17:48:13 -07002029
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002030 try {
Jeff Brown03bd3022012-03-06 13:48:56 -08002031 // has attached databases. query sqlite to get the list of attached databases.
2032 Cursor c = null;
2033 try {
2034 c = rawQuery("pragma database_list;", null);
2035 while (c.moveToNext()) {
2036 // sqlite returns a row for each database in the returned list of databases.
2037 // in each row,
2038 // 1st column is the database name such as main, or the database
2039 // name specified on the "ATTACH" command
2040 // 2nd column is the database file path.
2041 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
2042 }
2043 } finally {
2044 if (c != null) {
2045 c.close();
2046 }
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002047 }
Jeff Brown03bd3022012-03-06 13:48:56 -08002048 return attachedDbs;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002049 } finally {
Jeff Brown03bd3022012-03-06 13:48:56 -08002050 releaseReference();
Vasu Noric3849202010-03-09 10:47:25 -08002051 }
Vasu Noric3849202010-03-09 10:47:25 -08002052 }
2053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002055 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
2056 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002057 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07002058 *<p>
2059 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002060 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07002061 *<p>
2062 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002063 *
2064 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07002065 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002066 */
2067 public boolean isDatabaseIntegrityOk() {
Jeff Brown03bd3022012-03-06 13:48:56 -08002068 acquireReference();
Vasu Noribfe1dc22010-08-25 16:29:02 -07002069 try {
Jeff Brown03bd3022012-03-06 13:48:56 -08002070 List<Pair<String, String>> attachedDbs = null;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002071 try {
Jeff Brown03bd3022012-03-06 13:48:56 -08002072 attachedDbs = getAttachedDbs();
2073 if (attachedDbs == null) {
2074 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
2075 "be retrieved. probably because the database is closed");
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002076 }
Jeff Brown03bd3022012-03-06 13:48:56 -08002077 } catch (SQLiteException e) {
2078 // can't get attachedDb list. do integrity check on the main database
2079 attachedDbs = new ArrayList<Pair<String, String>>();
2080 attachedDbs.add(new Pair<String, String>("main", getPath()));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002081 }
Jeff Brown03bd3022012-03-06 13:48:56 -08002082
2083 for (int i = 0; i < attachedDbs.size(); i++) {
2084 Pair<String, String> p = attachedDbs.get(i);
2085 SQLiteStatement prog = null;
2086 try {
2087 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
2088 String rslt = prog.simpleQueryForString();
2089 if (!rslt.equalsIgnoreCase("ok")) {
2090 // integrity_checker failed on main or attached databases
2091 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
2092 return false;
2093 }
2094 } finally {
2095 if (prog != null) prog.close();
2096 }
2097 }
2098 } finally {
2099 releaseReference();
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002100 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07002101 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002102 }
2103
Jeff Browne5360fb2011-10-31 17:48:13 -07002104 @Override
2105 public String toString() {
2106 return "SQLiteDatabase: " + getPath();
2107 }
2108
Jeff Browne5360fb2011-10-31 17:48:13 -07002109 private void throwIfNotOpenLocked() {
2110 if (mConnectionPoolLocked == null) {
2111 throw new IllegalStateException("The database '" + mConfigurationLocked.label
2112 + "' is not open.");
2113 }
2114 }
Vasu Nori3ef94e22010-02-05 14:49:04 -08002115
2116 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07002117 * Used to allow returning sub-classes of {@link Cursor} when calling query.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 */
Jeff Browne5360fb2011-10-31 17:48:13 -07002119 public interface CursorFactory {
2120 /**
2121 * See {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
2122 */
2123 public Cursor newCursor(SQLiteDatabase db,
2124 SQLiteCursorDriver masterQuery, String editTable,
2125 SQLiteQuery query);
2126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127
2128 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07002129 * A callback interface for a custom sqlite3 function.
2130 * This can be used to create a function that can be called from
2131 * sqlite3 database triggers.
2132 * @hide
Vasu Noric3849202010-03-09 10:47:25 -08002133 */
Jeff Browne5360fb2011-10-31 17:48:13 -07002134 public interface CustomFunction {
2135 public void callback(String[] args);
2136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137}