GreenDAO模式更新和数据迁移?

我正在评估GreenDAO,以考虑我正在开发的商业Android应用程序,并希望确定架构更新的迁移path。

我是否正确地断言我将不得不编写提供onUpdate()的自定义OpenHelper,并根据新的模式提取转换和存储数据? 这个假设提出了一些有趣的问题,围绕命令和责任划分。

我还没有find有关GreenDAO的模式更新和数据迁移的任何文档。

这里有一些关于这个主题的博客文章:

  1. 审查greenDAO
  2. 第1部分 – 模式生成
  3. 第2部分 – 模式迁移
  4. 第3部分 – testing模式迁移

你假设正确。 今天在不同的模式版本之间没有更改跟踪。 因此,在进行模式升级时,您需要自己编写SQL。

考虑pleonasmik的方法(顺便说一下,谢谢,这真的很有帮助),我创build了一个MigrationHelper类。

怎么运行的:

  1. class级抓住你所有的道士
  2. 根据旧版本的scheme( generateTempTables方法)创build临时表
  3. 将所有数据导入到这个新表( generateTempTables方法)
  4. 删除旧版本的所有表( DaoMaster.dropAllTables方法)
  5. 创build新版本的表( DaoMaster.createAllTables方法)
  6. 从临时表更新新版本的表( restoreData方法)
  7. 删除所有临时表( restoreData方法)

迁移助手类:

 import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import com.crashlytics.android.Crashlytics; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.internal.DaoConfig; import greendao.DaoMaster; /** * 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; } } 

下面是一个例子,它应该如何在DaoMaster.java类中被调用:

 @Override 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); } 

我认为我对一个类似问题的回答可以帮助这种方法。 如果你真的需要迁移数据,我build议你,如果你例如需要处理一些限制的变化或SQLite不支持的东西,你自己写迁移。 例如,一个移民助手的例子(遵循我在链接回应中做的方法)可能是:

 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);"); } } 

这是@PedroOkawa与GreenDao 3. +一起使用的相同代码,带有固定的错误:

 import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import android.text.TextUtils; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.StandardDatabase; import org.greenrobot.greendao.internal.DaoConfig; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Createdby PedroOkawa and modified by MBH on 16/08/16. */ public final class MigrationHelper { public static void migrate(SQLiteDatabase sqliteDatabase, Class<? extends AbstractDao<?, ?>>... daoClasses) { StandardDatabase db = new StandardDatabase(sqliteDatabase); generateNewTablesIfNotExists(db, daoClasses); generateTempTables(db, daoClasses); dropAllTables(db, true, daoClasses); createAllTables(db, false, daoClasses); restoreData(db, daoClasses); } public static void migrate(StandardDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) { generateNewTablesIfNotExists(db, daoClasses); generateTempTables(db, daoClasses); dropAllTables(db, true, daoClasses); createAllTables(db, false, daoClasses); restoreData(db, daoClasses); } private static void generateNewTablesIfNotExists(StandardDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) { reflectMethod(db, "createTable", true, daoClasses); } private static void generateTempTables(StandardDatabase 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"); StringBuilder insertTableStringBuilder = new StringBuilder(); insertTableStringBuilder.append("CREATE TEMP TABLE ").append(tempTableName); insertTableStringBuilder.append(" AS SELECT * FROM ").append(tableName).append(";"); db.execSQL(insertTableStringBuilder.toString()); } } private static void dropAllTables(StandardDatabase db, boolean ifExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) { reflectMethod(db, "dropTable", ifExists, daoClasses); } private static void createAllTables(StandardDatabase db, boolean ifNotExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) { reflectMethod(db, "createTable", ifNotExists, daoClasses); } /** * dao class already define the sql exec method, so just invoke it */ private static void reflectMethod(StandardDatabase db, String methodName, boolean isExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) { if (daoClasses.length < 1) { return; } try { for (Class cls : daoClasses) { Method method = cls.getDeclaredMethod(methodName, Database.class, boolean.class); method.invoke(null, db, isExists); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } private static void restoreData(StandardDatabase 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"); // get all columns from tempTable, take careful to use the columns list List<String> columns = getColumns(db, tempTableName); ArrayList<String> properties = new ArrayList<>(columns.size()); for (int j = 0; j < daoConfig.properties.length; j++) { String columnName = daoConfig.properties[j].columnName; if (columns.contains(columnName)) { properties.add(columnName); } } if (properties.size() > 0) { final String columnSQL = TextUtils.join(",", properties); StringBuilder insertTableStringBuilder = new StringBuilder(); insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" ("); insertTableStringBuilder.append(columnSQL); insertTableStringBuilder.append(") SELECT "); insertTableStringBuilder.append(columnSQL); insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";"); db.execSQL(insertTableStringBuilder.toString()); } StringBuilder dropTableStringBuilder = new StringBuilder(); dropTableStringBuilder.append("DROP TABLE ").append(tempTableName); db.execSQL(dropTableStringBuilder.toString()); } } private static List<String> getColumns(StandardDatabase db, String tableName) { List<String> columns = null; Cursor cursor = null; try { cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 0", null); if (null != cursor && cursor.getColumnCount() > 0) { columns = Arrays.asList(cursor.getColumnNames()); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); if (null == columns) columns = new ArrayList<>(); } return columns; } } 

用法是:

 @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { MigrationHelper.migrate(new StandardDatabase(sqLiteDatabase), UserDao.class, ItemDao.class); // OR you can use it like this (Dont use both it is example of 2 different usages) MigrationHelper.migrate(sqLiteDatabase, UserDao.class, ItemDao.class); } 

StandardDatabase可以在greendao中find,这是导入:

 import org.greenrobot.greendao.database.StandardDatabase; 

再次感谢@PedroOkawa 🙂

Pedro Okawa'的解决scheme是正确的,但是您需要编写“UpgradeHelper”来扩展“OpenHelper”,因为每次重新生成DAO代码时,DaoMaster都会被覆盖。

例:

 public class UpgradeHelper extends DaoMaster.OpenHelper { public UpgradeHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) { super(context, name, factory); } @Override 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, AnotherClassToGenerateDao.class); } 

}

对于那些希望更新greenDAO 3上的数据库模式版本的人,将其添加到您的应用程序的build.gradle文件上面的依赖项:

 apply plugin: 'org.greenrobot.greendao' greendao { schemaVersion 1 } 

如果你正在寻找一种方法来添加新的表到你的模式,而不删除你的用户的数据,并不需要转换任何现有的数据,看看我的答案这个问题的离散例子如何做到这一点greenDao。