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

60 lines
1.8 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
function SchemaCompiler_MSSQL(client, builder) {
SchemaCompiler.call(this, client, builder);
2016-03-02 17:07:05 +01:00
}
inherits(SchemaCompiler_MSSQL, SchemaCompiler);
2016-03-02 17:07:05 +01:00
Object.assign(SchemaCompiler_MSSQL.prototype, {
2016-03-02 17:07:05 +01:00
dropTablePrefix: 'DROP TABLE ',
dropTableIfExists(tableName) {
const name = this.formatter.wrap(prefixedTableName(this.schema, tableName));
this.pushQuery(
`if object_id('${name}', 'U') is not null DROP TABLE ${name}`
);
2016-03-02 17:07:05 +01:00
},
// Rename a table on the schema.
renameTable(tableName, to) {
this.pushQuery(
`exec sp_rename ${this.formatter.parameter(
prefixedTableName(this.schema, tableName)
)}, ${this.formatter.parameter(to)}`
);
2016-03-02 17:07:05 +01:00
},
// Check whether a table exists on the query.
hasTable(tableName) {
const formattedTable = this.formatter.parameter(
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
const sql =
`select object_id from sys.tables ` +
`where object_id = object_id(${formattedTable})`;
this.pushQuery({ sql, output: (resp) => resp.length > 0 });
2016-03-02 17:07:05 +01:00
},
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
const formattedColumn = this.formatter.parameter(column);
const formattedTable = this.formatter.parameter(
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
const sql =
`select object_id from sys.columns ` +
`where name = ${formattedColumn} ` +
`and object_id = object_id(${formattedTable})`;
this.pushQuery({ sql, output: (resp) => resp.length > 0 });
},
});
2016-03-02 17:07:05 +01:00
function prefixedTableName(prefix, table) {
return prefix ? `${prefix}.${table}` : table;
}
module.exports = SchemaCompiler_MSSQL;