Home | History | Annotate | Download | only in sqlite
      1 /*
      2  * Copyright (C) 2007 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 
     17 package android.database.sqlite;
     18 
     19 import android.content.Context;
     20 import android.database.sqlite.SQLiteDatabase.CursorFactory;
     21 import android.util.Log;
     22 
     23 /**
     24  * A helper class to manage database creation and version management.
     25  *
     26  * <p>You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and
     27  * optionally {@link #onOpen}, and this class takes care of opening the database
     28  * if it exists, creating it if it does not, and upgrading it as necessary.
     29  * Transactions are used to make sure the database is always in a sensible state.
     30  *
     31  * <p>This class makes it easy for {@link android.content.ContentProvider}
     32  * implementations to defer opening and upgrading the database until first use,
     33  * to avoid blocking application startup with long-running database upgrades.
     34  *
     35  * <p>For an example, see the NotePadProvider class in the NotePad sample application,
     36  * in the <em>samples/</em> directory of the SDK.</p>
     37  *
     38  * <p class="note"><strong>Note:</strong> this class assumes
     39  * monotonically increasing version numbers for upgrades.  Also, there
     40  * is no concept of a database downgrade; installing a new version of
     41  * your app which uses a lower version number than a
     42  * previously-installed version will result in undefined behavior.</p>
     43  */
     44 public abstract class SQLiteOpenHelper {
     45     private static final String TAG = SQLiteOpenHelper.class.getSimpleName();
     46 
     47     private final Context mContext;
     48     private final String mName;
     49     private final CursorFactory mFactory;
     50     private final int mNewVersion;
     51 
     52     private SQLiteDatabase mDatabase = null;
     53     private boolean mIsInitializing = false;
     54 
     55     /**
     56      * Create a helper object to create, open, and/or manage a database.
     57      * This method always returns very quickly.  The database is not actually
     58      * created or opened until one of {@link #getWritableDatabase} or
     59      * {@link #getReadableDatabase} is called.
     60      *
     61      * @param context to use to open or create the database
     62      * @param name of the database file, or null for an in-memory database
     63      * @param factory to use for creating cursor objects, or null for the default
     64      * @param version number of the database (starting at 1); if the database is older,
     65      *     {@link #onUpgrade} will be used to upgrade the database
     66      */
     67     public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
     68         if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);
     69 
     70         mContext = context;
     71         mName = name;
     72         mFactory = factory;
     73         mNewVersion = version;
     74     }
     75 
     76     /**
     77      * Create and/or open a database that will be used for reading and writing.
     78      * The first time this is called, the database will be opened and
     79      * {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
     80      * called.
     81      *
     82      * <p>Once opened successfully, the database is cached, so you can
     83      * call this method every time you need to write to the database.
     84      * (Make sure to call {@link #close} when you no longer need the database.)
     85      * Errors such as bad permissions or a full disk may cause this method
     86      * to fail, but future attempts may succeed if the problem is fixed.</p>
     87      *
     88      * <p class="caution">Database upgrade may take a long time, you
     89      * should not call this method from the application main thread, including
     90      * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
     91      *
     92      * @throws SQLiteException if the database cannot be opened for writing
     93      * @return a read/write database object valid until {@link #close} is called
     94      */
     95     public synchronized SQLiteDatabase getWritableDatabase() {
     96         if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
     97             return mDatabase;  // The database is already open for business
     98         }
     99 
    100         if (mIsInitializing) {
    101             throw new IllegalStateException("getWritableDatabase called recursively");
    102         }
    103 
    104         // If we have a read-only database open, someone could be using it
    105         // (though they shouldn't), which would cause a lock to be held on
    106         // the file, and our attempts to open the database read-write would
    107         // fail waiting for the file lock.  To prevent that, we acquire the
    108         // lock on the read-only database, which shuts out other users.
    109 
    110         boolean success = false;
    111         SQLiteDatabase db = null;
    112         if (mDatabase != null) mDatabase.lock();
    113         try {
    114             mIsInitializing = true;
    115             if (mName == null) {
    116                 db = SQLiteDatabase.create(null);
    117             } else {
    118                 db = mContext.openOrCreateDatabase(mName, 0, mFactory);
    119             }
    120 
    121             int version = db.getVersion();
    122             if (version != mNewVersion) {
    123                 db.beginTransaction();
    124                 try {
    125                     if (version == 0) {
    126                         onCreate(db);
    127                     } else {
    128                         if (version > mNewVersion) {
    129                             Log.wtf(TAG, "Can't downgrade read-only database from version " +
    130                                     version + " to " + mNewVersion + ": " + db.getPath());
    131                         }
    132                         onUpgrade(db, version, mNewVersion);
    133                     }
    134                     db.setVersion(mNewVersion);
    135                     db.setTransactionSuccessful();
    136                 } finally {
    137                     db.endTransaction();
    138                 }
    139             }
    140 
    141             onOpen(db);
    142             success = true;
    143             return db;
    144         } finally {
    145             mIsInitializing = false;
    146             if (success) {
    147                 if (mDatabase != null) {
    148                     try { mDatabase.close(); } catch (Exception e) { }
    149                     mDatabase.unlock();
    150                 }
    151                 mDatabase = db;
    152             } else {
    153                 if (mDatabase != null) mDatabase.unlock();
    154                 if (db != null) db.close();
    155             }
    156         }
    157     }
    158 
    159     /**
    160      * Create and/or open a database.  This will be the same object returned by
    161      * {@link #getWritableDatabase} unless some problem, such as a full disk,
    162      * requires the database to be opened read-only.  In that case, a read-only
    163      * database object will be returned.  If the problem is fixed, a future call
    164      * to {@link #getWritableDatabase} may succeed, in which case the read-only
    165      * database object will be closed and the read/write object will be returned
    166      * in the future.
    167      *
    168      * <p class="caution">Like {@link #getWritableDatabase}, this method may
    169      * take a long time to return, so you should not call it from the
    170      * application main thread, including from
    171      * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
    172      *
    173      * @throws SQLiteException if the database cannot be opened
    174      * @return a database object valid until {@link #getWritableDatabase}
    175      *     or {@link #close} is called.
    176      */
    177     public synchronized SQLiteDatabase getReadableDatabase() {
    178         if (mDatabase != null && mDatabase.isOpen()) {
    179             return mDatabase;  // The database is already open for business
    180         }
    181 
    182         if (mIsInitializing) {
    183             throw new IllegalStateException("getReadableDatabase called recursively");
    184         }
    185 
    186         try {
    187             return getWritableDatabase();
    188         } catch (SQLiteException e) {
    189             if (mName == null) throw e;  // Can't open a temp database read-only!
    190             Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
    191         }
    192 
    193         SQLiteDatabase db = null;
    194         try {
    195             mIsInitializing = true;
    196             String path = mContext.getDatabasePath(mName).getPath();
    197             db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
    198             if (db.getVersion() != mNewVersion) {
    199                 throw new SQLiteException("Can't upgrade read-only database from version " +
    200                         db.getVersion() + " to " + mNewVersion + ": " + path);
    201             }
    202 
    203             onOpen(db);
    204             Log.w(TAG, "Opened " + mName + " in read-only mode");
    205             mDatabase = db;
    206             return mDatabase;
    207         } finally {
    208             mIsInitializing = false;
    209             if (db != null && db != mDatabase) db.close();
    210         }
    211     }
    212 
    213     /**
    214      * Close any open database object.
    215      */
    216     public synchronized void close() {
    217         if (mIsInitializing) throw new IllegalStateException("Closed during initialization");
    218 
    219         if (mDatabase != null && mDatabase.isOpen()) {
    220             mDatabase.close();
    221             mDatabase = null;
    222         }
    223     }
    224 
    225     /**
    226      * Called when the database is created for the first time. This is where the
    227      * creation of tables and the initial population of the tables should happen.
    228      *
    229      * @param db The database.
    230      */
    231     public abstract void onCreate(SQLiteDatabase db);
    232 
    233     /**
    234      * Called when the database needs to be upgraded. The implementation
    235      * should use this method to drop tables, add tables, or do anything else it
    236      * needs to upgrade to the new schema version.
    237      *
    238      * <p>The SQLite ALTER TABLE documentation can be found
    239      * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
    240      * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
    241      * you can use ALTER TABLE to rename the old table, then create the new table and then
    242      * populate the new table with the contents of the old table.
    243      *
    244      * @param db The database.
    245      * @param oldVersion The old database version.
    246      * @param newVersion The new database version.
    247      */
    248     public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
    249 
    250     /**
    251      * Called when the database has been opened.  The implementation
    252      * should check {@link SQLiteDatabase#isReadOnly} before updating the
    253      * database.
    254      *
    255      * @param db The database.
    256      */
    257     public void onOpen(SQLiteDatabase db) {}
    258 }
    259