blob: 377a680cf5e182f24e0a1de4794b60560e79d9fe [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
19import android.content.ContentValues;
Vasu Nori34ad57f02010-12-21 09:32:36 -080020import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.database.Cursor;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070022import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.database.DatabaseUtils;
Vasu Nori062fc7ce2010-03-31 16:13:05 -070024import android.database.DefaultDatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.database.SQLException;
Vasu Noric3849202010-03-09 10:47:25 -080026import android.database.sqlite.SQLiteDebug.DbStats;
Jeff Browne5360fb2011-10-31 17:48:13 -070027import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070030import android.util.Log;
Vasu Noric3849202010-03-09 10:47:25 -080031import android.util.Pair;
Jeff Browne5360fb2011-10-31 17:48:13 -070032import android.util.Printer;
33
34import dalvik.system.CloseGuard;
35
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import java.io.File;
Vasu Noric3849202010-03-09 10:47:25 -080037import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import java.util.HashMap;
Jesse Wilson9b5a9352011-02-10 11:19:09 -080039import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import java.util.Locale;
41import java.util.Map;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.util.WeakHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
44/**
45 * Exposes methods to manage a SQLite database.
Jeff Browne5360fb2011-10-31 17:48:13 -070046 *
47 * <p>
48 * SQLiteDatabase has methods to create, delete, execute SQL commands, and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049 * perform other common database management tasks.
Jeff Browne5360fb2011-10-31 17:48:13 -070050 * </p><p>
51 * See the Notepad sample application in the SDK for an example of creating
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 * and managing a database.
Jeff Browne5360fb2011-10-31 17:48:13 -070053 * </p><p>
54 * Database names must be unique within an application, not across all applications.
55 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 *
57 * <h3>Localized Collation - ORDER BY</h3>
Jeff Browne5360fb2011-10-31 17:48:13 -070058 * <p>
59 * In addition to SQLite's default <code>BINARY</code> collator, Android supplies
60 * two more, <code>LOCALIZED</code>, which changes with the system's current locale,
61 * and <code>UNICODE</code>, which is the Unicode Collation Algorithm and not tailored
62 * to the current locale.
63 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 */
65public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070066 private static final String TAG = "SQLiteDatabase";
Jeff Browne5360fb2011-10-31 17:48:13 -070067
Jeff Hamilton082c2af2009-09-29 11:49:51 -070068 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Jeff Browne5360fb2011-10-31 17:48:13 -070070 // Stores reference to all databases opened in the current process.
71 // (The referent Object is not used at this time.)
72 // INVARIANT: Guarded by sActiveDatabases.
73 private static WeakHashMap<SQLiteDatabase, Object> sActiveDatabases =
74 new WeakHashMap<SQLiteDatabase, Object>();
75
76 // Thread-local for database sessions that belong to this database.
77 // Each thread has its own database session.
78 // INVARIANT: Immutable.
79 private final ThreadLocal<SQLiteSession> mThreadSession = new ThreadLocal<SQLiteSession>() {
80 @Override
81 protected SQLiteSession initialValue() {
82 return createSession();
83 }
84 };
85
86 // The optional factory to use when creating new Cursors. May be null.
87 // INVARIANT: Immutable.
88 private final CursorFactory mCursorFactory;
89
90 // Error handler to be used when SQLite returns corruption errors.
91 // INVARIANT: Immutable.
92 private final DatabaseErrorHandler mErrorHandler;
93
94 // Shared database state lock.
95 // This lock guards all of the shared state of the database, such as its
96 // configuration, whether it is open or closed, and so on. This lock should
97 // be held for as little time as possible.
98 //
99 // The lock MUST NOT be held while attempting to acquire database connections or
100 // while executing SQL statements on behalf of the client as it can lead to deadlock.
101 //
102 // It is ok to hold the lock while reconfiguring the connection pool or dumping
103 // statistics because those operations are non-reentrant and do not try to acquire
104 // connections that might be held by other threads.
105 //
106 // Basic rule: grab the lock, access or modify global state, release the lock, then
107 // do the required SQL work.
108 private final Object mLock = new Object();
109
110 // Warns if the database is finalized without being closed properly.
111 // INVARIANT: Guarded by mLock.
112 private final CloseGuard mCloseGuardLocked = CloseGuard.get();
113
114 // The database configuration.
115 // INVARIANT: Guarded by mLock.
116 private final SQLiteDatabaseConfiguration mConfigurationLocked;
117
118 // The connection pool for the database, null when closed.
119 // The pool itself is thread-safe, but the reference to it can only be acquired
120 // when the lock is held.
121 // INVARIANT: Guarded by mLock.
122 private SQLiteConnectionPool mConnectionPoolLocked;
123
124 // True if the database has attached databases.
125 // INVARIANT: Guarded by mLock.
126 private boolean mHasAttachedDbsLocked;
127
128 // True if the database is in WAL mode.
129 // INVARIANT: Guarded by mLock.
130 private boolean mIsWALEnabledLocked;
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700133 * When a constraint violation occurs, an immediate ROLLBACK occurs,
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800134 * thus ending the current transaction, and the command aborts with a
135 * return code of SQLITE_CONSTRAINT. If no transaction is active
136 * (other than the implied transaction that is created on every command)
Jeff Browne5360fb2011-10-31 17:48:13 -0700137 * then this algorithm works the same as ABORT.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800138 */
139 public static final int CONFLICT_ROLLBACK = 1;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700140
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800141 /**
142 * When a constraint violation occurs,no ROLLBACK is executed
143 * so changes from prior commands within the same transaction
144 * are preserved. This is the default behavior.
145 */
146 public static final int CONFLICT_ABORT = 2;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700147
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800148 /**
149 * When a constraint violation occurs, the command aborts with a return
150 * code SQLITE_CONSTRAINT. But any changes to the database that
151 * the command made prior to encountering the constraint violation
152 * are preserved and are not backed out.
153 */
154 public static final int CONFLICT_FAIL = 3;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700155
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800156 /**
157 * When a constraint violation occurs, the one row that contains
158 * the constraint violation is not inserted or changed.
159 * But the command continues executing normally. Other rows before and
160 * after the row that contained the constraint violation continue to be
161 * inserted or updated normally. No error is returned.
162 */
163 public static final int CONFLICT_IGNORE = 4;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700164
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800165 /**
166 * When a UNIQUE constraint violation occurs, the pre-existing rows that
167 * are causing the constraint violation are removed prior to inserting
168 * or updating the current row. Thus the insert or update always occurs.
169 * The command continues executing normally. No error is returned.
170 * If a NOT NULL constraint violation occurs, the NULL value is replaced
171 * by the default value for that column. If the column has no default
172 * value, then the ABORT algorithm is used. If a CHECK constraint
173 * violation occurs then the IGNORE algorithm is used. When this conflict
174 * resolution strategy deletes rows in order to satisfy a constraint,
175 * it does not invoke delete triggers on those rows.
Jeff Browne5360fb2011-10-31 17:48:13 -0700176 * This behavior might change in a future release.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800177 */
178 public static final int CONFLICT_REPLACE = 5;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700179
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800180 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700181 * Use the following when no conflict action is specified.
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800182 */
183 public static final int CONFLICT_NONE = 0;
Jeff Browne5360fb2011-10-31 17:48:13 -0700184
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800185 private static final String[] CONFLICT_VALUES = new String[]
186 {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /**
189 * Maximum Length Of A LIKE Or GLOB Pattern
190 * The pattern matching algorithm used in the default LIKE and GLOB implementation
191 * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
192 * the pattern) for certain pathological cases. To avoid denial-of-service attacks
193 * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
194 * The default value of this limit is 50000. A modern workstation can evaluate
195 * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
196 * The denial of service problem only comes into play when the pattern length gets
197 * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
198 * are at most a few dozen bytes in length, paranoid application developers may
199 * want to reduce this parameter to something in the range of a few hundred
200 * if they know that external users are able to generate arbitrary patterns.
201 */
202 public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
203
204 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700205 * Open flag: Flag for {@link #openDatabase} to open the database for reading and writing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 * If the disk is full, this may fail even before you actually write anything.
207 *
208 * {@more} Note that the value of this flag is 0, so it is the default.
209 */
210 public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
211
212 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700213 * Open flag: Flag for {@link #openDatabase} to open the database for reading only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 * This is the only reliable way to open a database if the disk may be full.
215 */
216 public static final int OPEN_READONLY = 0x00000001; // update native code if changing
217
218 private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
219
220 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700221 * Open flag: Flag for {@link #openDatabase} to open the database without support for
222 * localized collators.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 *
224 * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
225 * You must be consistent when using this flag to use the setting the database was
226 * created with. If this is set, {@link #setLocale} will do nothing.
227 */
228 public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
229
230 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700231 * Open flag: Flag for {@link #openDatabase} to create the database file if it does not
232 * already exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 */
234 public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
235
236 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700237 * Absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}.
Vasu Norib729dcc2010-09-14 11:35:49 -0700238 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700239 * Each prepared-statement is between 1K - 6K, depending on the complexity of the
240 * SQL statement & schema. A large SQL cache may use a significant amount of memory.
Vasu Norie495d1f2010-01-06 16:34:19 -0800241 */
Vasu Nori90a367262010-04-12 12:49:09 -0700242 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Norib729dcc2010-09-14 11:35:49 -0700243
Jeff Browne5360fb2011-10-31 17:48:13 -0700244 private SQLiteDatabase(String path, int openFlags, CursorFactory cursorFactory,
245 DatabaseErrorHandler errorHandler) {
246 mCursorFactory = cursorFactory;
247 mErrorHandler = errorHandler != null ? errorHandler : new DefaultDatabaseErrorHandler();
248 mConfigurationLocked = new SQLiteDatabaseConfiguration(path, openFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700250
Jeff Browne5360fb2011-10-31 17:48:13 -0700251 @Override
252 protected void finalize() throws Throwable {
253 try {
254 dispose(true);
255 } finally {
256 super.finalize();
257 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700258 }
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 @Override
261 protected void onAllReferencesReleased() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700262 dispose(false);
263 }
264
265 private void dispose(boolean finalized) {
266 final SQLiteConnectionPool pool;
267 synchronized (mLock) {
268 if (mCloseGuardLocked != null) {
269 if (finalized) {
270 mCloseGuardLocked.warnIfOpen();
271 }
272 mCloseGuardLocked.close();
273 }
274
275 pool = mConnectionPoolLocked;
276 mConnectionPoolLocked = null;
277 }
278
279 if (!finalized) {
280 synchronized (sActiveDatabases) {
281 sActiveDatabases.remove(this);
282 }
283
284 if (pool != null) {
285 pool.close();
286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 }
289
290 /**
291 * Attempts to release memory that SQLite holds but does not require to
292 * operate properly. Typically this memory will come from the page cache.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700293 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 * @return the number of bytes actually released
295 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700296 public static int releaseMemory() {
297 return SQLiteGlobal.releaseMemory();
298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
300 /**
301 * Control whether or not the SQLiteDatabase is made thread-safe by using locks
302 * around critical sections. This is pretty expensive, so if you know that your
303 * DB will only be used by a single thread then you should set this to false.
304 * The default is true.
305 * @param lockingEnabled set to true to enable locks, false otherwise
Jeff Browne5360fb2011-10-31 17:48:13 -0700306 *
307 * @deprecated This method now does nothing. Do not use.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700309 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 public void setLockingEnabled(boolean lockingEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
312
313 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700314 * Gets a label to use when describing the database in log messages.
315 * @return The label.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700317 String getLabel() {
318 synchronized (mLock) {
319 return mConfigurationLocked.label;
320 }
321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
Jeff Browne5360fb2011-10-31 17:48:13 -0700323 /**
324 * Sends a corruption message to the database error handler.
325 */
326 void onCorruption() {
327 EventLog.writeEvent(EVENT_DB_CORRUPT, getLabel());
Vasu Noriccd95442010-05-28 17:04:16 -0700328 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330
331 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700332 * Gets the {@link SQLiteSession} that belongs to this thread for this database.
333 * Once a thread has obtained a session, it will continue to obtain the same
334 * session even after the database has been closed (although the session will not
335 * be usable). However, a thread that does not already have a session cannot
336 * obtain one after the database has been closed.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700337 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700338 * The idea is that threads that have active connections to the database may still
339 * have work to complete even after the call to {@link #close}. Active database
340 * connections are not actually disposed until they are released by the threads
341 * that own them.
342 *
343 * @return The session, never null.
344 *
345 * @throws IllegalStateException if the thread does not yet have a session and
346 * the database is not open.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700348 SQLiteSession getThreadSession() {
349 return mThreadSession.get(); // initialValue() throws if database closed
Vasu Nori6d970252010-10-05 10:48:49 -0700350 }
Vasu Nori16057fa2011-03-18 11:40:37 -0700351
Jeff Browne5360fb2011-10-31 17:48:13 -0700352 SQLiteSession createSession() {
353 final SQLiteConnectionPool pool;
354 synchronized (mLock) {
355 throwIfNotOpenLocked();
356 pool = mConnectionPoolLocked;
Vasu Nori6d970252010-10-05 10:48:49 -0700357 }
Jeff Browne5360fb2011-10-31 17:48:13 -0700358 return new SQLiteSession(pool);
Vasu Norid4608a32011-02-03 16:24:06 -0800359 }
360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700362 * Gets default connection flags that are appropriate for this thread, taking into
363 * account whether the thread is acting on behalf of the UI.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700365 * @param readOnly True if the connection should be read-only.
366 * @return The connection flags.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700368 int getThreadDefaultConnectionFlags(boolean readOnly) {
369 int flags = readOnly ? SQLiteConnectionPool.CONNECTION_FLAG_READ_ONLY :
370 SQLiteConnectionPool.CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY;
371 if (isMainThread()) {
372 flags |= SQLiteConnectionPool.CONNECTION_FLAG_INTERACTIVE;
373 }
374 return flags;
Vasu Nori16057fa2011-03-18 11:40:37 -0700375 }
376
Jeff Browne5360fb2011-10-31 17:48:13 -0700377 private static boolean isMainThread() {
378 // FIXME: There should be a better way to do this.
379 // Would also be nice to have something that would work across Binder calls.
380 Looper looper = Looper.myLooper();
381 return looper != null && looper == Looper.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383
384 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700385 * Begins a transaction in EXCLUSIVE mode.
386 * <p>
387 * Transactions can be nested.
388 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * the work done in that transaction and all of the nested transactions will be committed or
390 * rolled back. The changes will be rolled back if any transaction is ended without being
391 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700392 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 * <p>Here is the standard idiom for transactions:
394 *
395 * <pre>
396 * db.beginTransaction();
397 * try {
398 * ...
399 * db.setTransactionSuccessful();
400 * } finally {
401 * db.endTransaction();
402 * }
403 * </pre>
404 */
405 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700406 beginTransaction(null /* transactionStatusCallback */, true);
407 }
408
409 /**
410 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
411 * the outer transaction is ended all of the work done in that transaction
412 * and all of the nested transactions will be committed or rolled back. The
413 * changes will be rolled back if any transaction is ended without being
414 * marked as clean (by calling setTransactionSuccessful). Otherwise they
415 * will be committed.
416 * <p>
417 * Here is the standard idiom for transactions:
418 *
419 * <pre>
420 * db.beginTransactionNonExclusive();
421 * try {
422 * ...
423 * db.setTransactionSuccessful();
424 * } finally {
425 * db.endTransaction();
426 * }
427 * </pre>
428 */
429 public void beginTransactionNonExclusive() {
430 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700431 }
432
433 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700434 * Begins a transaction in EXCLUSIVE mode.
435 * <p>
436 * Transactions can be nested.
437 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700438 * the work done in that transaction and all of the nested transactions will be committed or
439 * rolled back. The changes will be rolled back if any transaction is ended without being
440 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700441 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700442 * <p>Here is the standard idiom for transactions:
443 *
444 * <pre>
445 * db.beginTransactionWithListener(listener);
446 * try {
447 * ...
448 * db.setTransactionSuccessful();
449 * } finally {
450 * db.endTransaction();
451 * }
452 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700453 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700454 * @param transactionListener listener that should be notified when the transaction begins,
455 * commits, or is rolled back, either explicitly or by a call to
456 * {@link #yieldIfContendedSafely}.
457 */
458 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700459 beginTransaction(transactionListener, true);
460 }
461
462 /**
463 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
464 * the outer transaction is ended all of the work done in that transaction
465 * and all of the nested transactions will be committed or rolled back. The
466 * changes will be rolled back if any transaction is ended without being
467 * marked as clean (by calling setTransactionSuccessful). Otherwise they
468 * will be committed.
469 * <p>
470 * Here is the standard idiom for transactions:
471 *
472 * <pre>
473 * db.beginTransactionWithListenerNonExclusive(listener);
474 * try {
475 * ...
476 * db.setTransactionSuccessful();
477 * } finally {
478 * db.endTransaction();
479 * }
480 * </pre>
481 *
482 * @param transactionListener listener that should be notified when the
483 * transaction begins, commits, or is rolled back, either
484 * explicitly or by a call to {@link #yieldIfContendedSafely}.
485 */
486 public void beginTransactionWithListenerNonExclusive(
487 SQLiteTransactionListener transactionListener) {
488 beginTransaction(transactionListener, false);
489 }
490
491 private void beginTransaction(SQLiteTransactionListener transactionListener,
492 boolean exclusive) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700493 getThreadSession().beginTransaction(exclusive ? SQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
494 SQLiteSession.TRANSACTION_MODE_IMMEDIATE, transactionListener,
495 getThreadDefaultConnectionFlags(false /*readOnly*/));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
497
498 /**
499 * End a transaction. See beginTransaction for notes about how to use this and when transactions
500 * are committed and rolled back.
501 */
502 public void endTransaction() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700503 getThreadSession().endTransaction();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
505
506 /**
507 * Marks the current transaction as successful. Do not do any more database work between
508 * calling this and calling endTransaction. Do as little non-database work as possible in that
509 * situation too. If any errors are encountered between this and endTransaction the transaction
510 * will still be committed.
511 *
512 * @throws IllegalStateException if the current thread is not in a transaction or the
513 * transaction is already marked as successful.
514 */
515 public void setTransactionSuccessful() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700516 getThreadSession().setTransactionSuccessful();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 }
518
519 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700520 * Returns true if the current thread has a transaction pending.
521 *
522 * @return True if the current thread is in a transaction.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 */
524 public boolean inTransaction() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700525 return getThreadSession().hasTransaction();
Vasu Norice38b982010-07-22 13:57:13 -0700526 }
527
528 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700529 * Returns true if the current thread is holding an active connection to the database.
Vasu Norice38b982010-07-22 13:57:13 -0700530 * <p>
Jeff Browne5360fb2011-10-31 17:48:13 -0700531 * The name of this method comes from a time when having an active connection
532 * to the database meant that the thread was holding an actual lock on the
533 * database. Nowadays, there is no longer a true "database lock" although threads
534 * may block if they cannot acquire a database connection to perform a
535 * particular operation.
536 * </p>
Vasu Norice38b982010-07-22 13:57:13 -0700537 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700538 * @return True if the current thread is holding an active connection to the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 */
540 public boolean isDbLockedByCurrentThread() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700541 return getThreadSession().hasConnection();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543
544 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700545 * Always returns false.
546 * <p>
547 * There is no longer the concept of a database lock, so this method always returns false.
548 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 *
Jeff Browne5360fb2011-10-31 17:48:13 -0700550 * @return False.
551 * @deprecated Always returns false. Do not use this method.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 */
Jeff Browne5360fb2011-10-31 17:48:13 -0700553 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 public boolean isDbLockedByOtherThreads() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700555 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 }
557
558 /**
559 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
560 * successful so far. Do not call setTransactionSuccessful before calling this. When this
561 * returns a new transaction will have been created but not marked as successful.
562 * @return true if the transaction was yielded
563 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
564 * will not be yielded. Use yieldIfContendedSafely instead.
565 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700566 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700568 return yieldIfContendedHelper(false /* do not check yielding */,
569 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571
572 /**
573 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
574 * successful so far. Do not call setTransactionSuccessful before calling this. When this
575 * returns a new transaction will have been created but not marked as successful. This assumes
576 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700577 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * @return true if the transaction was yielded
579 */
580 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700581 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
Fred Quintana5c7aede2009-08-27 21:41:27 -0700584 /**
585 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
586 * successful so far. Do not call setTransactionSuccessful before calling this. When this
587 * returns a new transaction will have been created but not marked as successful. This assumes
588 * that there are no nested transactions (beginTransaction has only been called once) and will
589 * throw an exception if that is not the case.
590 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
591 * the lock was actually yielded. This will allow other background threads to make some
592 * more progress than they would if we started the transaction immediately.
593 * @return true if the transaction was yielded
594 */
595 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
596 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
597 }
598
Jeff Browne5360fb2011-10-31 17:48:13 -0700599 private boolean yieldIfContendedHelper(boolean throwIfUnsafe, long sleepAfterYieldDelay) {
600 return getThreadSession().yieldTransaction(sleepAfterYieldDelay, throwIfUnsafe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 /**
Jeff Browne5360fb2011-10-31 17:48:13 -0700604 * Deprecated.
Vasu Nori95675132010-07-21 16:24:40 -0700605 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 */
Vasu Nori95675132010-07-21 16:24:40 -0700607 @Deprecated
608 public Map<String, String> getSyncedTables() {
609 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
611
612 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 * Open the database according to the flags {@link #OPEN_READWRITE}
614 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
615 *
616 * <p>Sets the locale of the database to the the system's current locale.
617 * Call {@link #setLocale} if you would like something else.</p>
618 *
619 * @param path to database file to open and/or create
620 * @param factory an optional factory class that is called to instantiate a
621 * cursor when query is called, or null for default
622 * @param flags to control database access mode
623 * @return the newly opened database
624 * @throws SQLiteException if the database cannot be opened
625 */
626 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700627 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
628 }
629
630 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700631 * Open the database according to the flags {@link #OPEN_READWRITE}
632 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
633 *
634 * <p>Sets the locale of the database to the the system's current locale.
635 * Call {@link #setLocale} if you would like something else.</p>
636 *
637 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
638 * used to handle corruption when sqlite reports database corruption.</p>
639 *
640 * @param path to database file to open and/or create
641 * @param factory an optional factory class that is called to instantiate a
642 * cursor when query is called, or null for default
643 * @param flags to control database access mode
644 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
645 * when sqlite reports database corruption
646 * @return the newly opened database
647 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700648 */
649 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
650 DatabaseErrorHandler errorHandler) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700651 SQLiteDatabase db = new SQLiteDatabase(path, flags, factory, errorHandler);
652 db.open();
653 return db;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700654 }
655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 /**
657 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
658 */
659 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
660 return openOrCreateDatabase(file.getPath(), factory);
661 }
662
663 /**
664 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
665 */
666 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
667 return openDatabase(path, factory, CREATE_IF_NECESSARY);
668 }
669
670 /**
Vasu Nori6c354da2010-04-26 23:33:39 -0700671 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700672 */
673 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
674 DatabaseErrorHandler errorHandler) {
675 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
676 }
677
Jeff Browne5360fb2011-10-31 17:48:13 -0700678 private void open() {
679 try {
680 try {
681 openInner();
682 } catch (SQLiteDatabaseCorruptException ex) {
683 onCorruption();
684 openInner();
685 }
686
687 // Disable WAL if it was previously enabled.
688 setJournalMode("TRUNCATE");
689 } catch (SQLiteException ex) {
690 Log.e(TAG, "Failed to open database '" + getLabel() + "'.", ex);
691 close();
692 throw ex;
693 }
694 }
695
696 private void openInner() {
697 synchronized (mLock) {
698 assert mConnectionPoolLocked == null;
699 mConnectionPoolLocked = SQLiteConnectionPool.open(mConfigurationLocked);
700 mCloseGuardLocked.open("close");
701 }
702
703 synchronized (sActiveDatabases) {
704 sActiveDatabases.put(this, null);
705 }
706 }
707
708 private void setJournalMode(String mode) {
709 // Journal mode can be set only for non-memory databases
Vasu Nori8fcda302010-11-08 13:46:40 -0800710 // AND can't be set for readonly databases
Jeff Browne5360fb2011-10-31 17:48:13 -0700711 if (isInMemoryDatabase() || isReadOnly()) {
Vasu Nori8fcda302010-11-08 13:46:40 -0800712 return;
713 }
714 String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null);
715 if (!s.equalsIgnoreCase(mode)) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700716 Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + getLabel()
717 + " (on pragma set journal_mode, sqlite returned:" + s);
Vasu Noria98cb262010-06-22 13:16:35 -0700718 }
719 }
720
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700721 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 * Create a memory backed SQLite database. Its contents will be destroyed
723 * when the database is closed.
724 *
725 * <p>Sets the locale of the database to the the system's current locale.
726 * Call {@link #setLocale} if you would like something else.</p>
727 *
728 * @param factory an optional factory class that is called to instantiate a
729 * cursor when query is called
730 * @return a SQLiteDatabase object, or null if the database can't be created
731 */
732 public static SQLiteDatabase create(CursorFactory factory) {
733 // This is a magic string with special meaning for SQLite.
Jeff Browne5360fb2011-10-31 17:48:13 -0700734 return openDatabase(SQLiteDatabaseConfiguration.MEMORY_DB_PATH,
735 factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737
738 /**
739 * Close the database.
740 */
741 public void close() {
Jeff Browne5360fb2011-10-31 17:48:13 -0700742 dispose(false);
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400743 }
744
745 /**
746 * Registers a CustomFunction callback as a function that can be called from
Jeff Browne5360fb2011-10-31 17:48:13 -0700747 * SQLite database triggers.
748 *
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400749 * @param name the name of the sqlite3 function
750 * @param numArgs the number of arguments for the function
751 * @param function callback to call when the function is executed
752 * @hide
753 */
754 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700755 // Create wrapper (also validates arguments).
756 SQLiteCustomFunction wrapper = new SQLiteCustomFunction(name, numArgs, function);
757
758 synchronized (mLock) {
759 throwIfNotOpenLocked();
760 mConfigurationLocked.customFunctions.add(wrapper);
761 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400762 }
763 }
764
Mike Lockwood9d9c1be2010-07-13 19:27:52 -0400765 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 * Gets the database version.
767 *
768 * @return the database version
769 */
770 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -0700771 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
773
774 /**
775 * Sets the database version.
776 *
777 * @param version the new database version
778 */
779 public void setVersion(int version) {
780 execSQL("PRAGMA user_version = " + version);
781 }
782
783 /**
784 * Returns the maximum size the database may grow to.
785 *
786 * @return the new maximum database size
787 */
788 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700789 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
790 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792
793 /**
794 * Sets the maximum size the database will grow to. The maximum size cannot
795 * be set below the current size.
796 *
797 * @param numBytes the maximum database size, in bytes
798 * @return the new maximum database size
799 */
800 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -0700801 long pageSize = getPageSize();
802 long numPages = numBytes / pageSize;
803 // If numBytes isn't a multiple of pageSize, bump up a page
804 if ((numBytes % pageSize) != 0) {
805 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -0700806 }
Vasu Noriccd95442010-05-28 17:04:16 -0700807 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
808 null);
809 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 }
811
812 /**
813 * Returns the current database page size, in bytes.
814 *
815 * @return the database page size, in bytes
816 */
817 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -0700818 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820
821 /**
822 * Sets the database page size. The page size must be a power of two. This
823 * method does not work if any data has been written to the database file,
824 * and must be called right after the database has been created.
825 *
826 * @param numBytes the database page size, in bytes
827 */
828 public void setPageSize(long numBytes) {
829 execSQL("PRAGMA page_size = " + numBytes);
830 }
831
832 /**
833 * Mark this table as syncable. When an update occurs in this table the
834 * _sync_dirty field will be set to ensure proper syncing operation.
835 *
836 * @param table the table to mark as syncable
837 * @param deletedTable The deleted table that corresponds to the
838 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -0700839 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 */
Vasu Nori95675132010-07-21 16:24:40 -0700841 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844
845 /**
846 * Mark this table as syncable, with the _sync_dirty residing in another
847 * table. When an update occurs in this table the _sync_dirty field of the
848 * row in updateTable with the _id in foreignKey will be set to
849 * ensure proper syncing operation.
850 *
851 * @param table an update on this table will trigger a sync time removal
852 * @param foreignKey this is the column in table whose value is an _id in
853 * updateTable
854 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -0700855 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 */
Vasu Nori95675132010-07-21 16:24:40 -0700857 @Deprecated
858 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
860
861 /**
862 * Finds the name of the first table, which is editable.
863 *
864 * @param tables a list of tables
865 * @return the first table listed
866 */
867 public static String findEditTable(String tables) {
868 if (!TextUtils.isEmpty(tables)) {
869 // find the first word terminated by either a space or a comma
870 int spacepos = tables.indexOf(' ');
871 int commapos = tables.indexOf(',');
872
873 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
874 return tables.substring(0, spacepos);
875 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
876 return tables.substring(0, commapos);
877 }
878 return tables;
879 } else {
880 throw new IllegalStateException("Invalid tables");
881 }
882 }
883
884 /**
885 * Compiles an SQL statement into a reusable pre-compiled statement object.
886 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
887 * statement and fill in those values with {@link SQLiteProgram#bindString}
888 * and {@link SQLiteProgram#bindLong} each time you want to run the
889 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -0700890 *<p>
891 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 *
893 * @param sql The raw SQL statement, may contain ? for unknown values to be
894 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700895 * @return A pre-compiled {@link SQLiteStatement} object. Note that
896 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 */
898 public SQLiteStatement compileStatement(String sql) throws SQLException {
Jeff Browne5360fb2011-10-31 17:48:13 -0700899 throwIfNotOpen(); // fail fast
Vasu Nori0732f792010-07-29 17:24:12 -0700900 return new SQLiteStatement(this, sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
902
903 /**
904 * Query the given URL, returning a {@link Cursor} over the result set.
905 *
906 * @param distinct true if you want each row to be unique, false otherwise.
907 * @param table The table name to compile the query against.
908 * @param columns A list of which columns to return. Passing null will
909 * return all columns, which is discouraged to prevent reading
910 * data from storage that isn't going to be used.
911 * @param selection A filter declaring which rows to return, formatted as an
912 * SQL WHERE clause (excluding the WHERE itself). Passing null
913 * will return all rows for the given table.
914 * @param selectionArgs You may include ?s in selection, which will be
915 * replaced by the values from selectionArgs, in order that they
916 * appear in the selection. The values will be bound as Strings.
917 * @param groupBy A filter declaring how to group rows, formatted as an SQL
918 * GROUP BY clause (excluding the GROUP BY itself). Passing null
919 * will cause the rows to not be grouped.
920 * @param having A filter declare which row groups to include in the cursor,
921 * if row grouping is being used, formatted as an SQL HAVING
922 * clause (excluding the HAVING itself). Passing null will cause
923 * all row groups to be included, and is required when row
924 * grouping is not being used.
925 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
926 * (excluding the ORDER BY itself). Passing null will use the
927 * default sort order, which may be unordered.
928 * @param limit Limits the number of rows returned by the query,
929 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700930 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
931 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 * @see Cursor
933 */
934 public Cursor query(boolean distinct, String table, String[] columns,
935 String selection, String[] selectionArgs, String groupBy,
936 String having, String orderBy, String limit) {
937 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
938 groupBy, having, orderBy, limit);
939 }
940
941 /**
942 * Query the given URL, returning a {@link Cursor} over the result set.
943 *
944 * @param cursorFactory the cursor factory to use, or null for the default factory
945 * @param distinct true if you want each row to be unique, false otherwise.
946 * @param table The table name to compile the query against.
947 * @param columns A list of which columns to return. Passing null will
948 * return all columns, which is discouraged to prevent reading
949 * data from storage that isn't going to be used.
950 * @param selection A filter declaring which rows to return, formatted as an
951 * SQL WHERE clause (excluding the WHERE itself). Passing null
952 * will return all rows for the given table.
953 * @param selectionArgs You may include ?s in selection, which will be
954 * replaced by the values from selectionArgs, in order that they
955 * appear in the selection. The values will be bound as Strings.
956 * @param groupBy A filter declaring how to group rows, formatted as an SQL
957 * GROUP BY clause (excluding the GROUP BY itself). Passing null
958 * will cause the rows to not be grouped.
959 * @param having A filter declare which row groups to include in the cursor,
960 * if row grouping is being used, formatted as an SQL HAVING
961 * clause (excluding the HAVING itself). Passing null will cause
962 * all row groups to be included, and is required when row
963 * grouping is not being used.
964 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
965 * (excluding the ORDER BY itself). Passing null will use the
966 * default sort order, which may be unordered.
967 * @param limit Limits the number of rows returned by the query,
968 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -0700969 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
970 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 * @see Cursor
972 */
973 public Cursor queryWithFactory(CursorFactory cursorFactory,
974 boolean distinct, String table, String[] columns,
975 String selection, String[] selectionArgs, String groupBy,
976 String having, String orderBy, String limit) {
Jeff Browne5360fb2011-10-31 17:48:13 -0700977 throwIfNotOpen(); // fail fast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 String sql = SQLiteQueryBuilder.buildQueryString(
979 distinct, table, columns, selection, groupBy, having, orderBy, limit);
980
981 return rawQueryWithFactory(
982 cursorFactory, sql, selectionArgs, findEditTable(table));
983 }
984
985 /**
986 * Query the given table, returning a {@link Cursor} over the result set.
987 *
988 * @param table The table name to compile the query against.
989 * @param columns A list of which columns to return. Passing null will
990 * return all columns, which is discouraged to prevent reading
991 * data from storage that isn't going to be used.
992 * @param selection A filter declaring which rows to return, formatted as an
993 * SQL WHERE clause (excluding the WHERE itself). Passing null
994 * will return all rows for the given table.
995 * @param selectionArgs You may include ?s in selection, which will be
996 * replaced by the values from selectionArgs, in order that they
997 * appear in the selection. The values will be bound as Strings.
998 * @param groupBy A filter declaring how to group rows, formatted as an SQL
999 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1000 * will cause the rows to not be grouped.
1001 * @param having A filter declare which row groups to include in the cursor,
1002 * if row grouping is being used, formatted as an SQL HAVING
1003 * clause (excluding the HAVING itself). Passing null will cause
1004 * all row groups to be included, and is required when row
1005 * grouping is not being used.
1006 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1007 * (excluding the ORDER BY itself). Passing null will use the
1008 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001009 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1010 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 * @see Cursor
1012 */
1013 public Cursor query(String table, String[] columns, String selection,
1014 String[] selectionArgs, String groupBy, String having,
1015 String orderBy) {
1016
1017 return query(false, table, columns, selection, selectionArgs, groupBy,
1018 having, orderBy, null /* limit */);
1019 }
1020
1021 /**
1022 * Query the given table, returning a {@link Cursor} over the result set.
1023 *
1024 * @param table The table name to compile the query against.
1025 * @param columns A list of which columns to return. Passing null will
1026 * return all columns, which is discouraged to prevent reading
1027 * data from storage that isn't going to be used.
1028 * @param selection A filter declaring which rows to return, formatted as an
1029 * SQL WHERE clause (excluding the WHERE itself). Passing null
1030 * will return all rows for the given table.
1031 * @param selectionArgs You may include ?s in selection, which will be
1032 * replaced by the values from selectionArgs, in order that they
1033 * appear in the selection. The values will be bound as Strings.
1034 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1035 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1036 * will cause the rows to not be grouped.
1037 * @param having A filter declare which row groups to include in the cursor,
1038 * if row grouping is being used, formatted as an SQL HAVING
1039 * clause (excluding the HAVING itself). Passing null will cause
1040 * all row groups to be included, and is required when row
1041 * grouping is not being used.
1042 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1043 * (excluding the ORDER BY itself). Passing null will use the
1044 * default sort order, which may be unordered.
1045 * @param limit Limits the number of rows returned by the query,
1046 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001047 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1048 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 * @see Cursor
1050 */
1051 public Cursor query(String table, String[] columns, String selection,
1052 String[] selectionArgs, String groupBy, String having,
1053 String orderBy, String limit) {
1054
1055 return query(false, table, columns, selection, selectionArgs, groupBy,
1056 having, orderBy, limit);
1057 }
1058
1059 /**
1060 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1061 *
1062 * @param sql the SQL query. The SQL string must not be ; terminated
1063 * @param selectionArgs You may include ?s in where clause in the query,
1064 * which will be replaced by the values from selectionArgs. The
1065 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001066 * @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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 */
1069 public Cursor rawQuery(String sql, String[] selectionArgs) {
1070 return rawQueryWithFactory(null, sql, selectionArgs, null);
1071 }
1072
1073 /**
1074 * Runs the provided SQL and returns a cursor over the result set.
1075 *
1076 * @param cursorFactory the cursor factory to use, or null for the default factory
1077 * @param sql the SQL query. The SQL string must not be ; terminated
1078 * @param selectionArgs You may include ?s in where clause in the query,
1079 * which will be replaced by the values from selectionArgs. The
1080 * values will be bound as Strings.
1081 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001082 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1083 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 */
1085 public Cursor rawQueryWithFactory(
1086 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1087 String editTable) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001088 throwIfNotOpen(); // fail fast
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089
Jeff Browne5360fb2011-10-31 17:48:13 -07001090 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, editTable);
1091 return driver.query(cursorFactory != null ? cursorFactory : mCursorFactory,
1092 selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094
1095 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 * Convenience method for inserting a row into the database.
1097 *
1098 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001099 * @param nullColumnHack optional; may be <code>null</code>.
1100 * SQL doesn't allow inserting a completely empty row without
1101 * naming at least one column name. If your provided <code>values</code> is
1102 * empty, no column names are known and an empty row can't be inserted.
1103 * If not set to null, the <code>nullColumnHack</code> parameter
1104 * provides the name of nullable column name to explicitly insert a NULL into
1105 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 * @param values this map contains the initial column values for the
1107 * row. The keys should be the column names and the values the
1108 * column values
1109 * @return the row ID of the newly inserted row, or -1 if an error occurred
1110 */
1111 public long insert(String table, String nullColumnHack, ContentValues values) {
1112 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001113 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 } catch (SQLException e) {
1115 Log.e(TAG, "Error inserting " + values, e);
1116 return -1;
1117 }
1118 }
1119
1120 /**
1121 * Convenience method for inserting a row into the database.
1122 *
1123 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001124 * @param nullColumnHack optional; may be <code>null</code>.
1125 * SQL doesn't allow inserting a completely empty row without
1126 * naming at least one column name. If your provided <code>values</code> is
1127 * empty, no column names are known and an empty row can't be inserted.
1128 * If not set to null, the <code>nullColumnHack</code> parameter
1129 * provides the name of nullable column name to explicitly insert a NULL into
1130 * in the case where your <code>values</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 * @param values this map contains the initial column values for the
1132 * row. The keys should be the column names and the values the
1133 * column values
1134 * @throws SQLException
1135 * @return the row ID of the newly inserted row, or -1 if an error occurred
1136 */
1137 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1138 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001139 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141
1142 /**
1143 * Convenience method for replacing a row in the database.
1144 *
1145 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001146 * @param nullColumnHack optional; may be <code>null</code>.
1147 * SQL doesn't allow inserting a completely empty row without
1148 * naming at least one column name. If your provided <code>initialValues</code> is
1149 * empty, no column names are known and an empty row can't be inserted.
1150 * If not set to null, the <code>nullColumnHack</code> parameter
1151 * provides the name of nullable column name to explicitly insert a NULL into
1152 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 * @param initialValues this map contains the initial column values for
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001154 * the row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 * @return the row ID of the newly inserted row, or -1 if an error occurred
1156 */
1157 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1158 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001159 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001160 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } catch (SQLException e) {
1162 Log.e(TAG, "Error inserting " + initialValues, e);
1163 return -1;
1164 }
1165 }
1166
1167 /**
1168 * Convenience method for replacing a row in the database.
1169 *
1170 * @param table the table in which to replace the row
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001171 * @param nullColumnHack optional; may be <code>null</code>.
1172 * SQL doesn't allow inserting a completely empty row without
1173 * naming at least one column name. If your provided <code>initialValues</code> is
1174 * empty, no column names are known and an empty row can't be inserted.
1175 * If not set to null, the <code>nullColumnHack</code> parameter
1176 * provides the name of nullable column name to explicitly insert a NULL into
1177 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 * @param initialValues this map contains the initial column values for
1179 * the row. The key
1180 * @throws SQLException
1181 * @return the row ID of the newly inserted row, or -1 if an error occurred
1182 */
1183 public long replaceOrThrow(String table, String nullColumnHack,
1184 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001185 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001186 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188
1189 /**
1190 * General method for inserting a row into the database.
1191 *
1192 * @param table the table to insert the row into
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001193 * @param nullColumnHack optional; may be <code>null</code>.
1194 * SQL doesn't allow inserting a completely empty row without
1195 * naming at least one column name. If your provided <code>initialValues</code> is
1196 * empty, no column names are known and an empty row can't be inserted.
1197 * If not set to null, the <code>nullColumnHack</code> parameter
1198 * provides the name of nullable column name to explicitly insert a NULL into
1199 * in the case where your <code>initialValues</code> is empty.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 * @param initialValues this map contains the initial column values for the
1201 * row. The keys should be the column names and the values the
1202 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001203 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001204 * @return the row ID of the newly inserted row
1205 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001206 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001207 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 */
1209 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001210 ContentValues initialValues, int conflictAlgorithm) {
Vasu Nori0732f792010-07-29 17:24:12 -07001211 StringBuilder sql = new StringBuilder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001213 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 sql.append(" INTO ");
1215 sql.append(table);
Vasu Nori0732f792010-07-29 17:24:12 -07001216 sql.append('(');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217
Vasu Nori0732f792010-07-29 17:24:12 -07001218 Object[] bindArgs = null;
1219 int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
1220 if (size > 0) {
1221 bindArgs = new Object[size];
1222 int i = 0;
1223 for (String colName : initialValues.keySet()) {
1224 sql.append((i > 0) ? "," : "");
1225 sql.append(colName);
1226 bindArgs[i++] = initialValues.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 sql.append(')');
Vasu Nori0732f792010-07-29 17:24:12 -07001229 sql.append(" VALUES (");
1230 for (i = 0; i < size; i++) {
1231 sql.append((i > 0) ? ",?" : "?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
Vasu Nori0732f792010-07-29 17:24:12 -07001233 } else {
1234 sql.append(nullColumnHack + ") VALUES (NULL");
1235 }
1236 sql.append(')');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
Vasu Nori0732f792010-07-29 17:24:12 -07001238 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
1239 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001240 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001242 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244 }
1245
1246 /**
1247 * Convenience method for deleting rows in the database.
1248 *
1249 * @param table the table to delete from
1250 * @param whereClause the optional WHERE clause to apply when deleting.
1251 * Passing null will delete all rows.
1252 * @return the number of rows affected if a whereClause is passed in, 0
1253 * otherwise. To remove all rows and get a count pass "1" as the
1254 * whereClause.
1255 */
1256 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Nori0732f792010-07-29 17:24:12 -07001257 SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
1258 (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001260 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001262 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264 }
1265
1266 /**
1267 * Convenience method for updating rows in the database.
1268 *
1269 * @param table the table to update in
1270 * @param values a map from column names to new column values. null is a
1271 * valid value that will be translated to NULL.
1272 * @param whereClause the optional WHERE clause to apply when updating.
1273 * Passing null will update all rows.
1274 * @return the number of rows affected
1275 */
1276 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001277 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 /**
1281 * Convenience method for updating rows in the database.
1282 *
1283 * @param table the table to update in
1284 * @param values a map from column names to new column values. null is a
1285 * valid value that will be translated to NULL.
1286 * @param whereClause the optional WHERE clause to apply when updating.
1287 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001288 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001291 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001292 String whereClause, String[] whereArgs, int conflictAlgorithm) {
Brian Muramatsu46a88512010-11-12 13:53:57 -08001293 if (values == null || values.size() == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 throw new IllegalArgumentException("Empty values");
1295 }
1296
1297 StringBuilder sql = new StringBuilder(120);
1298 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001299 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 sql.append(table);
1301 sql.append(" SET ");
1302
Vasu Nori0732f792010-07-29 17:24:12 -07001303 // move all bind args to one array
Brian Muramatsu46a88512010-11-12 13:53:57 -08001304 int setValuesSize = values.size();
Vasu Nori0732f792010-07-29 17:24:12 -07001305 int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
1306 Object[] bindArgs = new Object[bindArgsSize];
1307 int i = 0;
1308 for (String colName : values.keySet()) {
1309 sql.append((i > 0) ? "," : "");
1310 sql.append(colName);
1311 bindArgs[i++] = values.get(colName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 sql.append("=?");
Vasu Nori0732f792010-07-29 17:24:12 -07001313 }
1314 if (whereArgs != null) {
1315 for (i = setValuesSize; i < bindArgsSize; i++) {
1316 bindArgs[i] = whereArgs[i - setValuesSize];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
1318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 if (!TextUtils.isEmpty(whereClause)) {
1320 sql.append(" WHERE ");
1321 sql.append(whereClause);
1322 }
1323
Vasu Nori0732f792010-07-29 17:24:12 -07001324 SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 try {
Vasu Norifb16cbd2010-07-25 16:38:48 -07001326 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001328 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 }
1331
1332 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001333 * Execute a single SQL statement that is NOT a SELECT
1334 * or any other SQL statement that returns data.
1335 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001336 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001337 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1338 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1339 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001340 * <p>
1341 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1342 * automatically managed by this class. So, do not set journal_mode
1343 * using "PRAGMA journal_mode'<value>" statement if your app is using
1344 * {@link #enableWriteAheadLogging()}
1345 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 *
Vasu Noriccd95442010-05-28 17:04:16 -07001347 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1348 * not supported.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001349 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001351 public void execSQL(String sql) throws SQLException {
Vasu Nori16057fa2011-03-18 11:40:37 -07001352 executeSql(sql, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 }
1354
1355 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001356 * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
1357 * <p>
1358 * For INSERT statements, use any of the following instead.
1359 * <ul>
1360 * <li>{@link #insert(String, String, ContentValues)}</li>
1361 * <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
1362 * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
1363 * </ul>
1364 * <p>
1365 * For UPDATE statements, use any of the following instead.
1366 * <ul>
1367 * <li>{@link #update(String, ContentValues, String, String[])}</li>
1368 * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
1369 * </ul>
1370 * <p>
1371 * For DELETE statements, use any of the following instead.
1372 * <ul>
1373 * <li>{@link #delete(String, String, String[])}</li>
1374 * </ul>
1375 * <p>
1376 * For example, the following are good candidates for using this method:
1377 * <ul>
1378 * <li>ALTER TABLE</li>
1379 * <li>CREATE or DROP table / trigger / view / index / virtual table</li>
1380 * <li>REINDEX</li>
1381 * <li>RELEASE</li>
1382 * <li>SAVEPOINT</li>
1383 * <li>PRAGMA that returns no data</li>
1384 * </ul>
1385 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001386 * <p>
1387 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1388 * automatically managed by this class. So, do not set journal_mode
1389 * using "PRAGMA journal_mode'<value>" statement if your app is using
1390 * {@link #enableWriteAheadLogging()}
1391 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 *
Vasu Noriccd95442010-05-28 17:04:16 -07001393 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1394 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
Brad Fitzpatrick69ea4e12011-01-05 11:13:40 -08001396 * @throws SQLException if the SQL string is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 */
Vasu Norib83cb7c2010-09-14 13:36:01 -07001398 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 if (bindArgs == null) {
1400 throw new IllegalArgumentException("Empty bindArgs");
1401 }
Vasu Norib83cb7c2010-09-14 13:36:01 -07001402 executeSql(sql, bindArgs);
Vasu Norice38b982010-07-22 13:57:13 -07001403 }
1404
Vasu Nori54025902010-09-14 12:14:26 -07001405 private int executeSql(String sql, Object[] bindArgs) throws SQLException {
Vasu Noricc1eaf62011-03-14 19:22:16 -07001406 if (DatabaseUtils.getSqlStatementType(sql) == DatabaseUtils.STATEMENT_ATTACH) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001407 boolean disableWal = false;
1408 synchronized (mLock) {
1409 if (!mHasAttachedDbsLocked) {
1410 mHasAttachedDbsLocked = true;
1411 disableWal = true;
1412 }
1413 }
1414 if (disableWal) {
1415 disableWriteAheadLogging();
1416 }
Vasu Noricc1eaf62011-03-14 19:22:16 -07001417 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001418
Vasu Nori0732f792010-07-29 17:24:12 -07001419 SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 try {
Vasu Nori16057fa2011-03-18 11:40:37 -07001421 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 } finally {
Vasu Nori0732f792010-07-29 17:24:12 -07001423 statement.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001428 * Returns true if the database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001430 * @return True if database is opened as read only.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 */
1432 public boolean isReadOnly() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001433 synchronized (mLock) {
1434 return isReadOnlyLocked();
1435 }
1436 }
1437
1438 private boolean isReadOnlyLocked() {
1439 return (mConfigurationLocked.openFlags & OPEN_READ_MASK) == OPEN_READONLY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441
1442 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001443 * Returns true if the database is in-memory db.
1444 *
1445 * @return True if the database is in-memory.
1446 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001448 public boolean isInMemoryDatabase() {
1449 synchronized (mLock) {
1450 return mConfigurationLocked.isInMemoryDb();
1451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
Jeff Browne5360fb2011-10-31 17:48:13 -07001454 /**
1455 * Returns true if the database is currently open.
1456 *
1457 * @return True if the database is currently open (has not been closed).
1458 */
1459 public boolean isOpen() {
1460 synchronized (mLock) {
1461 return mConnectionPoolLocked != null;
1462 }
1463 }
1464
1465 /**
1466 * Returns true if the new version code is greater than the current database version.
1467 *
1468 * @param newVersion The new version code.
1469 * @return True if the new version code is greater than the current database version.
1470 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 public boolean needUpgrade(int newVersion) {
1472 return newVersion > getVersion();
1473 }
1474
1475 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001476 * Gets the path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001478 * @return The path to the database file.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 */
1480 public final String getPath() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001481 synchronized (mLock) {
1482 return mConfigurationLocked.path;
Christopher Tatead9e8b12011-10-05 17:49:26 -07001483 }
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001484 }
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 /**
1487 * Sets the locale for this database. Does nothing if this database has
1488 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
Jeff Browne5360fb2011-10-31 17:48:13 -07001489 *
1490 * @param locale The new locale.
1491 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 * @throws SQLException if the locale could not be set. The most common reason
1493 * for this is that there is no collator available for the locale you requested.
1494 * In this case the database remains unchanged.
1495 */
1496 public void setLocale(Locale locale) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001497 if (locale == null) {
1498 throw new IllegalArgumentException("locale must not be null.");
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001499 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001500
Jeff Browne5360fb2011-10-31 17:48:13 -07001501 synchronized (mLock) {
1502 throwIfNotOpenLocked();
1503 mConfigurationLocked.locale = locale;
1504 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Vasu Norib729dcc2010-09-14 11:35:49 -07001505 }
Vasu Norib729dcc2010-09-14 11:35:49 -07001506 }
1507
Vasu Norie495d1f2010-01-06 16:34:19 -08001508 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001509 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08001510 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07001511 *<p>
Vasu Norib729dcc2010-09-14 11:35:49 -07001512 * Maximum cache size can ONLY be increased from its current size (default = 10).
Vasu Noriccd95442010-05-28 17:04:16 -07001513 * If this method is called with smaller size than the current maximum value,
1514 * then IllegalStateException is thrown.
Vasu Norib729dcc2010-09-14 11:35:49 -07001515 *<p>
1516 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08001517 *
Vasu Nori90a367262010-04-12 12:49:09 -07001518 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
Jeff Browne5360fb2011-10-31 17:48:13 -07001519 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE}.
Vasu Norie495d1f2010-01-06 16:34:19 -08001520 */
Vasu Nori54025902010-09-14 12:14:26 -07001521 public void setMaxSqlCacheSize(int cacheSize) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001522 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
1523 throw new IllegalStateException(
1524 "expected value between 0 and " + MAX_SQL_CACHE_SIZE);
Vasu Nori587423a2010-09-27 18:18:34 -07001525 }
Vasu Nori587423a2010-09-27 18:18:34 -07001526
Jeff Browne5360fb2011-10-31 17:48:13 -07001527 synchronized (mLock) {
1528 throwIfNotOpenLocked();
1529 mConfigurationLocked.maxSqlCacheSize = cacheSize;
1530 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Jesse Wilsondfe515e2011-02-10 19:06:09 -08001531 }
1532 }
1533
Vasu Nori6c354da2010-04-26 23:33:39 -07001534 /**
1535 * This method enables parallel execution of queries from multiple threads on the same database.
1536 * It does this by opening multiple handles to the database and using a different
1537 * database handle for each query.
1538 * <p>
1539 * If a transaction is in progress on one connection handle and say, a table is updated in the
1540 * transaction, then query on the same table on another connection handle will block for the
1541 * transaction to complete. But this method enables such queries to execute by having them
1542 * return old version of the data from the table. Most often it is the data that existed in the
1543 * table prior to the above transaction updates on that table.
1544 * <p>
1545 * Maximum number of simultaneous handles used to execute queries in parallel is
1546 * dependent upon the device memory and possibly other properties.
1547 * <p>
1548 * After calling this method, execution of queries in parallel is enabled as long as this
1549 * database handle is open. To disable execution of queries in parallel, database should
1550 * be closed and reopened.
1551 * <p>
1552 * If a query is part of a transaction, then it is executed on the same database handle the
1553 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07001554 * <p>
1555 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07001556 * possible. In such cases, a message is printed to logcat and false is returned.
1557 * <p>
1558 * This feature is not available for :memory: databases. In such cases,
1559 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07001560 * <p>
1561 * A typical way to use this method is the following:
1562 * <pre>
1563 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
1564 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
1565 * db.enableWriteAheadLogging();
1566 * </pre>
1567 * <p>
1568 * Writers should use {@link #beginTransactionNonExclusive()} or
1569 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
1570 * to start a trsnsaction.
1571 * Non-exclusive mode allows database file to be in readable by threads executing queries.
1572 * </p>
1573 *
Vasu Noria98cb262010-06-22 13:16:35 -07001574 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07001575 */
Vasu Noriffe06122010-09-27 12:32:57 -07001576 public boolean enableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001577 synchronized (mLock) {
1578 throwIfNotOpenLocked();
1579
1580 if (mIsWALEnabledLocked) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001581 return true;
1582 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001583
1584 if (isReadOnlyLocked()) {
1585 // WAL doesn't make sense for readonly-databases.
1586 // TODO: True, but connection pooling does still make sense...
1587 return false;
1588 }
1589
1590 if (mConfigurationLocked.isInMemoryDb()) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001591 Log.i(TAG, "can't enable WAL for memory databases.");
1592 return false;
1593 }
1594
1595 // make sure this database has NO attached databases because sqlite's write-ahead-logging
1596 // doesn't work for databases with attached databases
Jeff Browne5360fb2011-10-31 17:48:13 -07001597 if (mHasAttachedDbsLocked) {
Paul Westbrookdae6d372011-02-17 10:59:56 -08001598 if (Log.isLoggable(TAG, Log.DEBUG)) {
Jeff Browne5360fb2011-10-31 17:48:13 -07001599 Log.d(TAG, "this database: " + mConfigurationLocked.label
1600 + " has attached databases. can't enable WAL.");
Paul Westbrookdae6d372011-02-17 10:59:56 -08001601 }
1602 return false;
1603 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001604
1605 mIsWALEnabledLocked = true;
1606 mConfigurationLocked.maxConnectionPoolSize = Math.max(2,
1607 Resources.getSystem().getInteger(
1608 com.android.internal.R.integer.db_connection_pool_size));
1609 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Paul Westbrookdae6d372011-02-17 10:59:56 -08001610 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001611
1612 setJournalMode("WAL");
1613 return true;
Vasu Nori6c354da2010-04-26 23:33:39 -07001614 }
1615
Vasu Nori2827d6d2010-07-04 00:26:18 -07001616 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07001617 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
1618 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07001619 */
Vasu Nori7b04c412010-07-20 10:31:21 -07001620 public void disableWriteAheadLogging() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001621 synchronized (mLock) {
1622 throwIfNotOpenLocked();
1623
1624 if (!mIsWALEnabledLocked) {
1625 return;
Paul Westbrookdae6d372011-02-17 10:59:56 -08001626 }
Vasu Nori8d111032010-06-22 18:34:21 -07001627
Jeff Browne5360fb2011-10-31 17:48:13 -07001628 mIsWALEnabledLocked = false;
1629 mConfigurationLocked.maxConnectionPoolSize = 1;
1630 mConnectionPoolLocked.reconfigure(mConfigurationLocked);
Vasu Nori65a88832010-07-16 15:14:08 -07001631 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001632
Jeff Browne5360fb2011-10-31 17:48:13 -07001633 setJournalMode("TRUNCATE");
Vasu Nori6c354da2010-04-26 23:33:39 -07001634 }
1635
Vasu Norif3cf8a42010-03-23 11:41:44 -07001636 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001637 * Collect statistics about all open databases in the current process.
1638 * Used by bug report.
Vasu Norif3cf8a42010-03-23 11:41:44 -07001639 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001640 static ArrayList<DbStats> getDbStats() {
Vasu Noric3849202010-03-09 10:47:25 -08001641 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001642 for (SQLiteDatabase db : getActiveDatabases()) {
1643 db.collectDbStats(dbStatsList);
Vasu Nori24675612010-09-27 14:54:19 -07001644 }
Vasu Noric3849202010-03-09 10:47:25 -08001645 return dbStatsList;
1646 }
1647
Jeff Browne5360fb2011-10-31 17:48:13 -07001648 private void collectDbStats(ArrayList<DbStats> dbStatsList) {
1649 synchronized (mLock) {
1650 if (mConnectionPoolLocked != null) {
1651 mConnectionPoolLocked.collectDbStats(dbStatsList);
1652 }
1653 }
1654 }
1655
1656 private static ArrayList<SQLiteDatabase> getActiveDatabases() {
1657 ArrayList<SQLiteDatabase> databases = new ArrayList<SQLiteDatabase>();
1658 synchronized (sActiveDatabases) {
1659 databases.addAll(sActiveDatabases.keySet());
1660 }
1661 return databases;
1662 }
1663
1664 /**
1665 * Dump detailed information about all open databases in the current process.
1666 * Used by bug report.
1667 */
1668 static void dumpAll(Printer printer) {
1669 for (SQLiteDatabase db : getActiveDatabases()) {
1670 db.dump(printer);
1671 }
1672 }
1673
1674 private void dump(Printer printer) {
1675 synchronized (mLock) {
1676 if (mConnectionPoolLocked != null) {
1677 printer.println("");
1678 mConnectionPoolLocked.dump(printer);
1679 }
1680 }
1681 }
1682
Vasu Noric3849202010-03-09 10:47:25 -08001683 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001684 * Returns list of full pathnames of all attached databases including the main database
1685 * by executing 'pragma database_list' on the database.
1686 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001687 * @return ArrayList of pairs of (database name, database file path) or null if the database
1688 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08001689 */
Vasu Noria017eda2011-01-27 10:52:55 -08001690 public List<Pair<String, String>> getAttachedDbs() {
Vasu Noric3849202010-03-09 10:47:25 -08001691 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001692 synchronized (mLock) {
1693 if (mConnectionPoolLocked == null) {
1694 return null; // not open
1695 }
1696
1697 if (!mHasAttachedDbsLocked) {
1698 // No attached databases.
1699 // There is a small window where attached databases exist but this flag is not
1700 // set yet. This can occur when this thread is in a race condition with another
1701 // thread that is executing the SQL statement: "attach database <blah> as <foo>"
1702 // If this thread is NOT ok with such a race condition (and thus possibly not
1703 // receivethe entire list of attached databases), then the caller should ensure
1704 // that no thread is executing any SQL statements while a thread is calling this
1705 // method. Typically, this method is called when 'adb bugreport' is done or the
1706 // caller wants to collect stats on the database and all its attached databases.
1707 attachedDbs.add(new Pair<String, String>("main", mConfigurationLocked.path));
1708 return attachedDbs;
1709 }
Vasu Nori24675612010-09-27 14:54:19 -07001710 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001711
Vasu Nori24675612010-09-27 14:54:19 -07001712 // has attached databases. query sqlite to get the list of attached databases.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001713 Cursor c = null;
1714 try {
1715 c = rawQuery("pragma database_list;", null);
1716 while (c.moveToNext()) {
1717 // sqlite returns a row for each database in the returned list of databases.
1718 // in each row,
1719 // 1st column is the database name such as main, or the database
1720 // name specified on the "ATTACH" command
1721 // 2nd column is the database file path.
1722 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
1723 }
1724 } finally {
1725 if (c != null) {
1726 c.close();
1727 }
Vasu Noric3849202010-03-09 10:47:25 -08001728 }
Vasu Noric3849202010-03-09 10:47:25 -08001729 return attachedDbs;
1730 }
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001733 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
1734 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001735 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07001736 *<p>
1737 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001738 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07001739 *<p>
1740 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001741 *
1742 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07001743 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001744 */
1745 public boolean isDatabaseIntegrityOk() {
Jeff Browne5360fb2011-10-31 17:48:13 -07001746 throwIfNotOpen(); // fail fast
1747
Vasu Noria017eda2011-01-27 10:52:55 -08001748 List<Pair<String, String>> attachedDbs = null;
Vasu Noribfe1dc22010-08-25 16:29:02 -07001749 try {
1750 attachedDbs = getAttachedDbs();
1751 if (attachedDbs == null) {
1752 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
1753 "be retrieved. probably because the database is closed");
1754 }
1755 } catch (SQLiteException e) {
1756 // can't get attachedDb list. do integrity check on the main database
1757 attachedDbs = new ArrayList<Pair<String, String>>();
Jeff Browne5360fb2011-10-31 17:48:13 -07001758 attachedDbs.add(new Pair<String, String>("main", getPath()));
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001759 }
Jeff Browne5360fb2011-10-31 17:48:13 -07001760
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001761 for (int i = 0; i < attachedDbs.size(); i++) {
1762 Pair<String, String> p = attachedDbs.get(i);
1763 SQLiteStatement prog = null;
1764 try {
1765 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
1766 String rslt = prog.simpleQueryForString();
1767 if (!rslt.equalsIgnoreCase("ok")) {
1768 // integrity_checker failed on main or attached databases
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001769 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
Vasu Noribfe1dc22010-08-25 16:29:02 -07001770 return false;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001771 }
1772 } finally {
1773 if (prog != null) prog.close();
1774 }
1775 }
Vasu Noribfe1dc22010-08-25 16:29:02 -07001776 return true;
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001777 }
1778
1779 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001780 * Prevent other threads from using the database's primary connection.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001782 * This method is only used by {@link SQLiteOpenHelper} when transitioning from
1783 * a readable to a writable database. It should not be used in any other way.
Vasu Nori3ef94e22010-02-05 14:49:04 -08001784 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001785 * @see #unlockPrimaryConnection()
Vasu Nori3ef94e22010-02-05 14:49:04 -08001786 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001787 void lockPrimaryConnection() {
1788 getThreadSession().beginTransaction(SQLiteSession.TRANSACTION_MODE_DEFERRED,
1789 null, SQLiteConnectionPool.CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY);
1790 }
Vasu Nori3ef94e22010-02-05 14:49:04 -08001791
1792 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001793 * Allow other threads to use the database's primary connection.
Vasu Nori3ef94e22010-02-05 14:49:04 -08001794 *
Jeff Browne5360fb2011-10-31 17:48:13 -07001795 * @see #lockPrimaryConnection()
Vasu Nori3ef94e22010-02-05 14:49:04 -08001796 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001797 void unlockPrimaryConnection() {
1798 getThreadSession().endTransaction();
1799 }
1800
1801 @Override
1802 public String toString() {
1803 return "SQLiteDatabase: " + getPath();
1804 }
1805
1806 private void throwIfNotOpen() {
1807 synchronized (mConnectionPoolLocked) {
1808 throwIfNotOpenLocked();
1809 }
1810 }
1811
1812 private void throwIfNotOpenLocked() {
1813 if (mConnectionPoolLocked == null) {
1814 throw new IllegalStateException("The database '" + mConfigurationLocked.label
1815 + "' is not open.");
1816 }
1817 }
Vasu Nori3ef94e22010-02-05 14:49:04 -08001818
1819 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001820 * Used to allow returning sub-classes of {@link Cursor} when calling query.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001822 public interface CursorFactory {
1823 /**
1824 * See {@link SQLiteCursor#SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)}.
1825 */
1826 public Cursor newCursor(SQLiteDatabase db,
1827 SQLiteCursorDriver masterQuery, String editTable,
1828 SQLiteQuery query);
1829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830
1831 /**
Jeff Browne5360fb2011-10-31 17:48:13 -07001832 * A callback interface for a custom sqlite3 function.
1833 * This can be used to create a function that can be called from
1834 * sqlite3 database triggers.
1835 * @hide
Vasu Noric3849202010-03-09 10:47:25 -08001836 */
Jeff Browne5360fb2011-10-31 17:48:13 -07001837 public interface CustomFunction {
1838 public void callback(String[] args);
1839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840}