Duplicate column name when updating SQLite for a new column

I get an inconsistent, nonreproducible crash when users upgrade a new version of the local SQLite DB when they upgrade the application.

Fatal Exception: android.database.sqlite.SQLiteException: duplicate column name: upload_pending (code 1): , while compiling: ALTER TABLE purchases ADD COLUMN upload_pending TINYINT DEFAULT 0
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
    (duplicate column name: upload_pending (code 1): , while compiling: ALTER TABLE purchases ADD COLUMN upload_pending TINYINT DEFAULT 0)
#################################################################

The column is new to this version of the application, and this suggests that the most likely error is that the SQLiteOpenHelper onUpgrade method is called twice. Here is the update processing logic:

@Override   
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    for(int currentUpgrade = oldVersion + 1; currentUpgrade <= newVersion; currentUpgrade++) {
        switch(currentUpgrade) {
            case 2: 
                //upgrade to db v2
                break;
            case 3:
                //upgrade to db v3
                break;
            //etc
            case 7:
                methodWhichUpdatesAnotherTable(db);
                db.execSQL("ALTER TABLE " + Purchases.TABLE_NAME
                            + " ADD COLUMN " + Purchases.UPLOAD_PENDING + " TINYINT DEFAULT 0");
                break;
        }
    }
}

EDIT: I updated the code to include something important. The fault line is NOT the first ALTER operation in the update. First, a method is called that creates two different alter statements (in another table), and this part works fine. This seems to rule out the possibility that this is a concurrency problem, because if that happens, it will be the first to fail.

, , , - , Android onUpgrade oldVersion newVersion, 7 . , , onCreate, onUpgrade , , , .

, , 1% , , . - , , , . !

+4
1

. , oldVersions 4 10. - , CREATE TABLE ALTER TABLE ADD COLUMN oldVersions pre 4:

if ( oldVersion < 4 && newVersion >= 4 ) { 
    TestTableDao.createTable( db, true );
}

if ( oldVersion < 10 && newVersion >= 10 ) { 
   db.execSQL( "ALTER TABLE TEXT_TABLE ADD COLUMN NEW_COLUMN TEXT" );
}

oldVersion :

 if ( oldVersion < 10 && newVersion >= 10 ) { 
   if( oldVersion >=4 )
       db.execSQL( "ALTER TABLE TEXT_TABLE ADD COLUMN NEW_COLUMN TEXT" );
}

, - .

+1

Source: https://habr.com/ru/post/1674609/


All Articles