SQLiteCursor.java revision ebc016c01ea9d5707287cfc19ccc59b21a486c00
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.database.AbstractWindowedCursor;
20import android.database.CursorWindow;
21import android.database.DatabaseUtils;
22import android.os.StrictMode;
23import android.util.Log;
24
25import java.util.HashMap;
26import java.util.Map;
27
28/**
29 * A Cursor implementation that exposes results from a query on a
30 * {@link SQLiteDatabase}.
31 *
32 * SQLiteCursor is not internally synchronized so code using a SQLiteCursor from multiple
33 * threads should perform its own synchronization when using the SQLiteCursor.
34 */
35public class SQLiteCursor extends AbstractWindowedCursor {
36    static final String TAG = "SQLiteCursor";
37    static final int NO_COUNT = -1;
38
39    /** The name of the table to edit */
40    private final String mEditTable;
41
42    /** The names of the columns in the rows */
43    private final String[] mColumns;
44
45    /** The query object for the cursor */
46    private final SQLiteQuery mQuery;
47
48    /** The compiled query this cursor came from */
49    private final SQLiteCursorDriver mDriver;
50
51    /** The number of rows in the cursor */
52    private int mCount = NO_COUNT;
53
54    /** The number of rows that can fit in the cursor window, 0 if unknown */
55    private int mCursorWindowCapacity;
56
57    /** A mapping of column names to column indices, to speed up lookups */
58    private Map<String, Integer> mColumnNameMap;
59
60    /** Used to find out where a cursor was allocated in case it never got released. */
61    private final Throwable mStackTrace;
62
63    /**
64     * Execute a query and provide access to its result set through a Cursor
65     * interface. For a query such as: {@code SELECT name, birth, phone FROM
66     * myTable WHERE ... LIMIT 1,20 ORDER BY...} the column names (name, birth,
67     * phone) would be in the projection argument and everything from
68     * {@code FROM} onward would be in the params argument.
69     *
70     * @param db a reference to a Database object that is already constructed
71     *     and opened. This param is not used any longer
72     * @param editTable the name of the table used for this query
73     * @param query the rest of the query terms
74     *     cursor is finalized
75     * @deprecated use {@link #SQLiteCursor(SQLiteCursorDriver, String, SQLiteQuery)} instead
76     */
77    @Deprecated
78    public SQLiteCursor(SQLiteDatabase db, SQLiteCursorDriver driver,
79            String editTable, SQLiteQuery query) {
80        this(driver, editTable, query);
81    }
82
83    /**
84     * Execute a query and provide access to its result set through a Cursor
85     * interface. For a query such as: {@code SELECT name, birth, phone FROM
86     * myTable WHERE ... LIMIT 1,20 ORDER BY...} the column names (name, birth,
87     * phone) would be in the projection argument and everything from
88     * {@code FROM} onward would be in the params argument.
89     *
90     * @param editTable the name of the table used for this query
91     * @param query the {@link SQLiteQuery} object associated with this cursor object.
92     */
93    public SQLiteCursor(SQLiteCursorDriver driver, String editTable, SQLiteQuery query) {
94        if (query == null) {
95            throw new IllegalArgumentException("query object cannot be null");
96        }
97        if (StrictMode.vmSqliteObjectLeaksEnabled()) {
98            mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
99        } else {
100            mStackTrace = null;
101        }
102        mDriver = driver;
103        mEditTable = editTable;
104        mColumnNameMap = null;
105        mQuery = query;
106
107        mColumns = query.getColumnNames();
108        for (int i = 0; i < mColumns.length; i++) {
109            // Make note of the row ID column index for quick access to it
110            if ("_id".equals(mColumns[i])) {
111                mRowIdColumnIndex = i;
112            }
113        }
114    }
115
116    /**
117     * Get the database that this cursor is associated with.
118     * @return the SQLiteDatabase that this cursor is associated with.
119     */
120    public SQLiteDatabase getDatabase() {
121        return mQuery.getDatabase();
122    }
123
124    @Override
125    public boolean onMove(int oldPosition, int newPosition) {
126        // Make sure the row at newPosition is present in the window
127        if (mWindow == null || newPosition < mWindow.getStartPosition() ||
128                newPosition >= (mWindow.getStartPosition() + mWindow.getNumRows())) {
129            fillWindow(newPosition);
130        }
131
132        return true;
133    }
134
135    @Override
136    public int getCount() {
137        if (mCount == NO_COUNT) {
138            fillWindow(0);
139        }
140        return mCount;
141    }
142
143    private void fillWindow(int requiredPos) {
144        clearOrCreateWindow(getDatabase().getPath());
145
146        if (mCount == NO_COUNT) {
147            int startPos = DatabaseUtils.cursorPickFillWindowStartPosition(requiredPos, 0);
148            mCount = mQuery.fillWindow(mWindow, startPos, requiredPos, true);
149            mCursorWindowCapacity = mWindow.getNumRows();
150            if (Log.isLoggable(TAG, Log.DEBUG)) {
151                Log.d(TAG, "received count(*) from native_fill_window: " + mCount);
152            }
153        } else {
154            int startPos = DatabaseUtils.cursorPickFillWindowStartPosition(requiredPos,
155                    mCursorWindowCapacity);
156            mQuery.fillWindow(mWindow, startPos, requiredPos, false);
157        }
158    }
159
160    @Override
161    public int getColumnIndex(String columnName) {
162        // Create mColumnNameMap on demand
163        if (mColumnNameMap == null) {
164            String[] columns = mColumns;
165            int columnCount = columns.length;
166            HashMap<String, Integer> map = new HashMap<String, Integer>(columnCount, 1);
167            for (int i = 0; i < columnCount; i++) {
168                map.put(columns[i], i);
169            }
170            mColumnNameMap = map;
171        }
172
173        // Hack according to bug 903852
174        final int periodIndex = columnName.lastIndexOf('.');
175        if (periodIndex != -1) {
176            Exception e = new Exception();
177            Log.e(TAG, "requesting column name with table name -- " + columnName, e);
178            columnName = columnName.substring(periodIndex + 1);
179        }
180
181        Integer i = mColumnNameMap.get(columnName);
182        if (i != null) {
183            return i.intValue();
184        } else {
185            return -1;
186        }
187    }
188
189    @Override
190    public String[] getColumnNames() {
191        return mColumns;
192    }
193
194    @Override
195    public void deactivate() {
196        super.deactivate();
197        mDriver.cursorDeactivated();
198    }
199
200    @Override
201    public void close() {
202        super.close();
203        synchronized (this) {
204            mQuery.close();
205            mDriver.cursorClosed();
206        }
207    }
208
209    @Override
210    public boolean requery() {
211        if (isClosed()) {
212            return false;
213        }
214
215        synchronized (this) {
216            if (!mQuery.getDatabase().isOpen()) {
217                return false;
218            }
219
220            if (mWindow != null) {
221                mWindow.clear();
222            }
223            mPos = -1;
224            mCount = NO_COUNT;
225
226            mDriver.cursorRequeried(this);
227        }
228
229        try {
230            return super.requery();
231        } catch (IllegalStateException e) {
232            // for backwards compatibility, just return false
233            Log.w(TAG, "requery() failed " + e.getMessage(), e);
234            return false;
235        }
236    }
237
238    @Override
239    public void setWindow(CursorWindow window) {
240        super.setWindow(window);
241        mCount = NO_COUNT;
242    }
243
244    /**
245     * Changes the selection arguments. The new values take effect after a call to requery().
246     */
247    public void setSelectionArguments(String[] selectionArgs) {
248        mDriver.setBindArguments(selectionArgs);
249    }
250
251    /**
252     * Release the native resources, if they haven't been released yet.
253     */
254    @Override
255    protected void finalize() {
256        try {
257            // if the cursor hasn't been closed yet, close it first
258            if (mWindow != null) {
259                if (mStackTrace != null) {
260                    String sql = mQuery.getSql();
261                    int len = sql.length();
262                    StrictMode.onSqliteObjectLeaked(
263                        "Finalizing a Cursor that has not been deactivated or closed. " +
264                        "database = " + mQuery.getDatabase().getLabel() +
265                        ", table = " + mEditTable +
266                        ", query = " + sql.substring(0, (len > 1000) ? 1000 : len),
267                        mStackTrace);
268                }
269                close();
270            }
271        } finally {
272            super.finalize();
273        }
274    }
275}
276