Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrading the SQLite Database of a Production Android App, is this Correct?

As the title says, I have a production Android app with about 1000 installs. I had to make a DB change in SQLite, up to this point the version of the SQLite DB has been set to version "1".

Hopefully I explain the code below sufficiently in the comments, this code resides in my SQLiteOpenHelper Class so the onUpgrade method is part of the Class:

// Provides an upgrade path for the DB when the apps version is updated.
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // First version of the DB was 1. Logic: each if statement will
        // alter the DB cumulatively based on the version code. So, if the
        // newVersion was version 3, there would be two if statements, one
        // for oldVersion 1 and one for oldVersion 2. oldVersion 2 will
        // contain the logic for upgrading from version 2 to 3, while
        // oldVersion 1 will contain a combination of alter statements
        // allowing the database to upgrade from version 1 directly to
        // version 3.
        if (oldVersion == 1) {
            db.execSQL("ALTER TABLE plans ADD COLUMN " + App.CURRENCYCODE
                    + " TEXT");
            Locale locale = Locale.getDefault();
            ContentValues content_values = new ContentValues();
            content_values.put(App.CURRENCYCODE, locale.toString());

            db.update(App.DBPLANS, content_values, App.ID + " > ?", new String[] {
                    "0"
            });
        }

        if (oldVersion == 2) {
            // Placeholder for next database upgrade instructions.
        }
    }

Please let me know if there are any pitfalls here. So far, it's tested fine, though I'm very concerned about messing up my first DB upgrade. I have a 1,000 users or so, I'd hate to lose them all.

Thanks again!

like image 791
AutoM8R Avatar asked Nov 02 '12 01:11

AutoM8R


1 Answers

When I need to update a database like this, I typically do it with a switch statement where cases fall through to one another, such as:

switch (oldVersion) {
    case 1:
        // update to version 2
        // do _not_ break; -- fall through!
    case 2:
        // update to version 3
        // again, do not break;
    case 3:
        // you're already up to date

The benefits to this is you do not end up repeating your update statements in multiple if-statements as you continue to change the database, and adding a database update requires only adding a new case statement, not updating multiple blocks of code.

There are sometimes exceptions to this, such as a column added in one version but then deleted in a future one, so you need to pay attention as you go.

like image 83
mah Avatar answered Sep 24 '22 18:09

mah