SQLiteCursor.java revision 7cd51efcbd2d083bf577696591ef1769034f7e2f
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.database.sqlite; 18 19import android.app.ActivityThread; 20import android.database.AbstractWindowedCursor; 21import android.database.CursorWindow; 22import android.database.DataSetObserver; 23import android.database.RequeryOnUiThreadException; 24import android.os.Handler; 25import android.os.Looper; 26import android.os.Message; 27import android.os.Process; 28import android.util.Config; 29import android.util.Log; 30 31import java.util.HashMap; 32import java.util.Map; 33import java.util.concurrent.locks.ReentrantLock; 34 35/** 36 * A Cursor implementation that exposes results from a query on a 37 * {@link SQLiteDatabase}. 38 * 39 * SQLiteCursor is not internally synchronized so code using a SQLiteCursor from multiple 40 * threads should perform its own synchronization when using the SQLiteCursor. 41 */ 42public class SQLiteCursor extends AbstractWindowedCursor { 43 static final String TAG = "Cursor"; 44 static final int NO_COUNT = -1; 45 46 /** The name of the table to edit */ 47 private String mEditTable; 48 49 /** The names of the columns in the rows */ 50 private String[] mColumns; 51 52 /** The query object for the cursor */ 53 private SQLiteQuery mQuery; 54 55 /** The database the cursor was created from */ 56 private SQLiteDatabase mDatabase; 57 58 /** The compiled query this cursor came from */ 59 private SQLiteCursorDriver mDriver; 60 61 /** The number of rows in the cursor */ 62 private int mCount = NO_COUNT; 63 64 /** A mapping of column names to column indices, to speed up lookups */ 65 private Map<String, Integer> mColumnNameMap; 66 67 /** Used to find out where a cursor was allocated in case it never got released. */ 68 private Throwable mStackTrace; 69 70 /** 71 * mMaxRead is the max items that each cursor window reads 72 * default to a very high value 73 */ 74 private int mMaxRead = Integer.MAX_VALUE; 75 private int mInitialRead = Integer.MAX_VALUE; 76 private int mCursorState = 0; 77 private ReentrantLock mLock = null; 78 private boolean mPendingData = false; 79 80 /** 81 * Used by {@link #requery()} to remember for which database we've already shown the warning. 82 */ 83 private static final HashMap<String, Boolean> sAlreadyWarned = new HashMap<String, Boolean>(); 84 85 /** 86 * support for a cursor variant that doesn't always read all results 87 * initialRead is the initial number of items that cursor window reads 88 * if query contains more than this number of items, a thread will be 89 * created and handle the left over items so that caller can show 90 * results as soon as possible 91 * @param initialRead initial number of items that cursor read 92 * @param maxRead leftover items read at maxRead items per time 93 * @hide 94 */ 95 public void setLoadStyle(int initialRead, int maxRead) { 96 mMaxRead = maxRead; 97 mInitialRead = initialRead; 98 mLock = new ReentrantLock(true); 99 } 100 101 private void queryThreadLock() { 102 if (mLock != null) { 103 mLock.lock(); 104 } 105 } 106 107 private void queryThreadUnlock() { 108 if (mLock != null) { 109 mLock.unlock(); 110 } 111 } 112 113 114 /** 115 * @hide 116 */ 117 final private class QueryThread implements Runnable { 118 private final int mThreadState; 119 QueryThread(int version) { 120 mThreadState = version; 121 } 122 private void sendMessage() { 123 if (mNotificationHandler != null) { 124 mNotificationHandler.sendEmptyMessage(1); 125 mPendingData = false; 126 } else { 127 mPendingData = true; 128 } 129 130 } 131 public void run() { 132 // use cached mWindow, to avoid get null mWindow 133 CursorWindow cw = mWindow; 134 Process.setThreadPriority(Process.myTid(), Process.THREAD_PRIORITY_BACKGROUND); 135 // the cursor's state doesn't change 136 while (true) { 137 mLock.lock(); 138 if (mCursorState != mThreadState) { 139 mLock.unlock(); 140 break; 141 } 142 try { 143 int count = mQuery.fillWindow(cw, mMaxRead, mCount); 144 // return -1 means not finished 145 if (count != 0) { 146 if (count == NO_COUNT){ 147 mCount += mMaxRead; 148 sendMessage(); 149 } else { 150 mCount = count; 151 sendMessage(); 152 break; 153 } 154 } else { 155 break; 156 } 157 } catch (Exception e) { 158 // end the tread when the cursor is close 159 break; 160 } finally { 161 mLock.unlock(); 162 } 163 } 164 } 165 } 166 167 /** 168 * @hide 169 */ 170 protected class MainThreadNotificationHandler extends Handler { 171 public void handleMessage(Message msg) { 172 notifyDataSetChange(); 173 } 174 } 175 176 /** 177 * @hide 178 */ 179 protected MainThreadNotificationHandler mNotificationHandler; 180 181 public void registerDataSetObserver(DataSetObserver observer) { 182 super.registerDataSetObserver(observer); 183 if ((Integer.MAX_VALUE != mMaxRead || Integer.MAX_VALUE != mInitialRead) && 184 mNotificationHandler == null) { 185 queryThreadLock(); 186 try { 187 mNotificationHandler = new MainThreadNotificationHandler(); 188 if (mPendingData) { 189 notifyDataSetChange(); 190 mPendingData = false; 191 } 192 } finally { 193 queryThreadUnlock(); 194 } 195 } 196 197 } 198 199 /** 200 * Execute a query and provide access to its result set through a Cursor 201 * interface. For a query such as: {@code SELECT name, birth, phone FROM 202 * myTable WHERE ... LIMIT 1,20 ORDER BY...} the column names (name, birth, 203 * phone) would be in the projection argument and everything from 204 * {@code FROM} onward would be in the params argument. This constructor 205 * has package scope. 206 * 207 * @param db a reference to a Database object that is already constructed 208 * and opened 209 * @param editTable the name of the table used for this query 210 * @param query the rest of the query terms 211 * cursor is finalized 212 */ 213 public SQLiteCursor(SQLiteDatabase db, SQLiteCursorDriver driver, 214 String editTable, SQLiteQuery query) { 215 // The AbstractCursor constructor needs to do some setup. 216 super(); 217 mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace(); 218 mDatabase = db; 219 mDriver = driver; 220 mEditTable = editTable; 221 mColumnNameMap = null; 222 mQuery = query; 223 224 try { 225 db.lock(); 226 227 // Setup the list of columns 228 int columnCount = mQuery.columnCountLocked(); 229 mColumns = new String[columnCount]; 230 231 // Read in all column names 232 for (int i = 0; i < columnCount; i++) { 233 String columnName = mQuery.columnNameLocked(i); 234 mColumns[i] = columnName; 235 if (Config.LOGV) { 236 Log.v("DatabaseWindow", "mColumns[" + i + "] is " 237 + mColumns[i]); 238 } 239 240 // Make note of the row ID column index for quick access to it 241 if ("_id".equals(columnName)) { 242 mRowIdColumnIndex = i; 243 } 244 } 245 } finally { 246 db.unlock(); 247 } 248 } 249 250 /** 251 * @return the SQLiteDatabase that this cursor is associated with. 252 */ 253 public SQLiteDatabase getDatabase() { 254 return mDatabase; 255 } 256 257 @Override 258 public boolean onMove(int oldPosition, int newPosition) { 259 // Make sure the row at newPosition is present in the window 260 if (mWindow == null || newPosition < mWindow.getStartPosition() || 261 newPosition >= (mWindow.getStartPosition() + mWindow.getNumRows())) { 262 fillWindow(newPosition); 263 } 264 265 return true; 266 } 267 268 @Override 269 public int getCount() { 270 if (mCount == NO_COUNT) { 271 fillWindow(0); 272 } 273 return mCount; 274 } 275 276 private void fillWindow (int startPos) { 277 if (mWindow == null) { 278 // If there isn't a window set already it will only be accessed locally 279 mWindow = new CursorWindow(true /* the window is local only */); 280 } else { 281 mCursorState++; 282 queryThreadLock(); 283 try { 284 mWindow.clear(); 285 } finally { 286 queryThreadUnlock(); 287 } 288 } 289 mWindow.setStartPosition(startPos); 290 mCount = mQuery.fillWindow(mWindow, mInitialRead, 0); 291 // return -1 means not finished 292 if (mCount == NO_COUNT){ 293 mCount = startPos + mInitialRead; 294 Thread t = new Thread(new QueryThread(mCursorState), "query thread"); 295 t.start(); 296 } 297 } 298 299 @Override 300 public int getColumnIndex(String columnName) { 301 // Create mColumnNameMap on demand 302 if (mColumnNameMap == null) { 303 String[] columns = mColumns; 304 int columnCount = columns.length; 305 HashMap<String, Integer> map = new HashMap<String, Integer>(columnCount, 1); 306 for (int i = 0; i < columnCount; i++) { 307 map.put(columns[i], i); 308 } 309 mColumnNameMap = map; 310 } 311 312 // Hack according to bug 903852 313 final int periodIndex = columnName.lastIndexOf('.'); 314 if (periodIndex != -1) { 315 Exception e = new Exception(); 316 Log.e(TAG, "requesting column name with table name -- " + columnName, e); 317 columnName = columnName.substring(periodIndex + 1); 318 } 319 320 Integer i = mColumnNameMap.get(columnName); 321 if (i != null) { 322 return i.intValue(); 323 } else { 324 return -1; 325 } 326 } 327 328 @Override 329 public String[] getColumnNames() { 330 return mColumns; 331 } 332 333 private void deactivateCommon() { 334 if (Config.LOGV) Log.v(TAG, "<<< Releasing cursor " + this); 335 mCursorState = 0; 336 if (mWindow != null) { 337 mWindow.close(); 338 mWindow = null; 339 } 340 if (Config.LOGV) Log.v("DatabaseWindow", "closing window in release()"); 341 } 342 343 @Override 344 public void deactivate() { 345 super.deactivate(); 346 deactivateCommon(); 347 mDriver.cursorDeactivated(); 348 } 349 350 @Override 351 public void close() { 352 super.close(); 353 deactivateCommon(); 354 mQuery.close(); 355 mDriver.cursorClosed(); 356 } 357 358 /** 359 * Show a warning against the use of requery() if called on the main thread. 360 * This warning is shown per database per process. 361 */ 362 private void warnIfUiThread() { 363 if (Looper.getMainLooper() == Looper.myLooper()) { 364 String databasePath = mDatabase.getPath(); 365 // We show the warning once per database in order not to spam logcat. 366 if (!sAlreadyWarned.containsKey(databasePath)) { 367 sAlreadyWarned.put(databasePath, true); 368 String packageName = ActivityThread.currentPackageName(); 369 Log.w(TAG, "should not attempt requery on main (UI) thread: app = " + 370 packageName == null ? "'unknown'" : packageName, 371 new RequeryOnUiThreadException(packageName)); 372 } 373 } 374 } 375 376 @Override 377 public boolean requery() { 378 if (isClosed()) { 379 return false; 380 } 381 warnIfUiThread(); 382 long timeStart = 0; 383 if (Config.LOGV) { 384 timeStart = System.currentTimeMillis(); 385 } 386 /* 387 * Synchronize on the database lock to ensure that mCount matches the 388 * results of mQuery.requery(). 389 */ 390 mDatabase.lock(); 391 try { 392 if (mWindow != null) { 393 mWindow.clear(); 394 } 395 mPos = -1; 396 // This one will recreate the temp table, and get its count 397 mDriver.cursorRequeried(this); 398 mCount = NO_COUNT; 399 mCursorState++; 400 queryThreadLock(); 401 try { 402 mQuery.requery(); 403 } finally { 404 queryThreadUnlock(); 405 } 406 } finally { 407 mDatabase.unlock(); 408 } 409 410 if (Config.LOGV) { 411 Log.v("DatabaseWindow", "closing window in requery()"); 412 Log.v(TAG, "--- Requery()ed cursor " + this + ": " + mQuery); 413 } 414 415 boolean result = super.requery(); 416 if (Config.LOGV) { 417 long timeEnd = System.currentTimeMillis(); 418 Log.v(TAG, "requery (" + (timeEnd - timeStart) + " ms): " + mDriver.toString()); 419 } 420 return result; 421 } 422 423 @Override 424 public void setWindow(CursorWindow window) { 425 if (mWindow != null) { 426 mCursorState++; 427 queryThreadLock(); 428 try { 429 mWindow.close(); 430 } finally { 431 queryThreadUnlock(); 432 } 433 mCount = NO_COUNT; 434 } 435 mWindow = window; 436 } 437 438 /** 439 * Changes the selection arguments. The new values take effect after a call to requery(). 440 */ 441 public void setSelectionArguments(String[] selectionArgs) { 442 mDriver.setBindArguments(selectionArgs); 443 } 444 445 /** 446 * Release the native resources, if they haven't been released yet. 447 */ 448 @Override 449 protected void finalize() { 450 try { 451 // if the cursor hasn't been closed yet, close it first 452 if (mWindow != null) { 453 int len = mQuery.mSql.length(); 454 Log.e(TAG, "Finalizing a Cursor that has not been deactivated or closed. " + 455 "database = " + mDatabase.getPath() + ", table = " + mEditTable + 456 ", query = " + mQuery.mSql.substring(0, (len > 100) ? 100 : len), 457 mStackTrace); 458 close(); 459 SQLiteDebug.notifyActiveCursorFinalized(); 460 } else { 461 if (Config.LOGV) { 462 Log.v(TAG, "Finalizing cursor on database = " + mDatabase.getPath() + 463 ", table = " + mEditTable + ", query = " + mQuery.mSql); 464 } 465 } 466 } finally { 467 super.finalize(); 468 } 469 } 470} 471