knex/lib/dialects/mysql/schema/compiler.js

61 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-03-02 17:07:05 +01:00
// MySQL Schema Compiler
// -------
const { inherits } = require('util');
const SchemaCompiler = require('../../../schema/compiler');
2016-03-02 17:07:05 +01:00
const some = require('lodash/some');
2016-03-02 17:07:05 +01:00
function SchemaCompiler_MySQL(client, builder) {
SchemaCompiler.call(this, client, builder);
2016-03-02 17:07:05 +01:00
}
inherits(SchemaCompiler_MySQL, SchemaCompiler);
2016-03-02 17:07:05 +01:00
Object.assign(SchemaCompiler_MySQL.prototype, {
2016-03-02 17:07:05 +01:00
// Rename a table on the schema.
renameTable(tableName, to) {
this.pushQuery(
`rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap(
to
)}`
);
2016-03-02 17:07:05 +01:00
},
// Check whether a table exists on the query.
hasTable(tableName) {
let sql = 'select * from information_schema.tables where table_name = ?';
const bindings = [tableName];
if (this.schema) {
sql += ' and table_schema = ?';
bindings.push(this.schema);
} else {
sql += ' and table_schema = database()';
}
2016-03-02 17:07:05 +01:00
this.pushQuery({
sql,
bindings,
output: function output(resp) {
2016-03-02 17:07:05 +01:00
return resp.length > 0;
},
2016-03-02 17:07:05 +01:00
});
},
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
2016-03-02 17:07:05 +01:00
this.pushQuery({
sql: `show columns from ${this.formatter.wrap(tableName)}`,
output(resp) {
return some(resp, (row) => {
return (
this.client.wrapIdentifier(row.Field) ===
this.client.wrapIdentifier(column)
);
});
},
2016-03-02 17:07:05 +01:00
});
},
});
2016-03-02 17:07:05 +01:00
module.exports = SchemaCompiler_MySQL;