Skip to content

Instantly share code, notes, and snippets.

@madmanlear
Created March 9, 2011 22:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madmanlear/863118 to your computer and use it in GitHub Desktop.
Save madmanlear/863118 to your computer and use it in GitHub Desktop.
Rails-like migrations for Titanium
/*
Model methods below requires Joli.js: https://github.com/xavierlacot/joli.js
Requires a tables named 'migrations' with columns id & version
Database migrations
Each migration is attached to a timestamp
When the migration is run, a record is added to the migrations table so it isn't run again
The rollback function takes a string date and rolls back all migrations since that date and deletes the migration record
Usage:
Migrations.migrate();
Migrations.rollback('2011/03/08');
*/
Migrations = (function() {
var c = {};
c.versions = {
1299703938917: {
down: function() {
var record = models.settings.findOneBy('name', 'testing_migrations');
models.settings.deleteRecords(record.id);
},
up: function() {
var record = {
name: 'testing_migrations',
value: 1
};
models.settings.newRecord(record).save();
}
}
};
c.migrate = function() {
for(var i in c.versions) {
if(c.versions[i]) {
migration = models.migrations.findOneBy('version', i);
if(!migration) {
c.versions[i].up();
models.migrations.newRecord({version: i}).save();
}
}
}
};
c.rollback = function(the_date) {
var timestamp = new Date(the_date).getTime();
for(var i in c.versions) {
if(c.versions[i] && i >= timestamp) {
migration = models.migrations.findOneBy('version', i);
if(migration) {
c.versions[i].down();
models.migrations.deleteRecords(migration.id);
}
}
}
};
return c;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment