knex/lib/schema/compiler.js

71 lines
1.8 KiB
JavaScript
Raw Normal View History

'use strict';
2015-05-09 13:58:18 -04:00
var helpers = require('./helpers');
var assign = require('lodash/object/assign');
// 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.
function SchemaCompiler(client, builder) {
2015-05-09 13:58:18 -04:00
this.builder = builder;
this.client = client;
2015-08-09 22:24:55 -03:00
this.schema = builder._schema;
2015-05-09 13:58:18 -04:00
this.formatter = client.formatter();
this.sequence = [];
}
2015-04-22 11:45:28 -04:00
assign(SchemaCompiler.prototype, {
2015-04-22 11:45:28 -04:00
pushQuery: helpers.pushQuery,
pushAdditional: helpers.pushAdditional,
createTable: buildTable('create'),
createTableIfNotExists: buildTable('createIfNot'),
alterTable: buildTable('alter'),
2015-12-14 09:56:53 -06:00
dropTablePrefix: 'drop table ',
2015-05-09 13:58:18 -04:00
dropTable: function dropTable(tableName) {
2015-12-14 09:56:53 -06:00
this.pushQuery(this.dropTablePrefix + this.formatter.wrap(prefixedTableName(this.schema, tableName)));
2015-04-22 11:45:28 -04:00
},
2015-05-09 13:58:18 -04:00
dropTableIfExists: function dropTableIfExists(tableName) {
2015-12-14 09:56:53 -06:00
this.pushQuery(this.dropTablePrefix + 'if exists ' + this.formatter.wrap(prefixedTableName(this.schema, tableName)));
2015-04-22 11:45:28 -04:00
},
2015-05-09 13:58:18 -04:00
raw: function raw(sql, bindings) {
2015-04-22 11:45:28 -04:00
this.sequence.push(this.client.raw(sql, bindings).toSQL());
},
2015-05-09 13:58:18 -04:00
toSQL: function toSQL() {
2015-04-22 11:45:28 -04:00
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;
2015-05-09 13:58:18 -04:00
}
2015-04-22 11:45:28 -04:00
2015-05-09 13:58:18 -04:00
});
function buildTable(type) {
2015-05-09 13:58:18 -04:00
return function (tableName, fn) {
2015-08-09 22:24:55 -03:00
var builder = this.client.tableBuilder(type, tableName, fn);
var sql;
builder.setSchema(this.schema);
sql = builder.toSQL();
for (var i = 0, l = sql.length; i < l; i++) {
this.sequence.push(sql[i]);
}
};
}
2014-04-09 10:11:41 -04:00
2015-08-09 22:24:55 -03:00
function prefixedTableName(prefix, table) {
return prefix ? prefix + '.' + table : table;
}
2015-05-09 13:58:18 -04:00
module.exports = SchemaCompiler;