GreenDAO資料庫版本升級
阿新 • • 發佈:2019-02-16
GreenDAO是一款非要流行的android平臺上的資料庫框架,效能優秀,程式碼簡潔。
初始化資料庫模型程式碼的時候需要使用java專案生成程式碼,依賴的jar包已經上傳到我的資源裡了,下載地址如下:http://download.csdn.net/detail/fancylovejava/8859203
專案開發中用到的就是GreenDAO資料庫框架,需要進行資料庫版本升級。
其實資料庫版本升級比較麻煩的就是資料的遷移,data migration。
資料庫版本升級有很多方法,按不同需求來處理。
本質上是去執行sql語句去建立臨時資料表,然後遷移資料,修改臨時表名等。
資料版本升級,為了便於維護程式碼可以先定義一個抽象類
public abstract class AbstractMigratorHelper {
public abstract void onUpgrade(SQLiteDatabase db);
}
然後讓自己更新資料庫邏輯的類繼承這個類
public class DBMigrationHelper6 extends AbstractMigratorHelper {
/* Upgrade from DB schema 6 to schema 7 , version numbers are just examples*/
public void onUpgrade(SQLiteDatabase db) {
/* Create a temporal table where you will copy all the data from the previous table that you need to modify with a non supported sqlite operation */
db.execSQL("CREATE TABLE " + "'post2' (" + //
"'_id' INTEGER PRIMARY KEY ," + // 0: id
"'POST_ID' INTEGER UNIQUE ," + // 1: postId
"'USER_ID' INTEGER," + // 2: userId
"'VERSION' INTEGER," + // 3: version
"'TYPE' TEXT," + // 4: type
"'MAGAZINE_ID' TEXT NOT NULL ," + // 5: magazineId
"'SERVER_TIMESTAMP' INTEGER," + // 6: serverTimestamp
"'CLIENT_TIMESTAMP' INTEGER," + // 7: clientTimestamp
"'MAGAZINE_REFERENCE' TEXT NOT NULL ," + // 8: magazineReference
"'POST_CONTENT' TEXT);"); // 9: postContent
/* Copy the data from one table to the new one */
db.execSQL("INSERT INTO post2 (_id, POST_ID, USER_ID, VERSION, TYPE, MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT)" +
" SELECT _id, POST_ID, USER_ID, VERSION, TYPE, MAGAZINE_ID, SERVER_TIMESTAMP, CLIENT_TIMESTAMP, MAGAZINE_REFERENCE, POST_CONTENT FROM post;");
/* Delete the previous table */
db.execSQL("DROP TABLE post");
/* Rename the just created table to the one that I have just deleted */
db.execSQL("ALTER TABLE post2 RENAME TO post");
/* Add Index/es if you want them */
db.execSQL("CREATE INDEX " + "IDX_post_USER_ID ON post" +
" (USER_ID);");
//Example sql statement
db.execSQL("ALTER TABLE user ADD COLUMN USERNAME TEXT");
}
}
最後在OpenHelper方法裡的OnUpgrade方法裡面處理,這裡方法呼叫的比較巧妙,借用國外大牛的程式碼複製下。
public static class UpgradeHelper extends OpenHelper {
public UpgradeHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
/**
* Here is where the calls to upgrade are executed
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* i represent the version where the user is now and the class named with this number implies that is upgrading from i to i++ schema */
for (int i = oldVersion; i < newVersion; i++) {
try {
/* New instance of the class that migrates from i version to i++ version named DBMigratorHelper{version that the db has on this moment} */
AbstractMigratorHelper migratorHelper = (AbstractMigratorHelper) Class.forName("com.nameofyourpackage.persistence.MigrationHelpers.DBMigrationHelper" + i).newInstance();
if (migratorHelper != null) {
/* Upgrade de db */
migratorHelper.onUpgrade(db);
}
} catch (ClassNotFoundException | ClassCastException | IllegalAccessException | InstantiationException e) {
Log.e(TAG, "Could not migrate from schema from schema: " + i + " to " + i++);
/* If something fail prevent the DB to be updated to future version if the previous version has not been upgraded successfully */
break;
}
}
}
}
上面已經做了資料的遷移,國外有個大牛封裝的程式碼摘抄下來:
/**
* Created by pokawa on 18/05/15.
*/
public class MigrationHelper {
private static final String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = "MIGRATION HELPER - CLASS DOESN'T MATCH WITH THE CURRENT PARAMETERS";
private static MigrationHelper instance;
public static MigrationHelper getInstance() {
if(instance == null) {
instance = new MigrationHelper();
}
return instance;
}
public void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
generateTempTables(db, daoClasses);
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
restoreData(db, daoClasses);
}
private void generateTempTables(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for(int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String divider = "";
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList<String> properties = new ArrayList<>();
StringBuilder createTableStringBuilder = new StringBuilder();
createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" (");
for(int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if(getColumns(db, tableName).contains(columnName)) {
properties.add(columnName);
String type = null;
try {
type = getTypeByClass(daoConfig.properties[j].type);
} catch (Exception exception) {
Crashlytics.logException(exception);
}
createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);
if(daoConfig.properties[j].primaryKey) {
createTableStringBuilder.append(" PRIMARY KEY");
}
divider = ",";
}
}
createTableStringBuilder.append(");");
db.execSQL(createTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
}
}
private void restoreData(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for(int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList<String> properties = new ArrayList();
for (int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if(getColumns(db, tempTableName).contains(columnName)) {
properties.add(columnName);
}
}
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
db.execSQL(insertTableStringBuilder.toString());
db.execSQL(dropTableStringBuilder.toString());
}
}
private String getTypeByClass(Class<?> type) throws Exception {
if(type.equals(String.class)) {
return "TEXT";
}
if(type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class)) {
return "INTEGER";
}
if(type.equals(Boolean.class)) {
return "BOOLEAN";
}
Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
Crashlytics.logException(exception);
throw exception;
}
private static List<String> getColumns(SQLiteDatabase db, String tableName) {
List<String> columns = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
if (cursor != null) {
columns = new ArrayList<>(Arrays.asList(cursor.getColumnNames()));
}
} catch (Exception e) {
Log.v(tableName, e.getMessage(), e);
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return columns;
}
}
然後在OnUpgrade方法裡面去呼叫
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by migrating all tables data");
MigrationHelper.getInstance().migrate(db,
UserDao.class,
ItemDao.class);
}
上面程式碼全是乾貨,記錄下來以備不時之需!