Skip to content

Instantly share code, notes, and snippets.

@ericdagenais
Forked from madmanlear/titanium_migrations.js
Created December 5, 2011 00:11
Show Gist options
  • Save ericdagenais/1431741 to your computer and use it in GitHub Desktop.
Save ericdagenais/1431741 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