From dc162a9ac818528f4f3c216eb837ab467895f022 Mon Sep 17 00:00:00 2001 From: cpfeiffer Date: Fri, 4 Mar 2016 23:19:44 +0100 Subject: [PATCH] Only add column if it doesn't exist yet Column can exist if there down- and upgrades --- .../freeyourgadget/gadgetbridge/database/DBHelper.java | 8 ++++++++ .../gadgetbridge/database/schema/ActivityDBUpdate_6.java | 9 ++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/DBHelper.java b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/DBHelper.java index a5fed010..b9b679bf 100644 --- a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/DBHelper.java +++ b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/DBHelper.java @@ -1,6 +1,7 @@ package nodomain.freeyourgadget.gadgetbridge.database; import android.content.Context; +import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; @@ -70,6 +71,13 @@ public class DBHelper { db.execSQL(statement); } + public static boolean existsColumn(String tableName, String columnName, SQLiteDatabase db) { + try (Cursor res = db.rawQuery("PRAGMA table_info('" + tableName + "')", null)) { + int result = res.getColumnIndex(columnName); + return result != -1; + } + } + /** * WITHOUT ROWID is only available with sqlite 3.8.2, which is available * with Lollipop and later. diff --git a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/schema/ActivityDBUpdate_6.java b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/schema/ActivityDBUpdate_6.java index 483f556d..b6d157c9 100644 --- a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/schema/ActivityDBUpdate_6.java +++ b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/database/schema/ActivityDBUpdate_6.java @@ -2,6 +2,7 @@ package nodomain.freeyourgadget.gadgetbridge.database.schema; import android.database.sqlite.SQLiteDatabase; +import nodomain.freeyourgadget.gadgetbridge.database.DBHelper; import nodomain.freeyourgadget.gadgetbridge.database.DBUpdateScript; import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_CUSTOM_SHORT; @@ -13,9 +14,11 @@ import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.TABLE_GB public class ActivityDBUpdate_6 implements DBUpdateScript { @Override public void upgradeSchema(SQLiteDatabase db) { - String ADD_COLUMN_CUSTOM_SHORT = "ALTER TABLE " + TABLE_GBACTIVITYSAMPLES + " ADD COLUMN " - + KEY_CUSTOM_SHORT + " INT;"; - db.execSQL(ADD_COLUMN_CUSTOM_SHORT); + if (!DBHelper.existsColumn(TABLE_GBACTIVITYSAMPLES, KEY_CUSTOM_SHORT, db)) { + String ADD_COLUMN_CUSTOM_SHORT = "ALTER TABLE " + TABLE_GBACTIVITYSAMPLES + " ADD COLUMN " + + KEY_CUSTOM_SHORT + " INT;"; + db.execSQL(ADD_COLUMN_CUSTOM_SHORT); + } } @Override