Skip to content

Instantly share code, notes, and snippets.

@YannickGagnon
Created April 5, 2013 16:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save YannickGagnon/5320593 to your computer and use it in GitHub Desktop.
Save YannickGagnon/5320593 to your computer and use it in GitHub Desktop.
HTML5 WebSql Database Migration
var migrationManager = (function() {
/**
* Our db instance
* @type {Database}
*/
var db = null;
/**
* Our versions, add a version when needed
* @type {Array}
*/
var versions = ['1.0', '1.1'];
return {
/**
* Establish a db connection
* @param {string} name of the database
* @param {string} version number, you must use '' or null to work
* @param {string} displayName self-describing right? ;)
* @param {integer} size set to null, 0 or else
*/
connect: function(name, version, displayName, size) {
db = window.openDatabase(name, version || '', displayName, size || 0);
},
/**
* Check if our db version is up2date
*/
checkDb: function() {
var fromVersionIndex = null;
var currentVersion = db.version;
var latestVersion = versions[versions.length - 1];
// If we already have the lastest version,
// bail out immediately
if (currentVersion !== latestVersion) {
// Check for empty version, meaning empty db
if (currentVersion === '') {
fromVersionIndex = 0;
} else if (currentVersion !== '') {
fromVersionIndex = versions.indexOf(currentVersion);
if (fromVersionIndex === -1) {
console.log("migrationManager Error: Can't locate version: " + currentVersion + " in versions stack: [" + versions.join(', ') + "]");
return;
}
fromVersionIndex += 1;
}
// Change version from current to latest and run all the upgrades
db.changeVersion(currentVersion, lastestVersion, function(transaction) {
for (var i = fromVersionIndex; i < versions.length; i++) {
this.upgradeDbToVersion(transaction, versions[i]);
}
}.bind(this));
}
},
/**
* Execute some SQL queries depending on requested version
* @param {SQLTransaction} transaction object used to run queries
* @param {string} version current upgrade version request
*/
upgradeDbToVersion: function(transaction, version) {
// Simple switch for running chunks of SQL Queries
switch (version) {
case '1.0':
transaction.executeSql('CREATE TABLE "event" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "type" integer NOT NULL, "fullDate" text(30,0) NOT NULL);');
break;
case '1.1':
transaction.executeSql('ALTER TABLE "event" ADD "name" text(255,0) NOT NULL;');
break;
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment