Created
March 9, 2011 22:10
-
-
Save madmanlear/863118 to your computer and use it in GitHub Desktop.
Rails-like migrations for Titanium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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