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

92 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2016-03-02 17:07:05 +01:00
// MySQL Schema Compiler
// -------
const SchemaCompiler = require('../../../schema/compiler');
2016-03-02 17:07:05 +01:00
2021-01-01 17:46:10 +02:00
class SchemaCompiler_MSSQL extends SchemaCompiler {
constructor(client, builder) {
super(client, builder);
}
2016-03-02 17:07:05 +01:00
dropTableIfExists(tableName) {
const name = this.formatter.wrap(prefixedTableName(this.schema, tableName));
this.pushQuery(
`if object_id('${name}', 'U') is not null DROP TABLE ${name}`
);
2021-01-01 17:46:10 +02:00
}
2016-03-02 17:07:05 +01:00
2021-10-20 22:23:29 +02:00
dropViewIfExists(viewName) {
const name = this.formatter.wrap(prefixedTableName(this.schema, viewName));
this.pushQuery(
`if object_id('${name}', 'V') is not null DROP VIEW ${name}`
);
}
2016-03-02 17:07:05 +01:00
// Rename a table on the schema.
renameTable(tableName, to) {
this.pushQuery(
`exec sp_rename ${this.client.parameter(
prefixedTableName(this.schema, tableName),
this.builder,
this.bindingsHolder
)}, ${this.client.parameter(to, this.builder, this.bindingsHolder)}`
);
2021-01-01 17:46:10 +02:00
}
2016-03-02 17:07:05 +01:00
2021-10-20 22:23:29 +02:00
renameView(viewTable, to) {
this.pushQuery(
`exec sp_rename ${this.client.parameter(
prefixedTableName(this.schema, viewTable),
this.builder,
this.bindingsHolder
)}, ${this.client.parameter(to, this.builder, this.bindingsHolder)}`
);
}
2016-03-02 17:07:05 +01:00
// Check whether a table exists on the query.
hasTable(tableName) {
const formattedTable = this.client.parameter(
prefixedTableName(this.schema, tableName),
this.builder,
this.bindingsHolder
);
const bindings = [tableName];
let sql =
`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ` +
`WHERE TABLE_NAME = ${formattedTable}`;
if (this.schema) {
sql += ' AND TABLE_SCHEMA = ?';
bindings.push(this.schema);
}
this.pushQuery({ sql, bindings, output: (resp) => resp.length > 0 });
2021-01-01 17:46:10 +02:00
}
2016-03-02 17:07:05 +01:00
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
const formattedColumn = this.client.parameter(
column,
this.builder,
this.bindingsHolder
);
const formattedTable = this.client.parameter(
this.formatter.wrap(prefixedTableName(this.schema, tableName)),
this.builder,
this.bindingsHolder
);
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 });
2021-01-01 17:46:10 +02:00
}
}
SchemaCompiler_MSSQL.prototype.dropTablePrefix = 'DROP TABLE ';
2016-03-02 17:07:05 +01:00
function prefixedTableName(prefix, table) {
return prefix ? `${prefix}.${table}` : table;
}
module.exports = SchemaCompiler_MSSQL;