Skip to content

Instantly share code, notes, and snippets.

@jamesmorgan
Created November 7, 2011 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jamesmorgan/1345937 to your computer and use it in GitHub Desktop.
Save jamesmorgan/1345937 to your computer and use it in GitHub Desktop.
ExampleOfORMLIteCustomDatabaseUpgradeStrategy
/**
* This is called when your application is upgraded and it has a higher version number. This allows you to adjust the various data to
* match the new version number.
*/
@Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, int oldVersion, final int newVersion) {
Logger.i(LOG_TAG, "onUpgrade, oldVersion=[%s], newVersion=[%s]", oldVersion, newVersion);
try {
// Simply loop round until newest version has been reached and add the appropriate migration
while (++oldVersion <= newVersion) {
switch (oldVersion) {
case 2: {
// Add migration for version 2 if required
UpgradeHelper.addUpgrade(2);
// Domain objects can still be created as normal with ORMLite
TableUtils.createTableIfNotExists(connectionSource, PlayerStats.class);
break;
}
case 3: {
// Add migration for version 3 if required
UpgradeHelper.addUpgrade(3);
break;
}
}
}
// Get all the available updates
final List<String> availableUpdates = UpgradeHelper.availableUpdates(this.context.getResources());
Logger.d(LOG_TAG, "Found a total of %s update statements", availableUpdates.size());
for (final String statement : availableUpdates) {
db.beginTransaction();
try {
Logger.d(LOG_TAG, "Executing statement: %s", statement);
db.execSQL(statement);
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}
}
}
catch (final SQLException e) {
Logger.e(LOG_TAG, "Can't migrate databases, bootstrap database, data will be lost", e);
// Completely resource the database on failure, you would need to attempt to drop all existing tables in your onCreate method
onCreate(db, connectionSource);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment