knex/src/schema/compiler.js

77 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-03-02 17:07:05 +01:00
import {pushQuery, pushAdditional} from './helpers';
2016-03-02 17:07:05 +01:00
import {assign} from '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.
function SchemaCompiler(client, builder) {
this.builder = builder
this.client = client
this.schema = builder._schema;
2016-03-02 17:07:05 +01:00
this.formatter = client.formatter()
this.sequence = []
2016-03-02 17:07:05 +01:00
}
assign(SchemaCompiler.prototype, {
pushQuery: pushQuery,
2016-03-02 17:07:05 +01:00
pushAdditional: pushAdditional,
2016-03-02 17:07:05 +01:00
createTable: buildTable('create'),
createTableIfNotExists: buildTable('createIfNot'),
alterTable: buildTable('alter'),
dropTablePrefix: 'drop table ',
dropTable(tableName) {
this.pushQuery(
this.dropTablePrefix + this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
2016-03-02 17:07:05 +01:00
},
dropTableIfExists(tableName) {
this.pushQuery(
this.dropTablePrefix + 'if exists ' +
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
2016-03-02 17:07:05 +01:00
},
raw(sql, bindings) {
2016-03-02 17:07:05 +01:00
this.sequence.push(this.client.raw(sql, bindings).toSQL());
},
toSQL() {
const sequence = this.builder._sequence;
for (let i = 0, l = sequence.length; i < l; i++) {
const query = sequence[i];
2016-03-02 17:07:05 +01:00
this[query.method].apply(this, query.args);
}
return this.sequence;
}
})
function buildTable(type) {
return function(tableName, fn) {
const builder = this.client.tableBuilder(type, tableName, fn);
2016-03-02 17:07:05 +01:00
builder.setSchema(this.schema);
const sql = builder.toSQL();
2016-03-02 17:07:05 +01:00
for (let i = 0, l = sql.length; i < l; i++) {
2016-03-02 17:07:05 +01:00
this.sequence.push(sql[i]);
}
};
}
function prefixedTableName(prefix, table) {
return prefix ? `${prefix}.${table}` : table;
}
export default SchemaCompiler;