Skip to content

Instantly share code, notes, and snippets.

@PierceZ
Created January 29, 2017 15:15
Show Gist options
  • Save PierceZ/664616390dc702a1fa51ed351c7a37d4 to your computer and use it in GitHub Desktop.
Save PierceZ/664616390dc702a1fa51ed351c7a37d4 to your computer and use it in GitHub Desktop.
Example of greenDAO migrations
public class DatabaseUpgradeHelper extends DaoMaster.OpenHelper {
public DatabaseUpgradeHelper(Context context, String name) {
super(context, name);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
List<Migration> migrations = getMigrations();
// Only run migrations past the old version
for (Migration migration : migrations) {
if (oldVersion < migration.getVersion()) {
migration.runMigration(db);
}
}
}
private List<Migration> getMigrations() {
List<Migration> migrations = new ArrayList<>();
migrations.add(new MigrationV2());
migrations.add(new MigrationV3());
// Sorting just to be safe, in case other people add migrations in the wrong order.
Comparator<Migration> migrationComparator = new Comparator<Migration>() {
@Override
public int compare(Migration m1, Migration m2) {
return m1.getVersion().compareTo(m2.getVersion());
}
};
Collections.sort(migrations, migrationComparator);
return migrations;
}
private static class MigrationV2 implements Migration {
@Override
public Integer getVersion() {
return 2;
}
@Override
public void runMigration(Database db) {
//Adding new table
UserDao.createTable(db, false);
}
}
private static class MigrationV3 implements Migration {
@Override
public Integer getVersion() {
return 3;
}
@Override
public void runMigration(Database db) {
// Add new column to user table
db.execSQL("ALTER TABLE " + UserDao.TABLENAME + " ADD COLUMN " + UserDao.Properties.Age.columnName + " INTEGER");
}
}
private interface Migration {
Integer getVersion();
void runMigration(Database db);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment