Skip to content

Commit

Permalink
added migrations management capacity
Browse files Browse the repository at this point in the history
  • Loading branch information
xavierlacot committed Feb 19, 2011
1 parent 0e0f25b commit 982df9e
Showing 1 changed file with 56 additions and 3 deletions.
59 changes: 56 additions & 3 deletions joli.js
Expand Up @@ -151,7 +151,7 @@ joli.Connection = function(database) {

joli.Connection.prototype = {
execute: function(query) {
// Titanium.API.log('debug', query);
Titanium.API.log('info', query);
return this.database.execute(query);
},

Expand All @@ -161,6 +161,38 @@ joli.Connection.prototype = {
};


/**
* Migration description
*/
joli.migration = function(options) {
var defaults = {
tableName: 'migration'
};

joli.setOptions.call(this, options, defaults);
this.table = this.options.tableName;
};

joli.migration.prototype = {
getVersion: function() {
var q = new joli.query().select().from(this.table).order('version desc');
var version = q.execute();

if (version.length > 0) {
return version[0].version;
} else {
var q = new joli.query().insertInto(this.table).values({ version: 0 });
q.execute();
return 0;
}
},

setVersion: function(version) {
var q = new joli.query().update(this.table).set({ version: version });
q.execute();
}
};

/**
* Model description
*/
Expand Down Expand Up @@ -202,6 +234,10 @@ joli.model.prototype = {
q.order(constraints.order);
}

if (constraints.limit) {
q.limit(constraints.limit);
}

return q.execute();
},

Expand Down Expand Up @@ -306,6 +342,7 @@ joli.model.prototype = {

joli.Models = function() {
this.models = {};
this.migration = new joli.migration({ tableName: 'migration' });
};

joli.Models.prototype = {
Expand Down Expand Up @@ -333,6 +370,22 @@ joli.Models.prototype = {
});
},

migrate: function(version) {
// create migration table
var query = 'CREATE TABLE IF NOT EXISTS ' + this.migration.table + ' (version)';
joli.connection.execute(query);

if (this.migration.getVersion() < version) {
joli.each(this.models, function(model, modelName) {
var query = 'DROP TABLE IF EXISTS ' + modelName;
joli.connection.execute(query);
});

// insert migration
this.migration.setVersion(version);
}
},

set: function(table, model) {
this.models[table] = model;
}
Expand Down Expand Up @@ -428,7 +481,7 @@ joli.query.prototype = {

return 'select ' + this.data.select_columns + ' from ' + this.data.from + join;
case 'update':
return 'update ' + this.data.from + ' set ' + this.data.values.join(', ');
return 'update ' + this.data.from + ' set ' + this.data.set.join(', ');
default:
throw("Operation type Error. joli.query operation type must be an insert, a delete, a select or an update.");
}
Expand Down Expand Up @@ -642,4 +695,4 @@ joli.record.prototype = {

return true;
}
};
};

0 comments on commit 982df9e

Please sign in to comment.