Index: sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java ================================================================== --- sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java +++ sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java @@ -1681,10 +1681,25 @@ } } finally { releaseReference(); } } + + /** + * Verifies that a SQL SELECT statement is valid by compiling it. + * If the SQL statement is not valid, this method will throw a {@link SQLiteException}. + * + * @param sql SQL to be validated + * @param cancellationSignal A signal to cancel the operation in progress, or null if none. + * If the operation is canceled, then {@link OperationCanceledException} will be thrown + * when the query is executed. + * @throws SQLiteException if {@code sql} is invalid + */ + public void validateSql(String sql, CancellationSignal cancellationSignal) { + getThreadSession().prepare(sql, + getThreadDefaultConnectionFlags(/* readOnly =*/ true), cancellationSignal, null); + } /** * Returns true if the database is opened as read only. * * @return True if database is opened as read only. Index: sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteOpenHelper.java ================================================================== --- sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteOpenHelper.java +++ sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteOpenHelper.java @@ -15,18 +15,19 @@ */ /* ** Modified to support SQLite extensions by the SQLite developers: ** sqlite-dev@sqlite.org. */ + package org.sqlite.database.sqlite; import android.content.Context; import org.sqlite.database.DatabaseErrorHandler; -import org.sqlite.database.DefaultDatabaseErrorHandler; import org.sqlite.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; +import java.io.File; /** * A helper class to manage database creation and version management. * *

You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and @@ -57,10 +58,11 @@ private final Context mContext; private final String mName; private final CursorFactory mFactory; private final int mNewVersion; + private final int mMinimumSupportedVersion; private SQLiteDatabase mDatabase; private boolean mIsInitializing; private boolean mEnableWriteAheadLogging; private final DatabaseErrorHandler mErrorHandler; @@ -99,17 +101,46 @@ * @param errorHandler the {@link DatabaseErrorHandler} to be used when sqlite reports database * corruption, or null to use the default error handler. */ public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { + this(context, name, factory, version, 0, errorHandler); + } + + /** + * Same as {@link #SQLiteOpenHelper(Context, String, CursorFactory, int, DatabaseErrorHandler)} + * but also accepts an integer minimumSupportedVersion as a convenience for upgrading very old + * versions of this database that are no longer supported. If a database with older version that + * minimumSupportedVersion is found, it is simply deleted and a new database is created with the + * given name and version + * + * @param context to use to open or create the database + * @param name the name of the database file, null for a temporary in-memory database + * @param factory to use for creating cursor objects, null for default + * @param version the required version of the database + * @param minimumSupportedVersion the minimum version that is supported to be upgraded to + * {@code version} via {@link #onUpgrade}. If the current database version is lower + * than this, database is simply deleted and recreated with the version passed in + * {@code version}. {@link #onBeforeDelete} is called before deleting the database + * when this happens. This is 0 by default. + * @param errorHandler the {@link DatabaseErrorHandler} to be used when sqlite reports database + * corruption, or null to use the default error handler. + * @see #onBeforeDelete(SQLiteDatabase) + * @see #SQLiteOpenHelper(Context, String, CursorFactory, int, DatabaseErrorHandler) + * @see #onUpgrade(SQLiteDatabase, int, int) + * @hide + */ + public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, + int minimumSupportedVersion, DatabaseErrorHandler errorHandler) { if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version); mContext = context; mName = name; mFactory = factory; mNewVersion = version; mErrorHandler = errorHandler; + mMinimumSupportedVersion = Math.max(0, minimumSupportedVersion); } /** * Return the name of the SQLite database being opened, as given to * the constructor. @@ -224,11 +255,11 @@ final String path = mContext.getDatabasePath(mName).getPath(); db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY, mErrorHandler); } else { db = SQLiteDatabase.openOrCreateDatabase( - mName, mFactory, mErrorHandler + mName, mFactory, mErrorHandler ); } } catch (SQLiteException ex) { if (writable) { throw ex; @@ -248,25 +279,38 @@ if (db.isReadOnly()) { throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " + mNewVersion + ": " + mName); } - db.beginTransaction(); - try { - if (version == 0) { - onCreate(db); - } else { - if (version > mNewVersion) { - onDowngrade(db, version, mNewVersion); - } else { - onUpgrade(db, version, mNewVersion); - } - } - db.setVersion(mNewVersion); - db.setTransactionSuccessful(); - } finally { - db.endTransaction(); + if (version > 0 && version < mMinimumSupportedVersion) { + File databaseFile = new File(db.getPath()); + onBeforeDelete(db); + db.close(); + if (SQLiteDatabase.deleteDatabase(databaseFile)) { + mIsInitializing = false; + return getDatabaseLocked(writable); + } else { + throw new IllegalStateException("Unable to delete obsolete database " + + mName + " with version " + version); + } + } else { + db.beginTransaction(); + try { + if (version == 0) { + onCreate(db); + } else { + if (version > mNewVersion) { + onDowngrade(db, version, mNewVersion); + } else { + onUpgrade(db, version, mNewVersion); + } + } + db.setVersion(mNewVersion); + db.setTransactionSuccessful(); + } finally { + db.endTransaction(); + } } } onOpen(db); @@ -295,27 +339,41 @@ mDatabase = null; } } /** - * Called when the database connection is being configured, to enable features - * such as write-ahead logging or foreign key support. + * Called when the database connection is being configured, to enable features such as + * write-ahead logging or foreign key support. + *

+ * This method is called before {@link #onCreate}, {@link #onUpgrade}, {@link #onDowngrade}, or + * {@link #onOpen} are called. It should not modify the database except to configure the + * database connection as required. + *

*

- * This method is called before {@link #onCreate}, {@link #onUpgrade}, - * {@link #onDowngrade}, or {@link #onOpen} are called. It should not modify - * the database except to configure the database connection as required. - *

- * This method should only call methods that configure the parameters of the - * database connection, such as {@link SQLiteDatabase#enableWriteAheadLogging} - * {@link SQLiteDatabase#setForeignKeyConstraintsEnabled}, - * {@link SQLiteDatabase#setLocale}, {@link SQLiteDatabase#setMaximumSize}, - * or executing PRAGMA statements. + * This method should only call methods that configure the parameters of the database + * connection, such as {@link SQLiteDatabase#enableWriteAheadLogging} + * {@link SQLiteDatabase#setForeignKeyConstraintsEnabled}, {@link SQLiteDatabase#setLocale}, + * {@link SQLiteDatabase#setMaximumSize}, or executing PRAGMA statements. *

* * @param db The database. */ public void onConfigure(SQLiteDatabase db) {} + + /** + * Called before the database is deleted when the version returned by + * {@link SQLiteDatabase#getVersion()} is lower than the minimum supported version passed (if at + * all) while creating this helper. After the database is deleted, a fresh database with the + * given version is created. This will be followed by {@link #onConfigure(SQLiteDatabase)} and + * {@link #onCreate(SQLiteDatabase)} being called with a new SQLiteDatabase object + * + * @param db the database opened with this helper + * @see #SQLiteOpenHelper(Context, String, CursorFactory, int, int, DatabaseErrorHandler) + * @hide + */ + public void onBeforeDelete(SQLiteDatabase db) { + } /** * Called when the database is created for the first time. This is where the * creation of tables and the initial population of the tables should happen. * Index: sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteQueryBuilder.java ================================================================== --- sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteQueryBuilder.java +++ sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteQueryBuilder.java @@ -388,12 +388,11 @@ // originally specified. An attacker cannot create an expression that // would escape the SQL expression while maintaining balanced parentheses // in both the wrapped and original forms. String sqlForValidation = buildQuery(projectionIn, "(" + selection + ")", groupBy, having, sortOrder, limit); - validateQuerySql(db, sqlForValidation, - cancellationSignal); // will throw if query is invalid + db.validateSql(sqlForValidation, cancellationSignal); // will throw if query is invalid } String sql = buildQuery( projectionIn, selection, groupBy, having, sortOrder, limit); @@ -405,20 +404,10 @@ mFactory, sql, selectionArgs, SQLiteDatabase.findEditTable(mTables), cancellationSignal); // will throw if query is invalid } - /** - * Verifies that a SQL SELECT statement is valid by compiling it. - * If the SQL statement is not valid, this method will throw a {@link SQLiteException}. - */ - private void validateQuerySql(SQLiteDatabase db, String sql, - CancellationSignal cancellationSignal) { - db.getThreadSession().prepare(sql, - db.getThreadDefaultConnectionFlags(true /*readOnly*/), cancellationSignal, null); - } - /** * Construct a SELECT statement suitable for use in a group of * SELECT statements that will be joined through UNION operators * in buildUnionQuery. * Index: sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteStatement.java ================================================================== --- sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteStatement.java +++ sqlite3/src/main/java/org/sqlite/database/sqlite/SQLiteStatement.java @@ -37,11 +37,11 @@ /** * Execute this SQL statement, if it is not a SELECT / INSERT / DELETE / UPDATE, for example * CREATE / DROP table, view, trigger, index etc. * - * @throws org.sqlite.database.SQLException If the SQL string is invalid for + * @throws android.database.SQLException If the SQL string is invalid for * some reason */ public void execute() { acquireReference(); try { @@ -57,11 +57,11 @@ /** * Execute this SQL statement, if the the number of rows affected by execution of this SQL * statement is of any importance to the caller - for example, UPDATE / DELETE SQL statements. * * @return the number of rows affected by this SQL statement execution. - * @throws org.sqlite.database.SQLException If the SQL string is invalid for + * @throws android.database.SQLException If the SQL string is invalid for * some reason */ public int executeUpdateDelete() { acquireReference(); try { @@ -79,11 +79,11 @@ * Execute this SQL statement and return the ID of the row inserted due to this call. * The SQL statement should be an INSERT for this to be a useful call. * * @return the row ID of the last row inserted, if this insert is successful. -1 otherwise. * - * @throws org.sqlite.database.SQLException If the SQL string is invalid for + * @throws android.database.SQLException If the SQL string is invalid for * some reason */ public long executeInsert() { acquireReference(); try { @@ -101,11 +101,11 @@ * Execute a statement that returns a 1 by 1 table with a numeric value. * For example, SELECT COUNT(*) FROM table; * * @return The result of the query. * - * @throws org.sqlite.database.sqlite.SQLiteDoneException if the query returns zero rows + * @throws android.database.sqlite.SQLiteDoneException if the query returns zero rows */ public long simpleQueryForLong() { acquireReference(); try { return getSession().executeForLong( @@ -122,11 +122,11 @@ * Execute a statement that returns a 1 by 1 table with a text value. * For example, SELECT COUNT(*) FROM table; * * @return The result of the query. * - * @throws org.sqlite.database.sqlite.SQLiteDoneException if the query returns zero rows + * @throws android.database.sqlite.SQLiteDoneException if the query returns zero rows */ public String simpleQueryForString() { acquireReference(); try { return getSession().executeForString( @@ -143,11 +143,11 @@ * Executes a statement that returns a 1 by 1 table with a blob value. * * @return A read-only file descriptor for a copy of the blob value, or {@code null} * if the value is null or could not be read for some reason. * - * @throws org.sqlite.database.sqlite.SQLiteDoneException if the query returns zero rows + * @throws android.database.sqlite.SQLiteDoneException if the query returns zero rows */ public ParcelFileDescriptor simpleQueryForBlobFileDescriptor() { acquireReference(); try { return getSession().executeForBlobFileDescriptor( DELETED sqlite3/src/main/java/org/sqlite/database/sqlite/SqliteWrapper.java Index: sqlite3/src/main/java/org/sqlite/database/sqlite/SqliteWrapper.java ================================================================== --- sqlite3/src/main/java/org/sqlite/database/sqlite/SqliteWrapper.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2008 Esmertec AG. - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* -** Modified to support SQLite extensions by the SQLite developers: -** sqlite-dev@sqlite.org. -*/ - -package org.sqlite.database.sqlite; - -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import org.sqlite.database.sqlite.SQLiteException; -import android.net.Uri; -import android.util.Log; -import android.widget.Toast; - -/** - * @hide - */ - -public final class SqliteWrapper { - private static final String TAG = "SqliteWrapper"; - private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE - = "unable to open database file"; - - private SqliteWrapper() { - // Forbidden being instantiated. - } - - // FIXME: need to optimize this method. - private static boolean isLowMemory(SQLiteException e) { - return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE); - } - - public static void checkSQLiteException(Context context, SQLiteException e) { - if (isLowMemory(e)) { - Toast.makeText(context, "low memory", Toast.LENGTH_SHORT).show(); - } else { - throw e; - } - } - - public static Cursor query(Context context, ContentResolver resolver, Uri uri, - String[] projection, String selection, String[] selectionArgs, String sortOrder) { - try { - return resolver.query(uri, projection, selection, selectionArgs, sortOrder); - } catch (SQLiteException e) { - Log.e(TAG, "Catch a SQLiteException when query: ", e); - checkSQLiteException(context, e); - return null; - } - } - - public static boolean requery(Context context, Cursor cursor) { - try { - return cursor.requery(); - } catch (SQLiteException e) { - Log.e(TAG, "Catch a SQLiteException when requery: ", e); - checkSQLiteException(context, e); - return false; - } - } - public static int update(Context context, ContentResolver resolver, Uri uri, - ContentValues values, String where, String[] selectionArgs) { - try { - return resolver.update(uri, values, where, selectionArgs); - } catch (SQLiteException e) { - Log.e(TAG, "Catch a SQLiteException when update: ", e); - checkSQLiteException(context, e); - return -1; - } - } - - public static int delete(Context context, ContentResolver resolver, Uri uri, - String where, String[] selectionArgs) { - try { - return resolver.delete(uri, where, selectionArgs); - } catch (SQLiteException e) { - Log.e(TAG, "Catch a SQLiteException when delete: ", e); - checkSQLiteException(context, e); - return -1; - } - } - - public static Uri insert(Context context, ContentResolver resolver, - Uri uri, ContentValues values) { - try { - return resolver.insert(uri, values); - } catch (SQLiteException e) { - Log.e(TAG, "Catch a SQLiteException when insert: ", e); - checkSQLiteException(context, e); - return null; - } - } -}