blob: a2fff730e227a0519d48d29c88bcf29fc8250927 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.database.sqlite;
18
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070019import android.app.AppGlobals;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentValues;
21import 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.os.Debug;
Vasu Noria8c24902010-06-01 11:30:27 -070028import android.os.StatFs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.os.SystemClock;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070030import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.text.TextUtils;
32import android.util.Config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.util.EventLog;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -070034import android.util.Log;
Vasu Noric3849202010-03-09 10:47:25 -080035import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -070037import dalvik.system.BlockGuard;
38
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import java.io.File;
Vasu Noric3849202010-03-09 10:47:25 -080040import java.lang.ref.WeakReference;
Vasu Noric3849202010-03-09 10:47:25 -080041import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.util.HashMap;
Vasu Noric3849202010-03-09 10:47:25 -080043import java.util.HashSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.util.Iterator;
Vasu Nori20f549f2010-04-15 11:25:51 -070045import java.util.LinkedHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import java.util.Locale;
47import java.util.Map;
Dan Egnor12311952009-11-23 14:47:45 -080048import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.Set;
50import java.util.WeakHashMap;
51import java.util.concurrent.locks.ReentrantLock;
Brad Fitzpatrickd8330232010-02-19 10:59:01 -080052import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
54/**
55 * Exposes methods to manage a SQLite database.
56 * <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and
57 * perform other common database management tasks.
58 * <p>See the Notepad sample application in the SDK for an example of creating
59 * and managing a database.
60 * <p> Database names must be unique within an application, not across all
61 * applications.
62 *
63 * <h3>Localized Collation - ORDER BY</h3>
64 * <p>In addition to SQLite's default <code>BINARY</code> collator, Android supplies
65 * two more, <code>LOCALIZED</code>, which changes with the system's current locale
66 * if you wire it up correctly (XXX a link needed!), and <code>UNICODE</code>, which
67 * is the Unicode Collation Algorithm and not tailored to the current locale.
68 */
69public class SQLiteDatabase extends SQLiteClosable {
Vasu Norifb16cbd2010-07-25 16:38:48 -070070 private static final String TAG = "SQLiteDatabase";
Jeff Hamilton082c2af2009-09-29 11:49:51 -070071 private static final int EVENT_DB_OPERATION = 52000;
72 private static final int EVENT_DB_CORRUPT = 75004;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74 /**
75 * Algorithms used in ON CONFLICT clause
76 * http://www.sqlite.org/lang_conflict.html
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 */
Vasu Nori8d45e4e2010-02-05 22:35:47 -080078 /**
79 * When a constraint violation occurs, an immediate ROLLBACK occurs,
80 * thus ending the current transaction, and the command aborts with a
81 * return code of SQLITE_CONSTRAINT. If no transaction is active
82 * (other than the implied transaction that is created on every command)
83 * then this algorithm works the same as ABORT.
84 */
85 public static final int CONFLICT_ROLLBACK = 1;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -070086
Vasu Nori8d45e4e2010-02-05 22:35:47 -080087 /**
88 * When a constraint violation occurs,no ROLLBACK is executed
89 * so changes from prior commands within the same transaction
90 * are preserved. This is the default behavior.
91 */
92 public static final int CONFLICT_ABORT = 2;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -070093
Vasu Nori8d45e4e2010-02-05 22:35:47 -080094 /**
95 * When a constraint violation occurs, the command aborts with a return
96 * code SQLITE_CONSTRAINT. But any changes to the database that
97 * the command made prior to encountering the constraint violation
98 * are preserved and are not backed out.
99 */
100 public static final int CONFLICT_FAIL = 3;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700101
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800102 /**
103 * When a constraint violation occurs, the one row that contains
104 * the constraint violation is not inserted or changed.
105 * But the command continues executing normally. Other rows before and
106 * after the row that contained the constraint violation continue to be
107 * inserted or updated normally. No error is returned.
108 */
109 public static final int CONFLICT_IGNORE = 4;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700110
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800111 /**
112 * When a UNIQUE constraint violation occurs, the pre-existing rows that
113 * are causing the constraint violation are removed prior to inserting
114 * or updating the current row. Thus the insert or update always occurs.
115 * The command continues executing normally. No error is returned.
116 * If a NOT NULL constraint violation occurs, the NULL value is replaced
117 * by the default value for that column. If the column has no default
118 * value, then the ABORT algorithm is used. If a CHECK constraint
119 * violation occurs then the IGNORE algorithm is used. When this conflict
120 * resolution strategy deletes rows in order to satisfy a constraint,
121 * it does not invoke delete triggers on those rows.
122 * This behavior might change in a future release.
123 */
124 public static final int CONFLICT_REPLACE = 5;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700125
Vasu Nori8d45e4e2010-02-05 22:35:47 -0800126 /**
127 * use the following when no conflict action is specified.
128 */
129 public static final int CONFLICT_NONE = 0;
130 private static final String[] CONFLICT_VALUES = new String[]
131 {"", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "};
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 /**
134 * Maximum Length Of A LIKE Or GLOB Pattern
135 * The pattern matching algorithm used in the default LIKE and GLOB implementation
136 * of SQLite can exhibit O(N^2) performance (where N is the number of characters in
137 * the pattern) for certain pathological cases. To avoid denial-of-service attacks
138 * the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes.
139 * The default value of this limit is 50000. A modern workstation can evaluate
140 * even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly.
141 * The denial of service problem only comes into play when the pattern length gets
142 * into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns
143 * are at most a few dozen bytes in length, paranoid application developers may
144 * want to reduce this parameter to something in the range of a few hundred
145 * if they know that external users are able to generate arbitrary patterns.
146 */
147 public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
148
149 /**
150 * Flag for {@link #openDatabase} to open the database for reading and writing.
151 * If the disk is full, this may fail even before you actually write anything.
152 *
153 * {@more} Note that the value of this flag is 0, so it is the default.
154 */
155 public static final int OPEN_READWRITE = 0x00000000; // update native code if changing
156
157 /**
158 * Flag for {@link #openDatabase} to open the database for reading only.
159 * This is the only reliable way to open a database if the disk may be full.
160 */
161 public static final int OPEN_READONLY = 0x00000001; // update native code if changing
162
163 private static final int OPEN_READ_MASK = 0x00000001; // update native code if changing
164
165 /**
166 * Flag for {@link #openDatabase} to open the database without support for localized collators.
167 *
168 * {@more} This causes the collator <code>LOCALIZED</code> not to be created.
169 * You must be consistent when using this flag to use the setting the database was
170 * created with. If this is set, {@link #setLocale} will do nothing.
171 */
172 public static final int NO_LOCALIZED_COLLATORS = 0x00000010; // update native code if changing
173
174 /**
175 * Flag for {@link #openDatabase} to create the database file if it does not already exist.
176 */
177 public static final int CREATE_IF_NECESSARY = 0x10000000; // update native code if changing
178
179 /**
180 * Indicates whether the most-recently started transaction has been marked as successful.
181 */
182 private boolean mInnerTransactionIsSuccessful;
183
184 /**
185 * Valid during the life of a transaction, and indicates whether the entire transaction (the
186 * outer one and all of the inner ones) so far has been successful.
187 */
188 private boolean mTransactionIsSuccessful;
189
Fred Quintanac4516a72009-09-03 12:14:06 -0700190 /**
191 * Valid during the life of a transaction.
192 */
193 private SQLiteTransactionListener mTransactionListener;
194
Vasu Norice38b982010-07-22 13:57:13 -0700195 /**
196 * this member is set if {@link #execSQL(String)} is used to begin and end transactions.
197 */
198 private boolean mTransactionUsingExecSql;
199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 /** Synchronize on this when accessing the database */
201 private final ReentrantLock mLock = new ReentrantLock(true);
202
203 private long mLockAcquiredWallTime = 0L;
204 private long mLockAcquiredThreadTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // limit the frequency of complaints about each database to one within 20 sec
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700207 // unless run command adb shell setprop log.tag.Database VERBOSE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private static final int LOCK_WARNING_WINDOW_IN_MS = 20000;
209 /** If the lock is held this long then a warning will be printed when it is released. */
210 private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS = 300;
211 private static final int LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS = 100;
212 private static final int LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT = 2000;
213
Dmitri Plotnikovb43b58d2009-09-09 18:10:42 -0700214 private static final int SLEEP_AFTER_YIELD_QUANTUM = 1000;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700215
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800216 // The pattern we remove from database filenames before
217 // potentially logging them.
218 private static final Pattern EMAIL_IN_DB_PATTERN = Pattern.compile("[\\w\\.\\-]+@[\\w\\.\\-]+");
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 private long mLastLockMessageTime = 0L;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700221
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800222 // Things related to query logging/sampling for debugging
223 // slow/frequent queries during development. Always log queries
Brad Fitzpatrick722802e2010-03-23 22:22:16 -0700224 // which take (by default) 500ms+; shorter queries are sampled
225 // accordingly. Commit statements, which are typically slow, are
226 // logged together with the most recently executed SQL statement,
227 // for disambiguation. The 500ms value is configurable via a
228 // SystemProperty, but developers actively debugging database I/O
229 // should probably use the regular log tunable,
230 // LOG_SLOW_QUERIES_PROPERTY, defined below.
231 private static int sQueryLogTimeInMillis = 0; // lazily initialized
Dan Egnor12311952009-11-23 14:47:45 -0800232 private static final int QUERY_LOG_SQL_LENGTH = 64;
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800233 private static final String COMMIT_SQL = "COMMIT;";
Dan Egnor12311952009-11-23 14:47:45 -0800234 private final Random mRandom = new Random();
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800235 private String mLastSqlStatement = null;
Dan Egnor12311952009-11-23 14:47:45 -0800236
Brad Fitzpatrick722802e2010-03-23 22:22:16 -0700237 // String prefix for slow database query EventLog records that show
238 // lock acquistions of the database.
239 /* package */ static final String GET_LOCK_LOG_PREFIX = "GETLOCK:";
240
Vasu Nori6f37f832010-05-19 11:53:25 -0700241 /** Used by native code, do not rename. make it volatile, so it is thread-safe. */
242 /* package */ volatile int mNativeHandle = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Vasu Noria8c24902010-06-01 11:30:27 -0700244 /**
245 * The size, in bytes, of a block on "/data". This corresponds to the Unix
246 * statfs.f_bsize field. note that this field is lazily initialized.
247 */
248 private static int sBlockSize = 0;
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 /** The path for the database file */
Vasu Noriccd95442010-05-28 17:04:16 -0700251 private final String mPath;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Brad Fitzpatrickd8330232010-02-19 10:59:01 -0800253 /** The anonymized path for the database file for logging purposes */
254 private String mPathForLogs = null; // lazily populated
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 /** The flags passed to open/create */
Vasu Noriccd95442010-05-28 17:04:16 -0700257 private final int mFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
259 /** The optional factory to use when creating new Cursors */
Vasu Noriccd95442010-05-28 17:04:16 -0700260 private final CursorFactory mFactory;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700261
Vasu Nori21343692010-06-03 16:01:39 -0700262 private final WeakHashMap<SQLiteClosable, Object> mPrograms;
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700263
Vasu Nori5a03f362009-10-20 15:16:35 -0700264 /**
Vasu Nori20f549f2010-04-15 11:25:51 -0700265 * for each instance of this class, a LRU cache is maintained to store
Vasu Nori5a03f362009-10-20 15:16:35 -0700266 * the compiled query statement ids returned by sqlite database.
Vasu Noriccd95442010-05-28 17:04:16 -0700267 * key = SQL statement with "?" for bind args
Vasu Nori5a03f362009-10-20 15:16:35 -0700268 * value = {@link SQLiteCompiledSql}
269 * If an application opens the database and keeps it open during its entire life, then
Vasu Noriccd95442010-05-28 17:04:16 -0700270 * there will not be an overhead of compilation of SQL statements by sqlite.
Vasu Nori5a03f362009-10-20 15:16:35 -0700271 *
272 * why is this cache NOT static? because sqlite attaches compiledsql statements to the
273 * struct created when {@link SQLiteDatabase#openDatabase(String, CursorFactory, int)} is
274 * invoked.
275 *
276 * this cache has an upper limit of mMaxSqlCacheSize (settable by calling the method
Vasu Nori9504c702010-04-23 01:04:31 -0700277 * (@link setMaxSqlCacheSize(int)}).
Vasu Nori5a03f362009-10-20 15:16:35 -0700278 */
Vasu Nori20f549f2010-04-15 11:25:51 -0700279 // default statement-cache size per database connection ( = instance of this class)
280 private int mMaxSqlCacheSize = 25;
Vasu Nori21343692010-06-03 16:01:39 -0700281 /* package */ final Map<String, SQLiteCompiledSql> mCompiledQueries =
Vasu Nori20f549f2010-04-15 11:25:51 -0700282 new LinkedHashMap<String, SQLiteCompiledSql>(mMaxSqlCacheSize + 1, 0.75f, true) {
283 @Override
284 public boolean removeEldestEntry(Map.Entry<String, SQLiteCompiledSql> eldest) {
Vasu Nori9504c702010-04-23 01:04:31 -0700285 // eldest = least-recently used entry
286 // if it needs to be removed to accommodate a new entry,
287 // close {@link SQLiteCompiledSql} represented by this entry, if not in use
288 // and then let it be removed from the Map.
Vasu Nori9463f292010-04-30 12:22:18 -0700289 // when this is called, the caller must be trying to add a just-compiled stmt
290 // to cache; i.e., caller should already have acquired database lock AND
291 // the lock on mCompiledQueries. do as assert of these two 2 facts.
292 verifyLockOwner();
293 if (this.size() <= mMaxSqlCacheSize) {
294 // cache is not full. nothing needs to be removed
295 return false;
Vasu Nori9504c702010-04-23 01:04:31 -0700296 }
Vasu Nori9463f292010-04-30 12:22:18 -0700297 // cache is full. eldest will be removed.
298 SQLiteCompiledSql entry = eldest.getValue();
299 if (!entry.isInUse()) {
300 // this {@link SQLiteCompiledSql} is not in use. release it.
301 entry.releaseSqlStatement();
302 }
303 // return true, so that this entry is removed automatically by the caller.
304 return true;
Vasu Nori20f549f2010-04-15 11:25:51 -0700305 }
306 };
Vasu Norie495d1f2010-01-06 16:34:19 -0800307 /**
Vasu Nori20f549f2010-04-15 11:25:51 -0700308 * absolute max value that can be set by {@link #setMaxSqlCacheSize(int)}
Vasu Nori90a367262010-04-12 12:49:09 -0700309 * size of each prepared-statement is between 1K - 6K, depending on the complexity of the
Vasu Noriccd95442010-05-28 17:04:16 -0700310 * SQL statement & schema.
Vasu Norie495d1f2010-01-06 16:34:19 -0800311 */
Vasu Nori90a367262010-04-12 12:49:09 -0700312 public static final int MAX_SQL_CACHE_SIZE = 100;
Vasu Norie9d92102010-01-20 15:07:26 -0800313 private int mCacheFullWarnings;
Vasu Nori49d02ac2010-03-05 21:49:30 -0800314 private static final int MAX_WARNINGS_ON_CACHESIZE_CONDITION = 1;
Vasu Nori5a03f362009-10-20 15:16:35 -0700315
316 /** maintain stats about number of cache hits and misses */
317 private int mNumCacheHits;
318 private int mNumCacheMisses;
319
Vasu Norid606b4b2010-02-24 12:54:20 -0800320 /** Used to find out where this object was created in case it never got closed. */
Vasu Nori21343692010-06-03 16:01:39 -0700321 private final Throwable mStackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
Dmitri Plotnikov90142c92009-09-15 10:52:17 -0700323 // System property that enables logging of slow queries. Specify the threshold in ms.
324 private static final String LOG_SLOW_QUERIES_PROPERTY = "db.log.slow_query_threshold";
325 private final int mSlowQueryThreshold;
326
Vasu Nori6f37f832010-05-19 11:53:25 -0700327 /** stores the list of statement ids that need to be finalized by sqlite */
Vasu Nori21343692010-06-03 16:01:39 -0700328 private final ArrayList<Integer> mClosedStatementIds = new ArrayList<Integer>();
Vasu Nori6f37f832010-05-19 11:53:25 -0700329
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700330 /** {@link DatabaseErrorHandler} to be used when SQLite returns any of the following errors
331 * Corruption
332 * */
Vasu Nori21343692010-06-03 16:01:39 -0700333 private final DatabaseErrorHandler mErrorHandler;
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700334
Vasu Nori6c354da2010-04-26 23:33:39 -0700335 /** The Database connection pool {@link DatabaseConnectionPool}.
336 * Visibility is package-private for testing purposes. otherwise, private visibility is enough.
337 */
338 /* package */ volatile DatabaseConnectionPool mConnectionPool = null;
339
340 /** Each database connection handle in the pool is assigned a number 1..N, where N is the
341 * size of the connection pool.
342 * The main connection handle to which the pool is attached is assigned a value of 0.
343 */
344 /* package */ final short mConnectionNum;
345
Vasu Nori65a88832010-07-16 15:14:08 -0700346 /** on pooled database connections, this member points to the parent ( = main)
347 * database connection handle.
348 * package visibility only for testing purposes
349 */
350 /* package */ SQLiteDatabase mParentConnObj = null;
351
Vasu Noria98cb262010-06-22 13:16:35 -0700352 private static final String MEMORY_DB_PATH = ":memory:";
353
Vasu Nori2827d6d2010-07-04 00:26:18 -0700354 synchronized void addSQLiteClosable(SQLiteClosable closable) {
355 // mPrograms is per instance of SQLiteDatabase and it doesn't actually touch the database
356 // itself. so, there is no need to lock().
357 mPrograms.put(closable, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700359
Vasu Nori2827d6d2010-07-04 00:26:18 -0700360 synchronized void removeSQLiteClosable(SQLiteClosable closable) {
361 mPrograms.remove(closable);
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700362 }
363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 @Override
365 protected void onAllReferencesReleased() {
366 if (isOpen()) {
Vasu Noriad239ab2010-06-14 16:58:47 -0700367 // close the database which will close all pending statements to be finalized also
368 close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
370 }
371
372 /**
373 * Attempts to release memory that SQLite holds but does not require to
374 * operate properly. Typically this memory will come from the page cache.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700375 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 * @return the number of bytes actually released
377 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700378 static public native int releaseMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380 /**
381 * Control whether or not the SQLiteDatabase is made thread-safe by using locks
382 * around critical sections. This is pretty expensive, so if you know that your
383 * DB will only be used by a single thread then you should set this to false.
384 * The default is true.
385 * @param lockingEnabled set to true to enable locks, false otherwise
386 */
387 public void setLockingEnabled(boolean lockingEnabled) {
388 mLockingEnabled = lockingEnabled;
389 }
390
391 /**
392 * If set then the SQLiteDatabase is made thread-safe by using locks
393 * around critical sections
394 */
395 private boolean mLockingEnabled = true;
396
397 /* package */ void onCorruption() {
Vasu Norif3cf8a42010-03-23 11:41:44 -0700398 EventLog.writeEvent(EVENT_DB_CORRUPT, mPath);
Vasu Noriccd95442010-05-28 17:04:16 -0700399 mErrorHandler.onCorruption(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 }
401
402 /**
403 * Locks the database for exclusive access. The database lock must be held when
404 * touch the native sqlite3* object since it is single threaded and uses
405 * a polling lock contention algorithm. The lock is recursive, and may be acquired
406 * multiple times by the same thread. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700407 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 * @see #unlock()
409 */
410 /* package */ void lock() {
Vasu Nori7b04c412010-07-20 10:31:21 -0700411 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 if (!mLockingEnabled) return;
413 mLock.lock();
414 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
415 if (mLock.getHoldCount() == 1) {
416 // Use elapsed real-time since the CPU may sleep when waiting for IO
417 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
418 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
419 }
420 }
421 }
422
423 /**
424 * Locks the database for exclusive access. The database lock must be held when
425 * touch the native sqlite3* object since it is single threaded and uses
426 * a polling lock contention algorithm. The lock is recursive, and may be acquired
427 * multiple times by the same thread.
428 *
429 * @see #unlockForced()
430 */
431 private void lockForced() {
Vasu Nori7b04c412010-07-20 10:31:21 -0700432 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 mLock.lock();
434 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
435 if (mLock.getHoldCount() == 1) {
436 // Use elapsed real-time since the CPU may sleep when waiting for IO
437 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
438 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
439 }
440 }
441 }
442
443 /**
444 * Releases the database lock. This is a no-op if mLockingEnabled is false.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700445 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 * @see #unlock()
447 */
448 /* package */ void unlock() {
449 if (!mLockingEnabled) return;
450 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
451 if (mLock.getHoldCount() == 1) {
452 checkLockHoldTime();
453 }
454 }
455 mLock.unlock();
456 }
457
458 /**
459 * Releases the database lock.
460 *
461 * @see #unlockForced()
462 */
463 private void unlockForced() {
464 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
465 if (mLock.getHoldCount() == 1) {
466 checkLockHoldTime();
467 }
468 }
469 mLock.unlock();
470 }
471
472 private void checkLockHoldTime() {
473 // Use elapsed real-time since the CPU may sleep when waiting for IO
474 long elapsedTime = SystemClock.elapsedRealtime();
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700475 long lockedTime = elapsedTime - mLockAcquiredWallTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 if (lockedTime < LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT &&
477 !Log.isLoggable(TAG, Log.VERBOSE) &&
478 (elapsedTime - mLastLockMessageTime) < LOCK_WARNING_WINDOW_IN_MS) {
479 return;
480 }
481 if (lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS) {
482 int threadTime = (int)
483 ((Debug.threadCpuTimeNanos() - mLockAcquiredThreadTime) / 1000000);
484 if (threadTime > LOCK_ACQUIRED_WARNING_THREAD_TIME_IN_MS ||
485 lockedTime > LOCK_ACQUIRED_WARNING_TIME_IN_MS_ALWAYS_PRINT) {
486 mLastLockMessageTime = elapsedTime;
487 String msg = "lock held on " + mPath + " for " + lockedTime + "ms. Thread time was "
488 + threadTime + "ms";
489 if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING_STACK_TRACE) {
490 Log.d(TAG, msg, new Exception());
491 } else {
492 Log.d(TAG, msg);
493 }
494 }
495 }
496 }
497
498 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700499 * Begins a transaction in EXCLUSIVE mode.
500 * <p>
501 * Transactions can be nested.
502 * When the outer transaction is ended all of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * the work done in that transaction and all of the nested transactions will be committed or
504 * rolled back. The changes will be rolled back if any transaction is ended without being
505 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700506 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 * <p>Here is the standard idiom for transactions:
508 *
509 * <pre>
510 * db.beginTransaction();
511 * try {
512 * ...
513 * db.setTransactionSuccessful();
514 * } finally {
515 * db.endTransaction();
516 * }
517 * </pre>
518 */
519 public void beginTransaction() {
Vasu Nori6c354da2010-04-26 23:33:39 -0700520 beginTransaction(null /* transactionStatusCallback */, true);
521 }
522
523 /**
524 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
525 * the outer transaction is ended all of the work done in that transaction
526 * and all of the nested transactions will be committed or rolled back. The
527 * changes will be rolled back if any transaction is ended without being
528 * marked as clean (by calling setTransactionSuccessful). Otherwise they
529 * will be committed.
530 * <p>
531 * Here is the standard idiom for transactions:
532 *
533 * <pre>
534 * db.beginTransactionNonExclusive();
535 * try {
536 * ...
537 * db.setTransactionSuccessful();
538 * } finally {
539 * db.endTransaction();
540 * }
541 * </pre>
542 */
543 public void beginTransactionNonExclusive() {
544 beginTransaction(null /* transactionStatusCallback */, false);
Fred Quintanac4516a72009-09-03 12:14:06 -0700545 }
546
547 /**
Vasu Noriccd95442010-05-28 17:04:16 -0700548 * Begins a transaction in EXCLUSIVE mode.
549 * <p>
550 * Transactions can be nested.
551 * When the outer transaction is ended all of
Fred Quintanac4516a72009-09-03 12:14:06 -0700552 * the work done in that transaction and all of the nested transactions will be committed or
553 * rolled back. The changes will be rolled back if any transaction is ended without being
554 * marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Vasu Noriccd95442010-05-28 17:04:16 -0700555 * </p>
Fred Quintanac4516a72009-09-03 12:14:06 -0700556 * <p>Here is the standard idiom for transactions:
557 *
558 * <pre>
559 * db.beginTransactionWithListener(listener);
560 * try {
561 * ...
562 * db.setTransactionSuccessful();
563 * } finally {
564 * db.endTransaction();
565 * }
566 * </pre>
Vasu Noriccd95442010-05-28 17:04:16 -0700567 *
Fred Quintanac4516a72009-09-03 12:14:06 -0700568 * @param transactionListener listener that should be notified when the transaction begins,
569 * commits, or is rolled back, either explicitly or by a call to
570 * {@link #yieldIfContendedSafely}.
571 */
572 public void beginTransactionWithListener(SQLiteTransactionListener transactionListener) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700573 beginTransaction(transactionListener, true);
574 }
575
576 /**
577 * Begins a transaction in IMMEDIATE mode. Transactions can be nested. When
578 * the outer transaction is ended all of the work done in that transaction
579 * and all of the nested transactions will be committed or rolled back. The
580 * changes will be rolled back if any transaction is ended without being
581 * marked as clean (by calling setTransactionSuccessful). Otherwise they
582 * will be committed.
583 * <p>
584 * Here is the standard idiom for transactions:
585 *
586 * <pre>
587 * db.beginTransactionWithListenerNonExclusive(listener);
588 * try {
589 * ...
590 * db.setTransactionSuccessful();
591 * } finally {
592 * db.endTransaction();
593 * }
594 * </pre>
595 *
596 * @param transactionListener listener that should be notified when the
597 * transaction begins, commits, or is rolled back, either
598 * explicitly or by a call to {@link #yieldIfContendedSafely}.
599 */
600 public void beginTransactionWithListenerNonExclusive(
601 SQLiteTransactionListener transactionListener) {
602 beginTransaction(transactionListener, false);
603 }
604
605 private void beginTransaction(SQLiteTransactionListener transactionListener,
606 boolean exclusive) {
Vasu Noriccd95442010-05-28 17:04:16 -0700607 verifyDbIsOpen();
Vasu Noric8e1f232010-04-13 15:05:09 -0700608 lockForced();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 boolean ok = false;
610 try {
611 // If this thread already had the lock then get out
612 if (mLock.getHoldCount() > 1) {
613 if (mInnerTransactionIsSuccessful) {
614 String msg = "Cannot call beginTransaction between "
615 + "calling setTransactionSuccessful and endTransaction";
616 IllegalStateException e = new IllegalStateException(msg);
617 Log.e(TAG, "beginTransaction() failed", e);
618 throw e;
619 }
620 ok = true;
621 return;
622 }
623
624 // This thread didn't already have the lock, so begin a database
625 // transaction now.
Vasu Nori57feb5d2010-06-22 10:39:04 -0700626 if (exclusive && mConnectionPool == null) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700627 execSQL("BEGIN EXCLUSIVE;");
628 } else {
629 execSQL("BEGIN IMMEDIATE;");
630 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700631 mTransactionListener = transactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 mTransactionIsSuccessful = true;
633 mInnerTransactionIsSuccessful = false;
Fred Quintanac4516a72009-09-03 12:14:06 -0700634 if (transactionListener != null) {
635 try {
636 transactionListener.onBegin();
637 } catch (RuntimeException e) {
638 execSQL("ROLLBACK;");
639 throw e;
640 }
641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 ok = true;
643 } finally {
644 if (!ok) {
645 // beginTransaction is called before the try block so we must release the lock in
646 // the case of failure.
647 unlockForced();
648 }
649 }
650 }
651
652 /**
653 * End a transaction. See beginTransaction for notes about how to use this and when transactions
654 * are committed and rolled back.
655 */
656 public void endTransaction() {
Vasu Noriccd95442010-05-28 17:04:16 -0700657 verifyLockOwner();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 try {
659 if (mInnerTransactionIsSuccessful) {
660 mInnerTransactionIsSuccessful = false;
661 } else {
662 mTransactionIsSuccessful = false;
663 }
664 if (mLock.getHoldCount() != 1) {
665 return;
666 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700667 RuntimeException savedException = null;
668 if (mTransactionListener != null) {
669 try {
670 if (mTransactionIsSuccessful) {
671 mTransactionListener.onCommit();
672 } else {
673 mTransactionListener.onRollback();
674 }
675 } catch (RuntimeException e) {
676 savedException = e;
677 mTransactionIsSuccessful = false;
678 }
679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 if (mTransactionIsSuccessful) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -0800681 execSQL(COMMIT_SQL);
Vasu Nori6c354da2010-04-26 23:33:39 -0700682 // if write-ahead logging is used, we have to take care of checkpoint.
683 // TODO: should applications be given the flexibility of choosing when to
684 // trigger checkpoint?
685 // for now, do checkpoint after every COMMIT because that is the fastest
686 // way to guarantee that readers will see latest data.
687 // but this is the slowest way to run sqlite with in write-ahead logging mode.
688 if (this.mConnectionPool != null) {
689 execSQL("PRAGMA wal_checkpoint;");
690 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
691 Log.i(TAG, "PRAGMA wal_Checkpoint done");
692 }
693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 } else {
695 try {
696 execSQL("ROLLBACK;");
Fred Quintanac4516a72009-09-03 12:14:06 -0700697 if (savedException != null) {
698 throw savedException;
699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 } catch (SQLException e) {
701 if (Config.LOGD) {
702 Log.d(TAG, "exception during rollback, maybe the DB previously "
703 + "performed an auto-rollback");
704 }
705 }
706 }
707 } finally {
Fred Quintanac4516a72009-09-03 12:14:06 -0700708 mTransactionListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 unlockForced();
710 if (Config.LOGV) {
711 Log.v(TAG, "unlocked " + Thread.currentThread()
712 + ", holdCount is " + mLock.getHoldCount());
713 }
714 }
715 }
716
717 /**
718 * Marks the current transaction as successful. Do not do any more database work between
719 * calling this and calling endTransaction. Do as little non-database work as possible in that
720 * situation too. If any errors are encountered between this and endTransaction the transaction
721 * will still be committed.
722 *
723 * @throws IllegalStateException if the current thread is not in a transaction or the
724 * transaction is already marked as successful.
725 */
726 public void setTransactionSuccessful() {
Vasu Noriccd95442010-05-28 17:04:16 -0700727 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 if (!mLock.isHeldByCurrentThread()) {
729 throw new IllegalStateException("no transaction pending");
730 }
731 if (mInnerTransactionIsSuccessful) {
732 throw new IllegalStateException(
733 "setTransactionSuccessful may only be called once per call to beginTransaction");
734 }
735 mInnerTransactionIsSuccessful = true;
736 }
737
738 /**
739 * return true if there is a transaction pending
740 */
741 public boolean inTransaction() {
Vasu Norice38b982010-07-22 13:57:13 -0700742 return mLock.getHoldCount() > 0 || mTransactionUsingExecSql;
743 }
744
745 /* package */ synchronized void setTransactionUsingExecSqlFlag() {
746 if (Log.isLoggable(TAG, Log.DEBUG)) {
747 Log.i(TAG, "found execSQL('begin transaction')");
748 }
749 mTransactionUsingExecSql = true;
750 }
751
752 /* package */ synchronized void resetTransactionUsingExecSqlFlag() {
753 if (Log.isLoggable(TAG, Log.DEBUG)) {
754 if (mTransactionUsingExecSql) {
755 Log.i(TAG, "found execSQL('commit or end or rollback')");
756 }
757 }
758 mTransactionUsingExecSql = false;
759 }
760
761 /**
762 * Returns true if the caller is considered part of the current transaction, if any.
763 * <p>
764 * Caller is part of the current transaction if either of the following is true
765 * <ol>
766 * <li>If transaction is started by calling beginTransaction() methods AND if the caller is
767 * in the same thread as the thread that started the transaction.
768 * </li>
769 * <li>If the transaction is started by calling {@link #execSQL(String)} like this:
770 * execSQL("BEGIN transaction"). In this case, every thread in the process is considered
771 * part of the current transaction.</li>
772 * </ol>
773 *
774 * @return true if the caller is considered part of the current transaction, if any.
775 */
776 /* package */ synchronized boolean amIInTransaction() {
777 // always do this test on the main database connection - NOT on pooled database connection
778 // since transactions always occur on the main database connections only.
779 SQLiteDatabase db = (isPooledConnection()) ? mParentConnObj : this;
780 boolean b = (!db.inTransaction()) ? false :
781 db.mTransactionUsingExecSql || db.mLock.isHeldByCurrentThread();
782 if (Log.isLoggable(TAG, Log.DEBUG)) {
783 Log.i(TAG, "amIinTransaction: " + b);
784 }
785 return b;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787
788 /**
789 * Checks if the database lock is held by this thread.
790 *
791 * @return true, if this thread is holding the database lock.
792 */
793 public boolean isDbLockedByCurrentThread() {
794 return mLock.isHeldByCurrentThread();
795 }
796
797 /**
798 * Checks if the database is locked by another thread. This is
799 * just an estimate, since this status can change at any time,
800 * including after the call is made but before the result has
801 * been acted upon.
802 *
803 * @return true, if the database is locked by another thread
804 */
805 public boolean isDbLockedByOtherThreads() {
806 return !mLock.isHeldByCurrentThread() && mLock.isLocked();
807 }
808
809 /**
810 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
811 * successful so far. Do not call setTransactionSuccessful before calling this. When this
812 * returns a new transaction will have been created but not marked as successful.
813 * @return true if the transaction was yielded
814 * @deprecated if the db is locked more than once (becuase of nested transactions) then the lock
815 * will not be yielded. Use yieldIfContendedSafely instead.
816 */
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700817 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 public boolean yieldIfContended() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700819 return yieldIfContendedHelper(false /* do not check yielding */,
820 -1 /* sleepAfterYieldDelay */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822
823 /**
824 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
825 * successful so far. Do not call setTransactionSuccessful before calling this. When this
826 * returns a new transaction will have been created but not marked as successful. This assumes
827 * that there are no nested transactions (beginTransaction has only been called once) and will
Fred Quintana5c7aede2009-08-27 21:41:27 -0700828 * throw an exception if that is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 * @return true if the transaction was yielded
830 */
831 public boolean yieldIfContendedSafely() {
Fred Quintana5c7aede2009-08-27 21:41:27 -0700832 return yieldIfContendedHelper(true /* check yielding */, -1 /* sleepAfterYieldDelay*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834
Fred Quintana5c7aede2009-08-27 21:41:27 -0700835 /**
836 * Temporarily end the transaction to let other threads run. The transaction is assumed to be
837 * successful so far. Do not call setTransactionSuccessful before calling this. When this
838 * returns a new transaction will have been created but not marked as successful. This assumes
839 * that there are no nested transactions (beginTransaction has only been called once) and will
840 * throw an exception if that is not the case.
841 * @param sleepAfterYieldDelay if > 0, sleep this long before starting a new transaction if
842 * the lock was actually yielded. This will allow other background threads to make some
843 * more progress than they would if we started the transaction immediately.
844 * @return true if the transaction was yielded
845 */
846 public boolean yieldIfContendedSafely(long sleepAfterYieldDelay) {
847 return yieldIfContendedHelper(true /* check yielding */, sleepAfterYieldDelay);
848 }
849
850 private boolean yieldIfContendedHelper(boolean checkFullyYielded, long sleepAfterYieldDelay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 if (mLock.getQueueLength() == 0) {
852 // Reset the lock acquire time since we know that the thread was willing to yield
853 // the lock at this time.
854 mLockAcquiredWallTime = SystemClock.elapsedRealtime();
855 mLockAcquiredThreadTime = Debug.threadCpuTimeNanos();
856 return false;
857 }
858 setTransactionSuccessful();
Fred Quintanac4516a72009-09-03 12:14:06 -0700859 SQLiteTransactionListener transactionListener = mTransactionListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 endTransaction();
861 if (checkFullyYielded) {
862 if (this.isDbLockedByCurrentThread()) {
863 throw new IllegalStateException(
864 "Db locked more than once. yielfIfContended cannot yield");
865 }
866 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700867 if (sleepAfterYieldDelay > 0) {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -0700868 // Sleep for up to sleepAfterYieldDelay milliseconds, waking up periodically to
869 // check if anyone is using the database. If the database is not contended,
870 // retake the lock and return.
871 long remainingDelay = sleepAfterYieldDelay;
872 while (remainingDelay > 0) {
873 try {
874 Thread.sleep(remainingDelay < SLEEP_AFTER_YIELD_QUANTUM ?
875 remainingDelay : SLEEP_AFTER_YIELD_QUANTUM);
876 } catch (InterruptedException e) {
877 Thread.interrupted();
878 }
879 remainingDelay -= SLEEP_AFTER_YIELD_QUANTUM;
880 if (mLock.getQueueLength() == 0) {
881 break;
882 }
Fred Quintana5c7aede2009-08-27 21:41:27 -0700883 }
884 }
Fred Quintanac4516a72009-09-03 12:14:06 -0700885 beginTransactionWithListener(transactionListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 return true;
887 }
888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 /**
Vasu Nori95675132010-07-21 16:24:40 -0700890 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 */
Vasu Nori95675132010-07-21 16:24:40 -0700892 @Deprecated
893 public Map<String, String> getSyncedTables() {
894 return new HashMap<String, String>(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896
897 /**
898 * Used to allow returning sub-classes of {@link Cursor} when calling query.
899 */
900 public interface CursorFactory {
901 /**
902 * See
903 * {@link SQLiteCursor#SQLiteCursor(SQLiteDatabase, SQLiteCursorDriver,
904 * String, SQLiteQuery)}.
905 */
906 public Cursor newCursor(SQLiteDatabase db,
907 SQLiteCursorDriver masterQuery, String editTable,
908 SQLiteQuery query);
909 }
910
911 /**
912 * Open the database according to the flags {@link #OPEN_READWRITE}
913 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
914 *
915 * <p>Sets the locale of the database to the the system's current locale.
916 * Call {@link #setLocale} if you would like something else.</p>
917 *
918 * @param path to database file to open and/or create
919 * @param factory an optional factory class that is called to instantiate a
920 * cursor when query is called, or null for default
921 * @param flags to control database access mode
922 * @return the newly opened database
923 * @throws SQLiteException if the database cannot be opened
924 */
925 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags) {
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700926 return openDatabase(path, factory, flags, new DefaultDatabaseErrorHandler());
927 }
928
929 /**
Vasu Nori74f170f2010-06-01 18:06:18 -0700930 * Open the database according to the flags {@link #OPEN_READWRITE}
931 * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
932 *
933 * <p>Sets the locale of the database to the the system's current locale.
934 * Call {@link #setLocale} if you would like something else.</p>
935 *
936 * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
937 * used to handle corruption when sqlite reports database corruption.</p>
938 *
939 * @param path to database file to open and/or create
940 * @param factory an optional factory class that is called to instantiate a
941 * cursor when query is called, or null for default
942 * @param flags to control database access mode
943 * @param errorHandler the {@link DatabaseErrorHandler} obj to be used to handle corruption
944 * when sqlite reports database corruption
945 * @return the newly opened database
946 * @throws SQLiteException if the database cannot be opened
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700947 */
948 public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
949 DatabaseErrorHandler errorHandler) {
Vasu Nori6c354da2010-04-26 23:33:39 -0700950 SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler,
951 (short) 0 /* the main connection handle */);
Vasu Noria8c24902010-06-01 11:30:27 -0700952
953 // set sqlite pagesize to mBlockSize
954 if (sBlockSize == 0) {
955 // TODO: "/data" should be a static final String constant somewhere. it is hardcoded
956 // in several places right now.
957 sBlockSize = new StatFs("/data").getBlockSize();
958 }
959 sqliteDatabase.setPageSize(sBlockSize);
Vasu Nori57feb5d2010-06-22 10:39:04 -0700960 //STOPSHIP - uncomment the following line
961 //sqliteDatabase.setJournalMode(path, "TRUNCATE");
962 // STOPSHIP remove the following lines
Vasu Nori7b04c412010-07-20 10:31:21 -0700963 if (!path.equalsIgnoreCase(MEMORY_DB_PATH)) {
964 sqliteDatabase.enableWriteAheadLogging();
965 }
966 // END STOPSHIP
Vasu Norif9e2bd02010-06-04 16:49:51 -0700967
Vasu Noriccd95442010-05-28 17:04:16 -0700968 // add this database to the list of databases opened in this process
969 ActiveDatabases.addActiveDatabase(sqliteDatabase);
Vasu Noric3849202010-03-09 10:47:25 -0800970 return sqliteDatabase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
972
Vasu Nori6c354da2010-04-26 23:33:39 -0700973 private static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
974 DatabaseErrorHandler errorHandler, short connectionNum) {
975 SQLiteDatabase db = new SQLiteDatabase(path, factory, flags, errorHandler, connectionNum);
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700976 try {
Vasu Norice38b982010-07-22 13:57:13 -0700977 if (Log.isLoggable(TAG, Log.DEBUG)) {
978 Log.i(TAG, "opening the db : " + path);
979 }
Vasu Nori6c354da2010-04-26 23:33:39 -0700980 // Open the database.
981 db.dbopen(path, flags);
982 db.setLocale(Locale.getDefault());
983 if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
984 db.enableSqlTracing(path, connectionNum);
985 }
986 if (SQLiteDebug.DEBUG_SQL_TIME) {
987 db.enableSqlProfiling(path, connectionNum);
988 }
989 return db;
990 } catch (SQLiteDatabaseCorruptException e) {
991 db.mErrorHandler.onCorruption(db);
992 return SQLiteDatabase.openDatabase(path, factory, flags, errorHandler);
993 } catch (SQLiteException e) {
994 Log.e(TAG, "Failed to open the database. closing it.", e);
995 db.close();
Vasu Nori062fc7ce2010-03-31 16:13:05 -0700996 throw e;
997 }
998 }
999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 /**
1001 * Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
1002 */
1003 public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) {
1004 return openOrCreateDatabase(file.getPath(), factory);
1005 }
1006
1007 /**
1008 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
1009 */
1010 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory) {
1011 return openDatabase(path, factory, CREATE_IF_NECESSARY);
1012 }
1013
1014 /**
Vasu Nori6c354da2010-04-26 23:33:39 -07001015 * Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001016 */
1017 public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory,
1018 DatabaseErrorHandler errorHandler) {
1019 return openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler);
1020 }
1021
Vasu Noria98cb262010-06-22 13:16:35 -07001022 private void setJournalMode(final String dbPath, final String mode) {
1023 // journal mode can be set only for non-memory databases
1024 if (!dbPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
1025 String s = DatabaseUtils.stringForQuery(this, "PRAGMA journal_mode=" + mode, null);
1026 if (!s.equalsIgnoreCase(mode)) {
1027 Log.e(TAG, "setting journal_mode to " + mode + " failed for db: " + dbPath +
1028 " (on pragma set journal_mode, sqlite returned:" + s);
1029 }
1030 }
1031 }
1032
Vasu Nori062fc7ce2010-03-31 16:13:05 -07001033 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 * Create a memory backed SQLite database. Its contents will be destroyed
1035 * when the database is closed.
1036 *
1037 * <p>Sets the locale of the database to the the system's current locale.
1038 * Call {@link #setLocale} if you would like something else.</p>
1039 *
1040 * @param factory an optional factory class that is called to instantiate a
1041 * cursor when query is called
1042 * @return a SQLiteDatabase object, or null if the database can't be created
1043 */
1044 public static SQLiteDatabase create(CursorFactory factory) {
1045 // This is a magic string with special meaning for SQLite.
Vasu Noria98cb262010-06-22 13:16:35 -07001046 return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
1049 /**
1050 * Close the database.
1051 */
1052 public void close() {
Vasu Norif3cf8a42010-03-23 11:41:44 -07001053 if (!isOpen()) {
1054 return; // already closed
1055 }
Vasu Norice38b982010-07-22 13:57:13 -07001056 if (Log.isLoggable(TAG, Log.DEBUG)) {
Vasu Nori75010102010-07-01 16:23:06 -07001057 Log.i(TAG, "closing db: " + mPath + " (connection # " + mConnectionNum);
1058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 lock();
1060 try {
1061 closeClosable();
Vasu Norifea6f6d2010-05-21 15:36:06 -07001062 // finalize ALL statements queued up so far
1063 closePendingStatements();
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001064 releaseCustomFunctions();
Vasu Norif6373e92010-03-16 10:21:00 -07001065 // close this database instance - regardless of its reference count value
Vasu Noriad239ab2010-06-14 16:58:47 -07001066 dbclose();
Vasu Nori6c354da2010-04-26 23:33:39 -07001067 if (mConnectionPool != null) {
Vasu Norice38b982010-07-22 13:57:13 -07001068 if (Log.isLoggable(TAG, Log.DEBUG)) {
1069 assert mConnectionPool != null;
1070 Log.i(TAG, mConnectionPool.toString());
1071 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001072 mConnectionPool.close();
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } finally {
1075 unlock();
1076 }
1077 }
1078
1079 private void closeClosable() {
Vasu Noriccd95442010-05-28 17:04:16 -07001080 /* deallocate all compiled SQL statement objects from mCompiledQueries cache.
Vasu Norie495d1f2010-01-06 16:34:19 -08001081 * this should be done before de-referencing all {@link SQLiteClosable} objects
1082 * from this database object because calling
1083 * {@link SQLiteClosable#onAllReferencesReleasedFromContainer()} could cause the database
1084 * to be closed. sqlite doesn't let a database close if there are
1085 * any unfinalized statements - such as the compiled-sql objects in mCompiledQueries.
1086 */
1087 deallocCachedSqlStatements();
1088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 Iterator<Map.Entry<SQLiteClosable, Object>> iter = mPrograms.entrySet().iterator();
1090 while (iter.hasNext()) {
1091 Map.Entry<SQLiteClosable, Object> entry = iter.next();
1092 SQLiteClosable program = entry.getKey();
1093 if (program != null) {
1094 program.onAllReferencesReleasedFromContainer();
1095 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 /**
1100 * Native call to close the database.
1101 */
1102 private native void dbclose();
1103
1104 /**
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001105 * A callback interface for a custom sqlite3 function.
1106 * This can be used to create a function that can be called from
1107 * sqlite3 database triggers.
1108 * @hide
1109 */
1110 public interface CustomFunction {
1111 public void callback(String[] args);
1112 }
1113
1114 /**
1115 * Registers a CustomFunction callback as a function that can be called from
1116 * sqlite3 database triggers.
1117 * @param name the name of the sqlite3 function
1118 * @param numArgs the number of arguments for the function
1119 * @param function callback to call when the function is executed
1120 * @hide
1121 */
1122 public void addCustomFunction(String name, int numArgs, CustomFunction function) {
1123 verifyDbIsOpen();
1124 synchronized (mCustomFunctions) {
1125 int ref = native_addCustomFunction(name, numArgs, function);
1126 if (ref != 0) {
1127 // save a reference to the function for cleanup later
1128 mCustomFunctions.add(new Integer(ref));
1129 } else {
1130 throw new SQLiteException("failed to add custom function " + name);
1131 }
1132 }
1133 }
1134
1135 private void releaseCustomFunctions() {
1136 synchronized (mCustomFunctions) {
1137 for (int i = 0; i < mCustomFunctions.size(); i++) {
1138 Integer function = mCustomFunctions.get(i);
1139 native_releaseCustomFunction(function.intValue());
1140 }
1141 mCustomFunctions.clear();
1142 }
1143 }
1144
1145 // list of CustomFunction references so we can clean up when the database closes
1146 private final ArrayList<Integer> mCustomFunctions =
1147 new ArrayList<Integer>();
1148
1149 private native int native_addCustomFunction(String name, int numArgs, CustomFunction function);
1150 private native void native_releaseCustomFunction(int function);
1151
1152 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 * Gets the database version.
1154 *
1155 * @return the database version
1156 */
1157 public int getVersion() {
Vasu Noriccd95442010-05-28 17:04:16 -07001158 return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160
1161 /**
1162 * Sets the database version.
1163 *
1164 * @param version the new database version
1165 */
1166 public void setVersion(int version) {
1167 execSQL("PRAGMA user_version = " + version);
1168 }
1169
1170 /**
1171 * Returns the maximum size the database may grow to.
1172 *
1173 * @return the new maximum database size
1174 */
1175 public long getMaximumSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001176 long pageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count;", null);
1177 return pageCount * getPageSize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
1179
1180 /**
1181 * Sets the maximum size the database will grow to. The maximum size cannot
1182 * be set below the current size.
1183 *
1184 * @param numBytes the maximum database size, in bytes
1185 * @return the new maximum database size
1186 */
1187 public long setMaximumSize(long numBytes) {
Vasu Noriccd95442010-05-28 17:04:16 -07001188 long pageSize = getPageSize();
1189 long numPages = numBytes / pageSize;
1190 // If numBytes isn't a multiple of pageSize, bump up a page
1191 if ((numBytes % pageSize) != 0) {
1192 numPages++;
Vasu Norif3cf8a42010-03-23 11:41:44 -07001193 }
Vasu Noriccd95442010-05-28 17:04:16 -07001194 long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
1195 null);
1196 return newPageCount * pageSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198
1199 /**
1200 * Returns the current database page size, in bytes.
1201 *
1202 * @return the database page size, in bytes
1203 */
1204 public long getPageSize() {
Vasu Noriccd95442010-05-28 17:04:16 -07001205 return DatabaseUtils.longForQuery(this, "PRAGMA page_size;", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207
1208 /**
1209 * Sets the database page size. The page size must be a power of two. This
1210 * method does not work if any data has been written to the database file,
1211 * and must be called right after the database has been created.
1212 *
1213 * @param numBytes the database page size, in bytes
1214 */
1215 public void setPageSize(long numBytes) {
1216 execSQL("PRAGMA page_size = " + numBytes);
1217 }
1218
1219 /**
1220 * Mark this table as syncable. When an update occurs in this table the
1221 * _sync_dirty field will be set to ensure proper syncing operation.
1222 *
1223 * @param table the table to mark as syncable
1224 * @param deletedTable The deleted table that corresponds to the
1225 * syncable table
Vasu Nori95675132010-07-21 16:24:40 -07001226 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 */
Vasu Nori95675132010-07-21 16:24:40 -07001228 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 public void markTableSyncable(String table, String deletedTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
1231
1232 /**
1233 * Mark this table as syncable, with the _sync_dirty residing in another
1234 * table. When an update occurs in this table the _sync_dirty field of the
1235 * row in updateTable with the _id in foreignKey will be set to
1236 * ensure proper syncing operation.
1237 *
1238 * @param table an update on this table will trigger a sync time removal
1239 * @param foreignKey this is the column in table whose value is an _id in
1240 * updateTable
1241 * @param updateTable this is the table that will have its _sync_dirty
Vasu Nori95675132010-07-21 16:24:40 -07001242 * @deprecated This method no longer serves any useful purpose and has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 */
Vasu Nori95675132010-07-21 16:24:40 -07001244 @Deprecated
1245 public void markTableSyncable(String table, String foreignKey, String updateTable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247
1248 /**
1249 * Finds the name of the first table, which is editable.
1250 *
1251 * @param tables a list of tables
1252 * @return the first table listed
1253 */
1254 public static String findEditTable(String tables) {
1255 if (!TextUtils.isEmpty(tables)) {
1256 // find the first word terminated by either a space or a comma
1257 int spacepos = tables.indexOf(' ');
1258 int commapos = tables.indexOf(',');
1259
1260 if (spacepos > 0 && (spacepos < commapos || commapos < 0)) {
1261 return tables.substring(0, spacepos);
1262 } else if (commapos > 0 && (commapos < spacepos || spacepos < 0) ) {
1263 return tables.substring(0, commapos);
1264 }
1265 return tables;
1266 } else {
1267 throw new IllegalStateException("Invalid tables");
1268 }
1269 }
1270
1271 /**
1272 * Compiles an SQL statement into a reusable pre-compiled statement object.
1273 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
1274 * statement and fill in those values with {@link SQLiteProgram#bindString}
1275 * and {@link SQLiteProgram#bindLong} each time you want to run the
1276 * statement. Statements may not return result sets larger than 1x1.
Vasu Nori2827d6d2010-07-04 00:26:18 -07001277 *<p>
1278 * No two threads should be using the same {@link SQLiteStatement} at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 *
1280 * @param sql The raw SQL statement, may contain ? for unknown values to be
1281 * bound later.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001282 * @return A pre-compiled {@link SQLiteStatement} object. Note that
1283 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 */
1285 public SQLiteStatement compileStatement(String sql) throws SQLException {
Vasu Noriccd95442010-05-28 17:04:16 -07001286 verifyDbIsOpen();
Vasu Nori2827d6d2010-07-04 00:26:18 -07001287 return new SQLiteStatement(this, sql);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289
1290 /**
1291 * Query the given URL, returning a {@link Cursor} over the result set.
1292 *
1293 * @param distinct true if you want each row to be unique, false otherwise.
1294 * @param table The table name to compile the query against.
1295 * @param columns A list of which columns to return. Passing null will
1296 * return all columns, which is discouraged to prevent reading
1297 * data from storage that isn't going to be used.
1298 * @param selection A filter declaring which rows to return, formatted as an
1299 * SQL WHERE clause (excluding the WHERE itself). Passing null
1300 * will return all rows for the given table.
1301 * @param selectionArgs You may include ?s in selection, which will be
1302 * replaced by the values from selectionArgs, in order that they
1303 * appear in the selection. The values will be bound as Strings.
1304 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1305 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1306 * will cause the rows to not be grouped.
1307 * @param having A filter declare which row groups to include in the cursor,
1308 * if row grouping is being used, formatted as an SQL HAVING
1309 * clause (excluding the HAVING itself). Passing null will cause
1310 * all row groups to be included, and is required when row
1311 * grouping is not being used.
1312 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1313 * (excluding the ORDER BY itself). Passing null will use the
1314 * default sort order, which may be unordered.
1315 * @param limit Limits the number of rows returned by the query,
1316 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001317 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1318 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 * @see Cursor
1320 */
1321 public Cursor query(boolean distinct, String table, String[] columns,
1322 String selection, String[] selectionArgs, String groupBy,
1323 String having, String orderBy, String limit) {
1324 return queryWithFactory(null, distinct, table, columns, selection, selectionArgs,
1325 groupBy, having, orderBy, limit);
1326 }
1327
1328 /**
1329 * Query the given URL, returning a {@link Cursor} over the result set.
1330 *
1331 * @param cursorFactory the cursor factory to use, or null for the default factory
1332 * @param distinct true if you want each row to be unique, false otherwise.
1333 * @param table The table name to compile the query against.
1334 * @param columns A list of which columns to return. Passing null will
1335 * return all columns, which is discouraged to prevent reading
1336 * data from storage that isn't going to be used.
1337 * @param selection A filter declaring which rows to return, formatted as an
1338 * SQL WHERE clause (excluding the WHERE itself). Passing null
1339 * will return all rows for the given table.
1340 * @param selectionArgs You may include ?s in selection, which will be
1341 * replaced by the values from selectionArgs, in order that they
1342 * appear in the selection. The values will be bound as Strings.
1343 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1344 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1345 * will cause the rows to not be grouped.
1346 * @param having A filter declare which row groups to include in the cursor,
1347 * if row grouping is being used, formatted as an SQL HAVING
1348 * clause (excluding the HAVING itself). Passing null will cause
1349 * all row groups to be included, and is required when row
1350 * grouping is not being used.
1351 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1352 * (excluding the ORDER BY itself). Passing null will use the
1353 * default sort order, which may be unordered.
1354 * @param limit Limits the number of rows returned by the query,
1355 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001356 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1357 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 * @see Cursor
1359 */
1360 public Cursor queryWithFactory(CursorFactory cursorFactory,
1361 boolean distinct, String table, String[] columns,
1362 String selection, String[] selectionArgs, String groupBy,
1363 String having, String orderBy, String limit) {
Vasu Noriccd95442010-05-28 17:04:16 -07001364 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 String sql = SQLiteQueryBuilder.buildQueryString(
1366 distinct, table, columns, selection, groupBy, having, orderBy, limit);
1367
1368 return rawQueryWithFactory(
1369 cursorFactory, sql, selectionArgs, findEditTable(table));
1370 }
1371
1372 /**
1373 * Query the given table, returning a {@link Cursor} over the result set.
1374 *
1375 * @param table The table name to compile the query against.
1376 * @param columns A list of which columns to return. Passing null will
1377 * return all columns, which is discouraged to prevent reading
1378 * data from storage that isn't going to be used.
1379 * @param selection A filter declaring which rows to return, formatted as an
1380 * SQL WHERE clause (excluding the WHERE itself). Passing null
1381 * will return all rows for the given table.
1382 * @param selectionArgs You may include ?s in selection, which will be
1383 * replaced by the values from selectionArgs, in order that they
1384 * appear in the selection. The values will be bound as Strings.
1385 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1386 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1387 * will cause the rows to not be grouped.
1388 * @param having A filter declare which row groups to include in the cursor,
1389 * if row grouping is being used, formatted as an SQL HAVING
1390 * clause (excluding the HAVING itself). Passing null will cause
1391 * all row groups to be included, and is required when row
1392 * grouping is not being used.
1393 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1394 * (excluding the ORDER BY itself). Passing null will use the
1395 * default sort order, which may be unordered.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001396 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1397 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 * @see Cursor
1399 */
1400 public Cursor query(String table, String[] columns, String selection,
1401 String[] selectionArgs, String groupBy, String having,
1402 String orderBy) {
1403
1404 return query(false, table, columns, selection, selectionArgs, groupBy,
1405 having, orderBy, null /* limit */);
1406 }
1407
1408 /**
1409 * Query the given table, returning a {@link Cursor} over the result set.
1410 *
1411 * @param table The table name to compile the query against.
1412 * @param columns A list of which columns to return. Passing null will
1413 * return all columns, which is discouraged to prevent reading
1414 * data from storage that isn't going to be used.
1415 * @param selection A filter declaring which rows to return, formatted as an
1416 * SQL WHERE clause (excluding the WHERE itself). Passing null
1417 * will return all rows for the given table.
1418 * @param selectionArgs You may include ?s in selection, which will be
1419 * replaced by the values from selectionArgs, in order that they
1420 * appear in the selection. The values will be bound as Strings.
1421 * @param groupBy A filter declaring how to group rows, formatted as an SQL
1422 * GROUP BY clause (excluding the GROUP BY itself). Passing null
1423 * will cause the rows to not be grouped.
1424 * @param having A filter declare which row groups to include in the cursor,
1425 * if row grouping is being used, formatted as an SQL HAVING
1426 * clause (excluding the HAVING itself). Passing null will cause
1427 * all row groups to be included, and is required when row
1428 * grouping is not being used.
1429 * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
1430 * (excluding the ORDER BY itself). Passing null will use the
1431 * default sort order, which may be unordered.
1432 * @param limit Limits the number of rows returned by the query,
1433 * formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001434 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1435 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 * @see Cursor
1437 */
1438 public Cursor query(String table, String[] columns, String selection,
1439 String[] selectionArgs, String groupBy, String having,
1440 String orderBy, String limit) {
1441
1442 return query(false, table, columns, selection, selectionArgs, groupBy,
1443 having, orderBy, limit);
1444 }
1445
1446 /**
1447 * Runs the provided SQL and returns a {@link Cursor} over the result set.
1448 *
1449 * @param sql the SQL query. The SQL string must not be ; terminated
1450 * @param selectionArgs You may include ?s in where clause in the query,
1451 * which will be replaced by the values from selectionArgs. The
1452 * values will be bound as Strings.
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001453 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1454 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 */
1456 public Cursor rawQuery(String sql, String[] selectionArgs) {
1457 return rawQueryWithFactory(null, sql, selectionArgs, null);
1458 }
1459
1460 /**
1461 * Runs the provided SQL and returns a cursor over the result set.
1462 *
1463 * @param cursorFactory the cursor factory to use, or null for the default factory
1464 * @param sql the SQL query. The SQL string must not be ; terminated
1465 * @param selectionArgs You may include ?s in where clause in the query,
1466 * which will be replaced by the values from selectionArgs. The
1467 * values will be bound as Strings.
1468 * @param editTable the name of the first table, which is editable
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001469 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1470 * {@link Cursor}s are not synchronized, see the documentation for more details.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 */
1472 public Cursor rawQueryWithFactory(
1473 CursorFactory cursorFactory, String sql, String[] selectionArgs,
1474 String editTable) {
Vasu Noriccd95442010-05-28 17:04:16 -07001475 verifyDbIsOpen();
Brad Fitzpatrickcfda9f32010-06-03 12:52:54 -07001476 BlockGuard.getThreadPolicy().onReadFromDisk();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 long timeStart = 0;
1478
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001479 if (Config.LOGV || mSlowQueryThreshold != -1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 timeStart = System.currentTimeMillis();
1481 }
1482
Vasu Nori6c354da2010-04-26 23:33:39 -07001483 SQLiteDatabase db = getDbConnection(sql);
1484 SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(db, sql, editTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001486 Cursor cursor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 try {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001488 cursor = driver.query(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 cursorFactory != null ? cursorFactory : mFactory,
1490 selectionArgs);
1491 } finally {
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001492 if (Config.LOGV || mSlowQueryThreshold != -1) {
1493
Vasu Nori020e5342010-04-28 14:22:38 -07001494 // Force query execution
1495 int count = -1;
1496 if (cursor != null) {
1497 count = cursor.getCount();
1498 }
1499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 long duration = System.currentTimeMillis() - timeStart;
1501
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001502 if (Config.LOGV || duration >= mSlowQueryThreshold) {
1503 Log.v(SQLiteCursor.TAG,
1504 "query (" + duration + " ms): " + driver.toString() + ", args are "
1505 + (selectionArgs != null
1506 ? TextUtils.join(",", selectionArgs)
Vasu Nori020e5342010-04-28 14:22:38 -07001507 : "<null>") + ", count is " + count);
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
Vasu Nori6c354da2010-04-26 23:33:39 -07001510 releaseDbConnection(db);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001512 return cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
1515 /**
1516 * Runs the provided SQL and returns a cursor over the result set.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001517 * The cursor will read an initial set of rows and the return to the caller.
1518 * It will continue to read in batches and send data changed notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 * when the later batches are ready.
1520 * @param sql the SQL query. The SQL string must not be ; terminated
1521 * @param selectionArgs You may include ?s in where clause in the query,
1522 * which will be replaced by the values from selectionArgs. The
1523 * values will be bound as Strings.
1524 * @param initialRead set the initial count of items to read from the cursor
1525 * @param maxRead set the count of items to read on each iteration after the first
Jeff Hamiltonf3ca9a52010-05-12 15:04:33 -07001526 * @return A {@link Cursor} object, which is positioned before the first entry. Note that
1527 * {@link Cursor}s are not synchronized, see the documentation for more details.
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001528 *
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001529 * This work is incomplete and not fully tested or reviewed, so currently
1530 * hidden.
1531 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001533 public Cursor rawQuery(String sql, String[] selectionArgs,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 int initialRead, int maxRead) {
1535 SQLiteCursor c = (SQLiteCursor)rawQueryWithFactory(
1536 null, sql, selectionArgs, null);
1537 c.setLoadStyle(initialRead, maxRead);
1538 return c;
1539 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 /**
1542 * Convenience method for inserting a row into the database.
1543 *
1544 * @param table the table to insert the row into
1545 * @param nullColumnHack SQL doesn't allow inserting a completely empty row,
1546 * so if initialValues is empty this column will explicitly be
1547 * assigned a NULL value
1548 * @param values this map contains the initial column values for the
1549 * row. The keys should be the column names and the values the
1550 * column values
1551 * @return the row ID of the newly inserted row, or -1 if an error occurred
1552 */
1553 public long insert(String table, String nullColumnHack, ContentValues values) {
1554 try {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001555 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 } catch (SQLException e) {
1557 Log.e(TAG, "Error inserting " + values, e);
1558 return -1;
1559 }
1560 }
1561
1562 /**
1563 * Convenience method for inserting a row into the database.
1564 *
1565 * @param table the table to insert the row into
1566 * @param nullColumnHack SQL doesn't allow inserting a completely empty row,
1567 * so if initialValues is empty this column will explicitly be
1568 * assigned a NULL value
1569 * @param values this map contains the initial column values for the
1570 * row. The keys should be the column names and the values the
1571 * column values
1572 * @throws SQLException
1573 * @return the row ID of the newly inserted row, or -1 if an error occurred
1574 */
1575 public long insertOrThrow(String table, String nullColumnHack, ContentValues values)
1576 throws SQLException {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001577 return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
1580 /**
1581 * Convenience method for replacing a row in the database.
1582 *
1583 * @param table the table in which to replace the row
1584 * @param nullColumnHack SQL doesn't allow inserting a completely empty row,
1585 * so if initialValues is empty this row will explicitly be
1586 * assigned a NULL value
1587 * @param initialValues this map contains the initial column values for
1588 * the row. The key
1589 * @return the row ID of the newly inserted row, or -1 if an error occurred
1590 */
1591 public long replace(String table, String nullColumnHack, ContentValues initialValues) {
1592 try {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001593 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001594 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 } catch (SQLException e) {
1596 Log.e(TAG, "Error inserting " + initialValues, e);
1597 return -1;
1598 }
1599 }
1600
1601 /**
1602 * Convenience method for replacing a row in the database.
1603 *
1604 * @param table the table in which to replace the row
1605 * @param nullColumnHack SQL doesn't allow inserting a completely empty row,
1606 * so if initialValues is empty this row will explicitly be
1607 * assigned a NULL value
1608 * @param initialValues this map contains the initial column values for
1609 * the row. The key
1610 * @throws SQLException
1611 * @return the row ID of the newly inserted row, or -1 if an error occurred
1612 */
1613 public long replaceOrThrow(String table, String nullColumnHack,
1614 ContentValues initialValues) throws SQLException {
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001615 return insertWithOnConflict(table, nullColumnHack, initialValues,
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001616 CONFLICT_REPLACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
1619 /**
1620 * General method for inserting a row into the database.
1621 *
1622 * @param table the table to insert the row into
1623 * @param nullColumnHack SQL doesn't allow inserting a completely empty row,
1624 * so if initialValues is empty this column will explicitly be
1625 * assigned a NULL value
1626 * @param initialValues this map contains the initial column values for the
1627 * row. The keys should be the column names and the values the
1628 * column values
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001629 * @param conflictAlgorithm for insert conflict resolver
Vasu Nori6eb7c452010-01-27 14:31:24 -08001630 * @return the row ID of the newly inserted row
1631 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001632 * {@link #CONFLICT_IGNORE}
Vasu Nori6eb7c452010-01-27 14:31:24 -08001633 * OR -1 if any error
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 */
1635 public long insertWithOnConflict(String table, String nullColumnHack,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001636 ContentValues initialValues, int conflictAlgorithm) {
Vasu Noriccd95442010-05-28 17:04:16 -07001637 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638
1639 // Measurements show most sql lengths <= 152
1640 StringBuilder sql = new StringBuilder(152);
1641 sql.append("INSERT");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001642 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 sql.append(" INTO ");
1644 sql.append(table);
1645 // Measurements show most values lengths < 40
1646 StringBuilder values = new StringBuilder(40);
1647
1648 Set<Map.Entry<String, Object>> entrySet = null;
1649 if (initialValues != null && initialValues.size() > 0) {
1650 entrySet = initialValues.valueSet();
1651 Iterator<Map.Entry<String, Object>> entriesIter = entrySet.iterator();
1652 sql.append('(');
1653
1654 boolean needSeparator = false;
1655 while (entriesIter.hasNext()) {
1656 if (needSeparator) {
1657 sql.append(", ");
1658 values.append(", ");
1659 }
1660 needSeparator = true;
1661 Map.Entry<String, Object> entry = entriesIter.next();
1662 sql.append(entry.getKey());
1663 values.append('?');
1664 }
1665
1666 sql.append(')');
1667 } else {
1668 sql.append("(" + nullColumnHack + ") ");
1669 values.append("NULL");
1670 }
1671
1672 sql.append(" VALUES(");
1673 sql.append(values);
1674 sql.append(");");
1675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 SQLiteStatement statement = null;
1677 try {
1678 statement = compileStatement(sql.toString());
1679
1680 // Bind the values
1681 if (entrySet != null) {
1682 int size = entrySet.size();
1683 Iterator<Map.Entry<String, Object>> entriesIter = entrySet.iterator();
1684 for (int i = 0; i < size; i++) {
1685 Map.Entry<String, Object> entry = entriesIter.next();
1686 DatabaseUtils.bindObjectToProgram(statement, i + 1, entry.getValue());
1687 }
1688 }
1689
1690 // Run the program and then cleanup
Vasu Norifb16cbd2010-07-25 16:38:48 -07001691 return statement.executeInsert();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 } catch (SQLiteDatabaseCorruptException e) {
1693 onCorruption();
1694 throw e;
1695 } finally {
1696 if (statement != null) {
1697 statement.close();
1698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700 }
1701
1702 /**
1703 * Convenience method for deleting rows in the database.
1704 *
1705 * @param table the table to delete from
1706 * @param whereClause the optional WHERE clause to apply when deleting.
1707 * Passing null will delete all rows.
1708 * @return the number of rows affected if a whereClause is passed in, 0
1709 * otherwise. To remove all rows and get a count pass "1" as the
1710 * whereClause.
1711 */
1712 public int delete(String table, String whereClause, String[] whereArgs) {
Vasu Noriccd95442010-05-28 17:04:16 -07001713 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 SQLiteStatement statement = null;
1715 try {
1716 statement = compileStatement("DELETE FROM " + table
1717 + (!TextUtils.isEmpty(whereClause)
1718 ? " WHERE " + whereClause : ""));
1719 if (whereArgs != null) {
1720 int numArgs = whereArgs.length;
1721 for (int i = 0; i < numArgs; i++) {
1722 DatabaseUtils.bindObjectToProgram(statement, i + 1, whereArgs[i]);
1723 }
1724 }
Vasu Norifb16cbd2010-07-25 16:38:48 -07001725 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 } catch (SQLiteDatabaseCorruptException e) {
1727 onCorruption();
1728 throw e;
1729 } finally {
1730 if (statement != null) {
1731 statement.close();
1732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734 }
1735
1736 /**
1737 * Convenience method for updating rows in the database.
1738 *
1739 * @param table the table to update in
1740 * @param values a map from column names to new column values. null is a
1741 * valid value that will be translated to NULL.
1742 * @param whereClause the optional WHERE clause to apply when updating.
1743 * Passing null will update all rows.
1744 * @return the number of rows affected
1745 */
1746 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001747 return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 /**
1751 * Convenience method for updating rows in the database.
1752 *
1753 * @param table the table to update in
1754 * @param values a map from column names to new column values. null is a
1755 * valid value that will be translated to NULL.
1756 * @param whereClause the optional WHERE clause to apply when updating.
1757 * Passing null will update all rows.
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001758 * @param conflictAlgorithm for update conflict resolver
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 * @return the number of rows affected
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 */
Dmitri Plotnikov600bdd82009-09-01 12:12:20 -07001761 public int updateWithOnConflict(String table, ContentValues values,
Vasu Nori6eb7c452010-01-27 14:31:24 -08001762 String whereClause, String[] whereArgs, int conflictAlgorithm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 if (values == null || values.size() == 0) {
1764 throw new IllegalArgumentException("Empty values");
1765 }
1766
1767 StringBuilder sql = new StringBuilder(120);
1768 sql.append("UPDATE ");
Vasu Nori8d45e4e2010-02-05 22:35:47 -08001769 sql.append(CONFLICT_VALUES[conflictAlgorithm]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 sql.append(table);
1771 sql.append(" SET ");
1772
1773 Set<Map.Entry<String, Object>> entrySet = values.valueSet();
1774 Iterator<Map.Entry<String, Object>> entriesIter = entrySet.iterator();
1775
1776 while (entriesIter.hasNext()) {
1777 Map.Entry<String, Object> entry = entriesIter.next();
1778 sql.append(entry.getKey());
1779 sql.append("=?");
1780 if (entriesIter.hasNext()) {
1781 sql.append(", ");
1782 }
1783 }
1784
1785 if (!TextUtils.isEmpty(whereClause)) {
1786 sql.append(" WHERE ");
1787 sql.append(whereClause);
1788 }
1789
Vasu Noriccd95442010-05-28 17:04:16 -07001790 verifyDbIsOpen();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 SQLiteStatement statement = null;
1792 try {
1793 statement = compileStatement(sql.toString());
1794
1795 // Bind the values
1796 int size = entrySet.size();
1797 entriesIter = entrySet.iterator();
1798 int bindArg = 1;
1799 for (int i = 0; i < size; i++) {
1800 Map.Entry<String, Object> entry = entriesIter.next();
1801 DatabaseUtils.bindObjectToProgram(statement, bindArg, entry.getValue());
1802 bindArg++;
1803 }
1804
1805 if (whereArgs != null) {
1806 size = whereArgs.length;
1807 for (int i = 0; i < size; i++) {
1808 statement.bindString(bindArg, whereArgs[i]);
1809 bindArg++;
1810 }
1811 }
1812
1813 // Run the program and then cleanup
Vasu Norifb16cbd2010-07-25 16:38:48 -07001814 return statement.executeUpdateDelete();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 } catch (SQLiteDatabaseCorruptException e) {
1816 onCorruption();
1817 throw e;
1818 } catch (SQLException e) {
1819 Log.e(TAG, "Error updating " + values + " using " + sql);
1820 throw e;
1821 } finally {
1822 if (statement != null) {
1823 statement.close();
1824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
1826 }
1827
1828 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001829 * Execute a single SQL statement that is NOT a SELECT
1830 * or any other SQL statement that returns data.
1831 * <p>
Vasu Norice38b982010-07-22 13:57:13 -07001832 * It has no means to return any data (such as the number of affected rows).
Vasu Noriccd95442010-05-28 17:04:16 -07001833 * Instead, you're encouraged to use {@link #insert(String, String, ContentValues)},
1834 * {@link #update(String, ContentValues, String, String[])}, et al, when possible.
1835 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001836 * <p>
1837 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1838 * automatically managed by this class. So, do not set journal_mode
1839 * using "PRAGMA journal_mode'<value>" statement if your app is using
1840 * {@link #enableWriteAheadLogging()}
1841 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 *
Vasu Noriccd95442010-05-28 17:04:16 -07001843 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1844 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 * @throws SQLException If the SQL string is invalid for some reason
1846 */
1847 public void execSQL(String sql) throws SQLException {
Vasu Norice38b982010-07-22 13:57:13 -07001848 int stmtType = DatabaseUtils.getSqlStatementType(sql);
1849 if (stmtType == DatabaseUtils.STATEMENT_ATTACH) {
Vasu Nori8d111032010-06-22 18:34:21 -07001850 disableWriteAheadLogging();
1851 }
Vasu Noric8e1f232010-04-13 15:05:09 -07001852 long timeStart = SystemClock.uptimeMillis();
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001853 logTimeStat(mLastSqlStatement, timeStart, GET_LOCK_LOG_PREFIX);
Vasu Norice38b982010-07-22 13:57:13 -07001854 executeSql(sql, null);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001855
1856 // Log commit statements along with the most recently executed
Vasu Norice38b982010-07-22 13:57:13 -07001857 // SQL statement for disambiguation.
1858 if (stmtType == DatabaseUtils.STATEMENT_COMMIT) {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001859 logTimeStat(mLastSqlStatement, timeStart, COMMIT_SQL);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001860 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07001861 logTimeStat(sql, timeStart, null);
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08001862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
1865 /**
Vasu Noriccd95442010-05-28 17:04:16 -07001866 * Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
1867 * <p>
1868 * For INSERT statements, use any of the following instead.
1869 * <ul>
1870 * <li>{@link #insert(String, String, ContentValues)}</li>
1871 * <li>{@link #insertOrThrow(String, String, ContentValues)}</li>
1872 * <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li>
1873 * </ul>
1874 * <p>
1875 * For UPDATE statements, use any of the following instead.
1876 * <ul>
1877 * <li>{@link #update(String, ContentValues, String, String[])}</li>
1878 * <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li>
1879 * </ul>
1880 * <p>
1881 * For DELETE statements, use any of the following instead.
1882 * <ul>
1883 * <li>{@link #delete(String, String, String[])}</li>
1884 * </ul>
1885 * <p>
1886 * For example, the following are good candidates for using this method:
1887 * <ul>
1888 * <li>ALTER TABLE</li>
1889 * <li>CREATE or DROP table / trigger / view / index / virtual table</li>
1890 * <li>REINDEX</li>
1891 * <li>RELEASE</li>
1892 * <li>SAVEPOINT</li>
1893 * <li>PRAGMA that returns no data</li>
1894 * </ul>
1895 * </p>
Vasu Nori9bf225e2010-07-07 16:38:28 -07001896 * <p>
1897 * When using {@link #enableWriteAheadLogging()}, journal_mode is
1898 * automatically managed by this class. So, do not set journal_mode
1899 * using "PRAGMA journal_mode'<value>" statement if your app is using
1900 * {@link #enableWriteAheadLogging()}
1901 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 *
Vasu Noriccd95442010-05-28 17:04:16 -07001903 * @param sql the SQL statement to be executed. Multiple statements separated by semicolons are
1904 * not supported.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 * @param bindArgs only byte[], String, Long and Double are supported in bindArgs.
1906 * @throws SQLException If the SQL string is invalid for some reason
1907 */
1908 public void execSQL(String sql, Object[] bindArgs) throws SQLException {
1909 if (bindArgs == null) {
1910 throw new IllegalArgumentException("Empty bindArgs");
1911 }
Vasu Norice38b982010-07-22 13:57:13 -07001912 executeSql(sql, bindArgs);
1913 }
1914
1915 private void executeSql(String sql, Object[] bindArgs) throws SQLException {
Vasu Noriccd95442010-05-28 17:04:16 -07001916 verifyDbIsOpen();
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08001917 long timeStart = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 SQLiteStatement statement = null;
1919 try {
1920 statement = compileStatement(sql);
1921 if (bindArgs != null) {
1922 int numArgs = bindArgs.length;
1923 for (int i = 0; i < numArgs; i++) {
1924 DatabaseUtils.bindObjectToProgram(statement, i + 1, bindArgs[i]);
1925 }
1926 }
Vasu Norice38b982010-07-22 13:57:13 -07001927 statement.execute();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 } catch (SQLiteDatabaseCorruptException e) {
1929 onCorruption();
1930 throw e;
1931 } finally {
1932 if (statement != null) {
1933 statement.close();
1934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Dan Egnor12311952009-11-23 14:47:45 -08001936 logTimeStat(sql, timeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938
1939 @Override
Mike Lockwood9d9c1be2010-07-13 19:27:52 -04001940 protected void finalize() throws Throwable {
1941 try {
1942 if (isOpen()) {
1943 Log.e(TAG, "close() was never explicitly called on database '" +
1944 mPath + "' ", mStackTrace);
1945 closeClosable();
1946 onAllReferencesReleased();
1947 releaseCustomFunctions();
1948 }
1949 } finally {
1950 super.finalize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952 }
1953
1954 /**
Vasu Nori21343692010-06-03 16:01:39 -07001955 * Private constructor.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 *
1957 * @param path The full path to the database
1958 * @param factory The factory to use when creating cursors, may be NULL.
1959 * @param flags 0 or {@link #NO_LOCALIZED_COLLATORS}. If the database file already
1960 * exists, mFlags will be updated appropriately.
Vasu Nori21343692010-06-03 16:01:39 -07001961 * @param errorHandler The {@link DatabaseErrorHandler} to be used when sqlite reports database
1962 * corruption. may be NULL.
Vasu Nori6c354da2010-04-26 23:33:39 -07001963 * @param connectionNum 0 for main database connection handle. 1..N for pooled database
1964 * connection handles.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 */
Vasu Nori21343692010-06-03 16:01:39 -07001966 private SQLiteDatabase(String path, CursorFactory factory, int flags,
Vasu Nori6c354da2010-04-26 23:33:39 -07001967 DatabaseErrorHandler errorHandler, short connectionNum) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 if (path == null) {
1969 throw new IllegalArgumentException("path should not be null");
1970 }
1971 mFlags = flags;
1972 mPath = path;
Dmitri Plotnikov90142c92009-09-15 10:52:17 -07001973 mSlowQueryThreshold = SystemProperties.getInt(LOG_SLOW_QUERIES_PROPERTY, -1);
Vasu Nori08b448e2010-03-03 10:05:16 -08001974 mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 mFactory = factory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 mPrograms = new WeakHashMap<SQLiteClosable,Object>();
Vasu Nori21343692010-06-03 16:01:39 -07001977 // Set the DatabaseErrorHandler to be used when SQLite reports corruption.
1978 // If the caller sets errorHandler = null, then use default errorhandler.
1979 mErrorHandler = (errorHandler == null) ? new DefaultDatabaseErrorHandler() : errorHandler;
Vasu Nori6c354da2010-04-26 23:33:39 -07001980 mConnectionNum = connectionNum;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 }
1982
1983 /**
1984 * return whether the DB is opened as read only.
1985 * @return true if DB is opened as read only
1986 */
1987 public boolean isReadOnly() {
1988 return (mFlags & OPEN_READ_MASK) == OPEN_READONLY;
1989 }
1990
1991 /**
1992 * @return true if the DB is currently open (has not been closed)
1993 */
1994 public boolean isOpen() {
1995 return mNativeHandle != 0;
1996 }
1997
1998 public boolean needUpgrade(int newVersion) {
1999 return newVersion > getVersion();
2000 }
2001
2002 /**
2003 * Getter for the path to the database file.
2004 *
2005 * @return the path to our database file.
2006 */
2007 public final String getPath() {
2008 return mPath;
2009 }
2010
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002011 /* package */ void logTimeStat(String sql, long beginMillis) {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002012 logTimeStat(sql, beginMillis, null);
2013 }
2014
2015 /* package */ void logTimeStat(String sql, long beginMillis, String prefix) {
Brad Fitzpatrickb28c7972010-02-12 12:49:41 -08002016 // Keep track of the last statement executed here, as this is
2017 // the common funnel through which all methods of hitting
2018 // libsqlite eventually flow.
2019 mLastSqlStatement = sql;
2020
Dan Egnor12311952009-11-23 14:47:45 -08002021 // Sample fast queries in proportion to the time taken.
2022 // Quantize the % first, so the logged sampling probability
2023 // exactly equals the actual sampling rate for this query.
2024
2025 int samplePercent;
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002026 long durationMillis = SystemClock.uptimeMillis() - beginMillis;
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002027 if (durationMillis == 0 && prefix == GET_LOCK_LOG_PREFIX) {
2028 // The common case is locks being uncontended. Don't log those,
2029 // even at 1%, which is our default below.
2030 return;
2031 }
2032 if (sQueryLogTimeInMillis == 0) {
2033 sQueryLogTimeInMillis = SystemProperties.getInt("db.db_operation.threshold_ms", 500);
2034 }
2035 if (durationMillis >= sQueryLogTimeInMillis) {
Dan Egnor12311952009-11-23 14:47:45 -08002036 samplePercent = 100;
Vasu Norifb16cbd2010-07-25 16:38:48 -07002037 } else {
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002038 samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1;
Dan Egnor799f7212009-11-24 16:24:44 -08002039 if (mRandom.nextInt(100) >= samplePercent) return;
Dan Egnor12311952009-11-23 14:47:45 -08002040 }
2041
Brad Fitzpatrick722802e2010-03-23 22:22:16 -07002042 // Note: the prefix will be "COMMIT;" or "GETLOCK:" when non-null. We wait to do
2043 // it here so we avoid allocating in the common case.
2044 if (prefix != null) {
2045 sql = prefix + sql;
2046 }
2047
Dan Egnor12311952009-11-23 14:47:45 -08002048 if (sql.length() > QUERY_LOG_SQL_LENGTH) sql = sql.substring(0, QUERY_LOG_SQL_LENGTH);
2049
2050 // ActivityThread.currentPackageName() only returns non-null if the
2051 // current thread is an application main thread. This parameter tells
2052 // us whether an event loop is blocked, and if so, which app it is.
2053 //
2054 // Sadly, there's no fast way to determine app name if this is *not* a
2055 // main thread, or when we are invoked via Binder (e.g. ContentProvider).
2056 // Hopefully the full path to the database will be informative enough.
2057
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002058 String blockingPackage = AppGlobals.getInitialPackage();
Dan Egnor12311952009-11-23 14:47:45 -08002059 if (blockingPackage == null) blockingPackage = "";
2060
Brad Fitzpatrickd72f7182010-02-11 17:07:51 -08002061 EventLog.writeEvent(
Brad Fitzpatrickd8330232010-02-19 10:59:01 -08002062 EVENT_DB_OPERATION,
2063 getPathForLogs(),
2064 sql,
2065 durationMillis,
2066 blockingPackage,
2067 samplePercent);
2068 }
2069
2070 /**
2071 * Removes email addresses from database filenames before they're
2072 * logged to the EventLog where otherwise apps could potentially
2073 * read them.
2074 */
2075 private String getPathForLogs() {
2076 if (mPathForLogs != null) {
2077 return mPathForLogs;
2078 }
2079 if (mPath == null) {
2080 return null;
2081 }
2082 if (mPath.indexOf('@') == -1) {
2083 mPathForLogs = mPath;
2084 } else {
2085 mPathForLogs = EMAIL_IN_DB_PATTERN.matcher(mPath).replaceAll("XX@YY");
2086 }
2087 return mPathForLogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
2090 /**
2091 * Sets the locale for this database. Does nothing if this database has
2092 * the NO_LOCALIZED_COLLATORS flag set or was opened read only.
2093 * @throws SQLException if the locale could not be set. The most common reason
2094 * for this is that there is no collator available for the locale you requested.
2095 * In this case the database remains unchanged.
2096 */
2097 public void setLocale(Locale locale) {
2098 lock();
2099 try {
2100 native_setLocale(locale.toString(), mFlags);
2101 } finally {
2102 unlock();
2103 }
2104 }
2105
Vasu Noriccd95442010-05-28 17:04:16 -07002106 /* package */ void verifyDbIsOpen() {
Vasu Nori9463f292010-04-30 12:22:18 -07002107 if (!isOpen()) {
Vasu Nori75010102010-07-01 16:23:06 -07002108 throw new IllegalStateException("database " + getPath() + " (conn# " +
2109 mConnectionNum + ") already closed");
Vasu Nori9463f292010-04-30 12:22:18 -07002110 }
Vasu Noriccd95442010-05-28 17:04:16 -07002111 }
2112
2113 /* package */ void verifyLockOwner() {
2114 verifyDbIsOpen();
2115 if (mLockingEnabled && !isDbLockedByCurrentThread()) {
Vasu Nori9463f292010-04-30 12:22:18 -07002116 throw new IllegalStateException("Don't have database lock!");
2117 }
2118 }
2119
Vasu Norie495d1f2010-01-06 16:34:19 -08002120 /*
2121 * ============================================================================
2122 *
2123 * The following methods deal with compiled-sql cache
2124 * ============================================================================
2125 */
2126 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002127 * Adds the given SQL and its compiled-statement-id-returned-by-sqlite to the
Vasu Norie495d1f2010-01-06 16:34:19 -08002128 * cache of compiledQueries attached to 'this'.
Vasu Noriccd95442010-05-28 17:04:16 -07002129 * <p>
2130 * If there is already a {@link SQLiteCompiledSql} in compiledQueries for the given SQL,
Vasu Norie495d1f2010-01-06 16:34:19 -08002131 * the new {@link SQLiteCompiledSql} object is NOT inserted into the cache (i.e.,the current
2132 * mapping is NOT replaced with the new mapping).
2133 */
2134 /* package */ void addToCompiledQueries(String sql, SQLiteCompiledSql compiledStatement) {
Vasu Norie495d1f2010-01-06 16:34:19 -08002135 SQLiteCompiledSql compiledSql = null;
2136 synchronized(mCompiledQueries) {
2137 // don't insert the new mapping if a mapping already exists
2138 compiledSql = mCompiledQueries.get(sql);
2139 if (compiledSql != null) {
2140 return;
2141 }
Vasu Nori20f549f2010-04-15 11:25:51 -07002142
Vasu Norie495d1f2010-01-06 16:34:19 -08002143 if (mCompiledQueries.size() == mMaxSqlCacheSize) {
Vasu Nori49d02ac2010-03-05 21:49:30 -08002144 /*
2145 * cache size of {@link #mMaxSqlCacheSize} is not enough for this app.
Vasu Nori20f549f2010-04-15 11:25:51 -07002146 * log a warning.
2147 * chances are it is NOT using ? for bindargs - or cachesize is too small.
Vasu Norie495d1f2010-01-06 16:34:19 -08002148 */
Vasu Nori49d02ac2010-03-05 21:49:30 -08002149 if (++mCacheFullWarnings == MAX_WARNINGS_ON_CACHESIZE_CONDITION) {
2150 Log.w(TAG, "Reached MAX size for compiled-sql statement cache for database " +
Vasu Nori20f549f2010-04-15 11:25:51 -07002151 getPath() + ". Consider increasing cachesize.");
Vasu Nori49d02ac2010-03-05 21:49:30 -08002152 }
Vasu Nori20f549f2010-04-15 11:25:51 -07002153 }
2154 /* add the given SQLiteCompiledSql compiledStatement to cache.
2155 * no need to worry about the cache size - because {@link #mCompiledQueries}
2156 * self-limits its size to {@link #mMaxSqlCacheSize}.
2157 */
2158 mCompiledQueries.put(sql, compiledStatement);
2159 if (SQLiteDebug.DEBUG_SQL_CACHE) {
2160 Log.v(TAG, "|adding_sql_to_cache|" + getPath() + "|" +
2161 mCompiledQueries.size() + "|" + sql);
Vasu Norie495d1f2010-01-06 16:34:19 -08002162 }
Vasu Norie495d1f2010-01-06 16:34:19 -08002163 }
Vasu Norie495d1f2010-01-06 16:34:19 -08002164 }
2165
Vasu Norice38b982010-07-22 13:57:13 -07002166 /** package-level access for testing purposes */
2167 /* package */ void deallocCachedSqlStatements() {
Vasu Norie495d1f2010-01-06 16:34:19 -08002168 synchronized (mCompiledQueries) {
2169 for (SQLiteCompiledSql compiledSql : mCompiledQueries.values()) {
2170 compiledSql.releaseSqlStatement();
2171 }
2172 mCompiledQueries.clear();
2173 }
2174 }
2175
2176 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002177 * From the compiledQueries cache, returns the compiled-statement-id for the given SQL.
2178 * Returns null, if not found in the cache.
Vasu Norie495d1f2010-01-06 16:34:19 -08002179 */
2180 /* package */ SQLiteCompiledSql getCompiledStatementForSql(String sql) {
2181 SQLiteCompiledSql compiledStatement = null;
2182 boolean cacheHit;
2183 synchronized(mCompiledQueries) {
Vasu Norie495d1f2010-01-06 16:34:19 -08002184 cacheHit = (compiledStatement = mCompiledQueries.get(sql)) != null;
2185 }
2186 if (cacheHit) {
2187 mNumCacheHits++;
2188 } else {
2189 mNumCacheMisses++;
2190 }
2191
2192 if (SQLiteDebug.DEBUG_SQL_CACHE) {
2193 Log.v(TAG, "|cache_stats|" +
2194 getPath() + "|" + mCompiledQueries.size() +
2195 "|" + mNumCacheHits + "|" + mNumCacheMisses +
Vasu Nori20f549f2010-04-15 11:25:51 -07002196 "|" + cacheHit + "|" + sql);
Vasu Norie495d1f2010-01-06 16:34:19 -08002197 }
2198 return compiledStatement;
2199 }
2200
2201 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002202 * Sets the maximum size of the prepared-statement cache for this database.
Vasu Norie495d1f2010-01-06 16:34:19 -08002203 * (size of the cache = number of compiled-sql-statements stored in the cache).
Vasu Noriccd95442010-05-28 17:04:16 -07002204 *<p>
2205 * Maximum cache size can ONLY be increased from its current size (default = 10).
2206 * If this method is called with smaller size than the current maximum value,
2207 * then IllegalStateException is thrown.
2208 *<p>
2209 * This method is thread-safe.
Vasu Norie495d1f2010-01-06 16:34:19 -08002210 *
Vasu Nori90a367262010-04-12 12:49:09 -07002211 * @param cacheSize the size of the cache. can be (0 to {@link #MAX_SQL_CACHE_SIZE})
2212 * @throws IllegalStateException if input cacheSize > {@link #MAX_SQL_CACHE_SIZE} or
2213 * > the value set with previous setMaxSqlCacheSize() call.
Vasu Norie495d1f2010-01-06 16:34:19 -08002214 */
2215 public synchronized void setMaxSqlCacheSize(int cacheSize) {
2216 if (cacheSize > MAX_SQL_CACHE_SIZE || cacheSize < 0) {
2217 throw new IllegalStateException("expected value between 0 and " + MAX_SQL_CACHE_SIZE);
2218 } else if (cacheSize < mMaxSqlCacheSize) {
2219 throw new IllegalStateException("cannot set cacheSize to a value less than the value " +
2220 "set with previous setMaxSqlCacheSize() call.");
2221 }
2222 mMaxSqlCacheSize = cacheSize;
2223 }
2224
Vasu Nori6c354da2010-04-26 23:33:39 -07002225 /* package */ boolean isSqlInStatementCache(String sql) {
2226 synchronized (mCompiledQueries) {
2227 return mCompiledQueries.containsKey(sql);
2228 }
2229 }
2230
Vasu Nori6f37f832010-05-19 11:53:25 -07002231 /* package */ void finalizeStatementLater(int id) {
2232 if (!isOpen()) {
2233 // database already closed. this statement will already have been finalized.
2234 return;
2235 }
2236 synchronized(mClosedStatementIds) {
2237 if (mClosedStatementIds.contains(id)) {
2238 // this statement id is already queued up for finalization.
2239 return;
2240 }
2241 mClosedStatementIds.add(id);
2242 }
2243 }
2244
Vasu Norice38b982010-07-22 13:57:13 -07002245 /* package */ void closePendingStatements() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002246 if (!isOpen()) {
2247 // since this database is already closed, no need to finalize anything.
2248 mClosedStatementIds.clear();
2249 return;
2250 }
2251 verifyLockOwner();
2252 /* to minimize synchronization on mClosedStatementIds, make a copy of the list */
2253 ArrayList<Integer> list = new ArrayList<Integer>(mClosedStatementIds.size());
2254 synchronized(mClosedStatementIds) {
2255 list.addAll(mClosedStatementIds);
2256 mClosedStatementIds.clear();
2257 }
2258 // finalize all the statements from the copied list
2259 int size = list.size();
2260 for (int i = 0; i < size; i++) {
2261 native_finalize(list.get(i));
2262 }
2263 }
2264
2265 /**
2266 * for testing only
Vasu Nori6f37f832010-05-19 11:53:25 -07002267 */
Vasu Norice38b982010-07-22 13:57:13 -07002268 /* package */ ArrayList<Integer> getQueuedUpStmtList() {
Vasu Nori6f37f832010-05-19 11:53:25 -07002269 return mClosedStatementIds;
2270 }
2271
Vasu Nori6c354da2010-04-26 23:33:39 -07002272 /**
2273 * This method enables parallel execution of queries from multiple threads on the same database.
2274 * It does this by opening multiple handles to the database and using a different
2275 * database handle for each query.
2276 * <p>
2277 * If a transaction is in progress on one connection handle and say, a table is updated in the
2278 * transaction, then query on the same table on another connection handle will block for the
2279 * transaction to complete. But this method enables such queries to execute by having them
2280 * return old version of the data from the table. Most often it is the data that existed in the
2281 * table prior to the above transaction updates on that table.
2282 * <p>
2283 * Maximum number of simultaneous handles used to execute queries in parallel is
2284 * dependent upon the device memory and possibly other properties.
2285 * <p>
2286 * After calling this method, execution of queries in parallel is enabled as long as this
2287 * database handle is open. To disable execution of queries in parallel, database should
2288 * be closed and reopened.
2289 * <p>
2290 * If a query is part of a transaction, then it is executed on the same database handle the
2291 * transaction was begun.
Vasu Nori6c354da2010-04-26 23:33:39 -07002292 * <p>
2293 * If the database has any attached databases, then execution of queries in paralel is NOT
Vasu Noria98cb262010-06-22 13:16:35 -07002294 * possible. In such cases, a message is printed to logcat and false is returned.
2295 * <p>
2296 * This feature is not available for :memory: databases. In such cases,
2297 * a message is printed to logcat and false is returned.
Vasu Nori6c354da2010-04-26 23:33:39 -07002298 * <p>
2299 * A typical way to use this method is the following:
2300 * <pre>
2301 * SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
2302 * CREATE_IF_NECESSARY, myDatabaseErrorHandler);
2303 * db.enableWriteAheadLogging();
2304 * </pre>
2305 * <p>
2306 * Writers should use {@link #beginTransactionNonExclusive()} or
2307 * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}
2308 * to start a trsnsaction.
2309 * Non-exclusive mode allows database file to be in readable by threads executing queries.
2310 * </p>
2311 *
Vasu Noria98cb262010-06-22 13:16:35 -07002312 * @return true if write-ahead-logging is set. false otherwise
Vasu Nori6c354da2010-04-26 23:33:39 -07002313 */
Vasu Noria98cb262010-06-22 13:16:35 -07002314 public synchronized boolean enableWriteAheadLogging() {
2315 if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
2316 Log.i(TAG, "can't enable WAL for memory databases.");
2317 return false;
Vasu Nori6c354da2010-04-26 23:33:39 -07002318 }
2319
2320 // make sure this database has NO attached databases because sqlite's write-ahead-logging
2321 // doesn't work for databases with attached databases
2322 if (getAttachedDbs().size() > 1) {
Vasu Norice38b982010-07-22 13:57:13 -07002323 if (Log.isLoggable(TAG, Log.DEBUG)) {
2324 Log.d(TAG,
2325 "this database: " + mPath + " has attached databases. can't enable WAL.");
2326 }
Vasu Noria98cb262010-06-22 13:16:35 -07002327 return false;
Vasu Nori6c354da2010-04-26 23:33:39 -07002328 }
Vasu Noria98cb262010-06-22 13:16:35 -07002329 if (mConnectionPool == null) {
2330 mConnectionPool = new DatabaseConnectionPool(this);
2331 setJournalMode(mPath, "WAL");
Vasu Nori6c354da2010-04-26 23:33:39 -07002332 }
Vasu Noria98cb262010-06-22 13:16:35 -07002333 return true;
Vasu Nori6c354da2010-04-26 23:33:39 -07002334 }
2335
Vasu Nori2827d6d2010-07-04 00:26:18 -07002336 /**
Vasu Nori7b04c412010-07-20 10:31:21 -07002337 * This method disables the features enabled by {@link #enableWriteAheadLogging()}.
2338 * @hide
Vasu Nori2827d6d2010-07-04 00:26:18 -07002339 */
Vasu Nori7b04c412010-07-20 10:31:21 -07002340 public void disableWriteAheadLogging() {
2341 synchronized (this) {
2342 if (mConnectionPool == null) {
2343 return;
2344 }
2345 mConnectionPool.close();
2346 mConnectionPool = null;
2347 setJournalMode(mPath, "TRUNCATE");
Vasu Nori8d111032010-06-22 18:34:21 -07002348 }
Vasu Nori8d111032010-06-22 18:34:21 -07002349 }
2350
Vasu Nori65a88832010-07-16 15:14:08 -07002351 /* package */ SQLiteDatabase getDatabaseHandle(String sql) {
2352 if (isPooledConnection()) {
2353 // this is a pooled database connection
Vasu Norice38b982010-07-22 13:57:13 -07002354 // use it if it is open AND if I am not currently part of a transaction
2355 if (isOpen() && !amIInTransaction()) {
Vasu Nori65a88832010-07-16 15:14:08 -07002356 // TODO: use another connection from the pool
2357 // if this connection is currently in use by some other thread
2358 // AND if there are free connections in the pool
2359 return this;
2360 } else {
2361 // the pooled connection is not open! could have been closed either due
2362 // to corruption on this or some other connection to the database
2363 // OR, maybe the connection pool is disabled after this connection has been
2364 // allocated to me. try to get some other pooled or main database connection
2365 return getParentDbConnObj().getDbConnection(sql);
2366 }
2367 } else {
2368 // this is NOT a pooled connection. can we get one?
2369 return getDbConnection(sql);
2370 }
2371 }
2372
Vasu Nori6c354da2010-04-26 23:33:39 -07002373 /**
2374 * Sets the database connection handle pool size to the given value.
2375 * Database connection handle pool is enabled when the app calls
2376 * {@link #enableWriteAheadLogging()}.
2377 * <p>
2378 * The default connection handle pool is set by the system by taking into account various
2379 * aspects of the device, such as memory, number of cores etc. It is recommended that
2380 * applications use the default pool size set by the system.
2381 *
2382 * @param size the value the connection handle pool size should be set to.
2383 */
2384 public synchronized void setConnectionPoolSize(int size) {
2385 if (mConnectionPool == null) {
2386 throw new IllegalStateException("connection pool not enabled");
2387 }
2388 int i = mConnectionPool.getMaxPoolSize();
2389 if (size < i) {
Vasu Noridaa4e4f2010-06-15 11:32:27 -07002390 throw new IllegalArgumentException(
Vasu Nori6c354da2010-04-26 23:33:39 -07002391 "cannot set max pool size to a value less than the current max value(=" +
2392 i + ")");
2393 }
2394 mConnectionPool.setMaxPoolSize(size);
2395 }
2396
2397 /* package */ SQLiteDatabase createPoolConnection(short connectionNum) {
Vasu Nori65a88832010-07-16 15:14:08 -07002398 SQLiteDatabase db = openDatabase(mPath, mFactory, mFlags, mErrorHandler, connectionNum);
2399 db.mParentConnObj = this;
2400 return db;
2401 }
2402
2403 private synchronized SQLiteDatabase getParentDbConnObj() {
2404 return mParentConnObj;
Vasu Nori6c354da2010-04-26 23:33:39 -07002405 }
2406
2407 private boolean isPooledConnection() {
2408 return this.mConnectionNum > 0;
2409 }
2410
Vasu Nori2827d6d2010-07-04 00:26:18 -07002411 /* package */ SQLiteDatabase getDbConnection(String sql) {
Vasu Nori6c354da2010-04-26 23:33:39 -07002412 verifyDbIsOpen();
Vasu Nori65a88832010-07-16 15:14:08 -07002413 // this method should always be called with main database connection handle
2414 // NEVER with pooled database connection handle
2415 if (isPooledConnection()) {
2416 throw new IllegalStateException("incorrect database connection handle");
2417 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002418
2419 // use the current connection handle if
Vasu Norice38b982010-07-22 13:57:13 -07002420 // 1. if the caller is part of the ongoing transaction, if any
Vasu Nori65a88832010-07-16 15:14:08 -07002421 // 2. OR, if there is NO connection handle pool setup
Vasu Norice38b982010-07-22 13:57:13 -07002422 if (amIInTransaction() || mConnectionPool == null) {
Vasu Nori65a88832010-07-16 15:14:08 -07002423 return this;
Vasu Nori6c354da2010-04-26 23:33:39 -07002424 } else {
2425 // get a connection handle from the pool
2426 if (Log.isLoggable(TAG, Log.DEBUG)) {
2427 assert mConnectionPool != null;
Vasu Norice38b982010-07-22 13:57:13 -07002428 Log.i(TAG, mConnectionPool.toString());
Vasu Nori6c354da2010-04-26 23:33:39 -07002429 }
Vasu Nori65a88832010-07-16 15:14:08 -07002430 return mConnectionPool.get(sql);
Vasu Nori6c354da2010-04-26 23:33:39 -07002431 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002432 }
2433
2434 private void releaseDbConnection(SQLiteDatabase db) {
2435 // ignore this release call if
2436 // 1. the database is closed
2437 // 2. OR, if db is NOT a pooled connection handle
2438 // 3. OR, if the database being released is same as 'this' (this condition means
2439 // that we should always be releasing a pooled connection handle by calling this method
2440 // from the 'main' connection handle
2441 if (!isOpen() || !db.isPooledConnection() || (db == this)) {
2442 return;
2443 }
2444 if (Log.isLoggable(TAG, Log.DEBUG)) {
2445 assert isPooledConnection();
2446 assert mConnectionPool != null;
2447 Log.d(TAG, "releaseDbConnection threadid = " + Thread.currentThread().getId() +
2448 ", releasing # " + db.mConnectionNum + ", " + getPath());
2449 }
2450 mConnectionPool.release(db);
2451 }
2452
Vasu Noric3849202010-03-09 10:47:25 -08002453 static class ActiveDatabases {
2454 private static final ActiveDatabases activeDatabases = new ActiveDatabases();
2455 private HashSet<WeakReference<SQLiteDatabase>> mActiveDatabases =
Vasu Noriccd95442010-05-28 17:04:16 -07002456 new HashSet<WeakReference<SQLiteDatabase>>();
Vasu Noric3849202010-03-09 10:47:25 -08002457 private ActiveDatabases() {} // disable instantiation of this class
Vasu Noriccd95442010-05-28 17:04:16 -07002458 static ActiveDatabases getInstance() {
2459 return activeDatabases;
2460 }
2461 private static void addActiveDatabase(SQLiteDatabase sqliteDatabase) {
2462 activeDatabases.mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase));
2463 }
Vasu Noric3849202010-03-09 10:47:25 -08002464 }
2465
Vasu Norif3cf8a42010-03-23 11:41:44 -07002466 /**
2467 * this method is used to collect data about ALL open databases in the current process.
2468 * bugreport is a user of this data.
2469 */
Vasu Noric3849202010-03-09 10:47:25 -08002470 /* package */ static ArrayList<DbStats> getDbStats() {
2471 ArrayList<DbStats> dbStatsList = new ArrayList<DbStats>();
2472 for (WeakReference<SQLiteDatabase> w : ActiveDatabases.getInstance().mActiveDatabases) {
2473 SQLiteDatabase db = w.get();
2474 if (db == null || !db.isOpen()) {
2475 continue;
2476 }
Vasu Noric3849202010-03-09 10:47:25 -08002477
Vasu Noriccd95442010-05-28 17:04:16 -07002478 try {
2479 // get SQLITE_DBSTATUS_LOOKASIDE_USED for the db
2480 int lookasideUsed = db.native_getDbLookaside();
Vasu Noric3849202010-03-09 10:47:25 -08002481
Vasu Noriccd95442010-05-28 17:04:16 -07002482 // get the lastnode of the dbname
2483 String path = db.getPath();
2484 int indx = path.lastIndexOf("/");
2485 String lastnode = path.substring((indx != -1) ? ++indx : 0);
Vasu Noric3849202010-03-09 10:47:25 -08002486
Vasu Noriccd95442010-05-28 17:04:16 -07002487 // get list of attached dbs and for each db, get its size and pagesize
2488 ArrayList<Pair<String, String>> attachedDbs = db.getAttachedDbs();
2489 if (attachedDbs == null) {
2490 continue;
2491 }
2492 for (int i = 0; i < attachedDbs.size(); i++) {
2493 Pair<String, String> p = attachedDbs.get(i);
2494 long pageCount = DatabaseUtils.longForQuery(db, "PRAGMA " + p.first
2495 + ".page_count;", null);
2496
2497 // first entry in the attached db list is always the main database
2498 // don't worry about prefixing the dbname with "main"
2499 String dbName;
2500 if (i == 0) {
2501 dbName = lastnode;
2502 } else {
2503 // lookaside is only relevant for the main db
2504 lookasideUsed = 0;
2505 dbName = " (attached) " + p.first;
2506 // if the attached db has a path, attach the lastnode from the path to above
2507 if (p.second.trim().length() > 0) {
2508 int idx = p.second.lastIndexOf("/");
2509 dbName += " : " + p.second.substring((idx != -1) ? ++idx : 0);
2510 }
2511 }
2512 if (pageCount > 0) {
2513 dbStatsList.add(new DbStats(dbName, pageCount, db.getPageSize(),
2514 lookasideUsed, db.mNumCacheHits, db.mNumCacheMisses,
2515 db.mCompiledQueries.size()));
Vasu Noric3849202010-03-09 10:47:25 -08002516 }
2517 }
Vasu Nori6c354da2010-04-26 23:33:39 -07002518 // if there are pooled connections, return the cache stats for them also.
2519 if (db.mConnectionPool != null) {
2520 for (SQLiteDatabase pDb : db.mConnectionPool.getConnectionList()) {
2521 dbStatsList.add(new DbStats("(pooled # " + pDb.mConnectionNum + ") "
2522 + lastnode, 0, 0, 0, pDb.mNumCacheHits, pDb.mNumCacheMisses,
2523 pDb.mCompiledQueries.size()));
2524 }
2525 }
Vasu Noriccd95442010-05-28 17:04:16 -07002526 } catch (SQLiteException e) {
2527 // ignore. we don't care about exceptions when we are taking adb
2528 // bugreport!
Vasu Noric3849202010-03-09 10:47:25 -08002529 }
2530 }
2531 return dbStatsList;
2532 }
2533
2534 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002535 * Returns list of full pathnames of all attached databases including the main database
2536 * by executing 'pragma database_list' on the database.
2537 *
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002538 * @return ArrayList of pairs of (database name, database file path) or null if the database
2539 * is not open.
Vasu Noric3849202010-03-09 10:47:25 -08002540 */
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002541 public ArrayList<Pair<String, String>> getAttachedDbs() {
2542 if (!isOpen()) {
Vasu Norif3cf8a42010-03-23 11:41:44 -07002543 return null;
2544 }
Vasu Noric3849202010-03-09 10:47:25 -08002545 ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002546 Cursor c = null;
2547 try {
2548 c = rawQuery("pragma database_list;", null);
2549 while (c.moveToNext()) {
2550 // sqlite returns a row for each database in the returned list of databases.
2551 // in each row,
2552 // 1st column is the database name such as main, or the database
2553 // name specified on the "ATTACH" command
2554 // 2nd column is the database file path.
2555 attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
2556 }
2557 } finally {
2558 if (c != null) {
2559 c.close();
2560 }
Vasu Noric3849202010-03-09 10:47:25 -08002561 }
Vasu Noric3849202010-03-09 10:47:25 -08002562 return attachedDbs;
2563 }
2564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002566 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
2567 * and returns true if the given database (and all its attached databases) pass integrity_check,
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002568 * false otherwise.
Vasu Noriccd95442010-05-28 17:04:16 -07002569 *<p>
2570 * If the result is false, then this method logs the errors reported by the integrity_check
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002571 * command execution.
Vasu Noriccd95442010-05-28 17:04:16 -07002572 *<p>
2573 * Note that 'pragma integrity_check' on a database can take a long time.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002574 *
2575 * @return true if the given database (and all its attached databases) pass integrity_check,
Vasu Noriccd95442010-05-28 17:04:16 -07002576 * false otherwise.
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002577 */
2578 public boolean isDatabaseIntegrityOk() {
Vasu Noriccd95442010-05-28 17:04:16 -07002579 verifyDbIsOpen();
Vasu Nori062fc7ce2010-03-31 16:13:05 -07002580 ArrayList<Pair<String, String>> attachedDbs = getAttachedDbs();
2581 if (attachedDbs == null) {
2582 throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
2583 "be retrieved. probably because the database is closed");
2584 }
2585 boolean isDatabaseCorrupt = false;
2586 for (int i = 0; i < attachedDbs.size(); i++) {
2587 Pair<String, String> p = attachedDbs.get(i);
2588 SQLiteStatement prog = null;
2589 try {
2590 prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
2591 String rslt = prog.simpleQueryForString();
2592 if (!rslt.equalsIgnoreCase("ok")) {
2593 // integrity_checker failed on main or attached databases
2594 isDatabaseCorrupt = true;
2595 Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
2596 }
2597 } finally {
2598 if (prog != null) prog.close();
2599 }
2600 }
2601 return isDatabaseCorrupt;
2602 }
2603
2604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 * Native call to open the database.
2606 *
2607 * @param path The full path to the database
2608 */
2609 private native void dbopen(String path, int flags);
2610
2611 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002612 * Native call to setup tracing of all SQL statements
Vasu Nori3ef94e22010-02-05 14:49:04 -08002613 *
2614 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002615 * @param connectionNum connection number: 0 - N, where the main database
2616 * connection handle is numbered 0 and the connection handles in the connection
2617 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002618 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002619 private native void enableSqlTracing(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002620
2621 /**
Vasu Noriccd95442010-05-28 17:04:16 -07002622 * Native call to setup profiling of all SQL statements.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002623 * currently, sqlite's profiling = printing of execution-time
Vasu Noriccd95442010-05-28 17:04:16 -07002624 * (wall-clock time) of each of the SQL statements, as they
Vasu Nori3ef94e22010-02-05 14:49:04 -08002625 * are executed.
2626 *
2627 * @param path the full path to the database
Vasu Nori6c354da2010-04-26 23:33:39 -07002628 * @param connectionNum connection number: 0 - N, where the main database
2629 * connection handle is numbered 0 and the connection handles in the connection
2630 * pool are numbered 1..N.
Vasu Nori3ef94e22010-02-05 14:49:04 -08002631 */
Vasu Nori6c354da2010-04-26 23:33:39 -07002632 private native void enableSqlProfiling(String path, short connectionNum);
Vasu Nori3ef94e22010-02-05 14:49:04 -08002633
2634 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 * Native call to set the locale. {@link #lock} must be held when calling
2636 * this method.
2637 * @throws SQLException
2638 */
2639 /* package */ native void native_setLocale(String loc, int flags);
2640
2641 /**
Vasu Noric3849202010-03-09 10:47:25 -08002642 * return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here
2643 * http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html
2644 * @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED
2645 */
2646 private native int native_getDbLookaside();
Vasu Nori6f37f832010-05-19 11:53:25 -07002647
2648 /**
2649 * finalizes the given statement id.
2650 *
2651 * @param statementId statement to be finzlied by sqlite
2652 */
2653 private final native void native_finalize(int statementId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654}