2014-04-08 16:25:57 -04:00
|
|
|
var _ = require('lodash');
|
|
|
|
|
|
|
|
// The "SchemaCompiler" takes all of the query statements which have been
|
|
|
|
// gathered in the "SchemaBuilder" and turns them into an array of
|
|
|
|
// properly formatted / bound query strings.
|
2014-04-09 10:11:41 -04:00
|
|
|
function SchemaCompiler(builder) {
|
|
|
|
this.builder = builder;
|
2014-04-08 16:25:57 -04:00
|
|
|
this.formatter = new this.Formatter();
|
|
|
|
this.sequence = [];
|
|
|
|
}
|
|
|
|
|
2014-04-09 10:11:41 -04:00
|
|
|
SchemaCompiler.prototype.toSQL = function() {
|
|
|
|
var sequence = this.builder._sequence;
|
|
|
|
for (var i = 0, l = sequence.length; i < l; i++) {
|
|
|
|
var query = sequence[i];
|
|
|
|
this[query.method].apply(this, query.args);
|
|
|
|
}
|
|
|
|
return this.sequence;
|
|
|
|
};
|
|
|
|
|
2014-04-08 16:25:57 -04:00
|
|
|
// Push a new query onto the compiled "sequence" stack,
|
|
|
|
// creating a new formatter, returning the compiler.
|
2014-04-09 10:11:41 -04:00
|
|
|
SchemaCompiler.prototype.pushQuery = function(query) {
|
2014-04-08 16:25:57 -04:00
|
|
|
if (_.isString(query)) {
|
|
|
|
query = {sql: query};
|
|
|
|
} else {
|
|
|
|
query = query;
|
|
|
|
}
|
|
|
|
query.bindings = this.formatter.bindings;
|
|
|
|
this.sequence.push(query);
|
|
|
|
this.formatter = new this.Formatter();
|
|
|
|
};
|
|
|
|
|
|
|
|
SchemaCompiler.prototype.createTable = function(tableName, fn) {
|
2014-04-09 10:11:41 -04:00
|
|
|
new this.client.TableCompiler(this, new this.client.TableBuilder(tableName)._create(fn)).toSQL('create');
|
2014-04-08 16:25:57 -04:00
|
|
|
};
|
|
|
|
SchemaCompiler.prototype.alterTable = function(tableName, fn) {
|
2014-04-09 10:11:41 -04:00
|
|
|
new this.client.TableCompiler(this, new this.client.TableBuilder(tableName)._alter(fn)).toSQL('alter');
|
2014-04-08 16:25:57 -04:00
|
|
|
};
|
|
|
|
SchemaCompiler.prototype.dropTable = function(tableName) {
|
2014-04-09 10:11:41 -04:00
|
|
|
this.pushQuery('drop table ' + this.formatter.wrap(tableName));
|
2014-04-08 16:25:57 -04:00
|
|
|
};
|
|
|
|
SchemaCompiler.prototype.dropTableIfExists = function(tableName) {
|
2014-04-09 10:11:41 -04:00
|
|
|
this.pushQuery('drop table if exists ' + this.formatter.wrap(tableName));
|
2014-04-08 16:25:57 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = SchemaCompiler;
|