不要怂,就是干,撸起袖子干!

Commit 65df6b4f by Joel Trost Committed by Matt Broadstone

QueryInterface passes with refactor

1 parent 3ae6e0aa
......@@ -48,67 +48,51 @@ module.exports = (function() {
return SqlGenerator.getCreateTableSql(tableName, attributes, options);
},
showTablesQuery: function () {
return 'SELECT name FROM sys.Tables';
return SqlGenerator.showTableSql();
},
dropTableQuery: function(tableName, options) {
options = options || {};
return SqlGenerator.dropTableSql(tableName,options);
},
var query = "IF (EXISTS ("
+ "SELECT * FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE TABLE_NAME='<%= tableName %>'))"
+ " BEGIN"
+ " DROP TABLE \"<%= tableName %>\""
+ " END";
addColumnQuery: function(tableName, key, dataType) {
var query = [
SqlGenerator.alterTableSql(tableName),
SqlGenerator.addColumnSql(key, dataType)
].join(' ') + ';';
return Utils._.template(query)({
tableName: tableName
});
return query;
},
removeColumnQuery: function(tableName, attributeName) {
var query = 'ALTER TABLE "<%= tableName %>" DROP "<%= attributeName %>";';
return Utils._.template(query)({ tableName: tableName, attributeName: attributeName });
var query = [
SqlGenerator.alterTableSql(tableName),
SqlGenerator.dropSql(attributeName)
].join(' ') + ';';
return query;
},
changeColumnQuery: function(tableName, attributes) {
var query = 'ALTER TABLE "<%= tableName %>" CHANGE <%= attributes %>;';
var attrString = [];
for (var attrName in attributes) {
var definition = attributes[attrName];
attrString.push(Utils._.template('"<%= attrName %>" "<%= attrName %>" <%= definition %>')({
attrName: attrName,
definition: definition
}));
}
var query = [
SqlGenerator.alterTableSql(tableName),
SqlGenerator.alterColumnSql(),
SqlGenerator.alterAttributesSql(attributes)
].join(' ') + ';';
return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') });
return query;
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = 'EXEC SP_RENAME \'<%= tableName %>.<%= before %>\', \'<%= after %>\'; <%= alter %>;';
var attrString = [];
var columnName;
var newColumnName;
for (var attrName in attributes) {
columnName = attrName;
if(attributes[attrName]){
var definition = attributes[attrName];
attrString.push(Utils._.template('ALTER TABLE "<%= tableName %>" ALTER COLUMN "<%= after %>" <%= definition %>')({
tableName: tableName,
after: columnName,
definition: definition
}));
}
}
return Utils._.template(query)({ tableName: tableName
, before: attrBefore
, after: columnName
, alter: attrString.join(' ')});
newColumnName = attrName;
}
var query = [
SqlGenerator.renameColumnSql(tableName, attrBefore, newColumnName),
this.changeColumnQuery(tableName, attributes)
].join(' ');
return query;
},
/*
......@@ -118,29 +102,8 @@ module.exports = (function() {
return SqlGenerator.insertSql(table,valueHash,modelAttributes, options);
},
showIndexQuery: function(tableName, options) {
var sql = "SELECT"
+ " TableName = t.name,"
+ " name = ind.name,"
+ " IndexId = ind.index_id,"
+ " ColumnId = ic.index_column_id,"
+ " ColumnName = col.name"
+ " FROM"
+ " sys.indexes ind"
+ " INNER JOIN "
+ " sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id"
+ " INNER JOIN"
+ " sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id"
+ " INNER JOIN "
+ " sys.tables t ON ind.object_id = t.object_id"
+ " WHERE t.name = '<%= tableName %>'<%= options %>";
return Utils._.template(sql)({
tableName: tableName,
options: (options || {}).database ? ' FROM \'' + options.database + '\'' : ''
});
return SqlGenerator.showIndexSql(tableName, options);
},
addIndexQuery: function(tableName, attributes, options, rawTablename) {
......@@ -187,7 +150,10 @@ module.exports = (function() {
* @return {String} The generated sql query.
*/
dropForeignKeyQuery: function(tableName, foreignKey) {
return SqlGenerator.dropForeignKeySql(tableName, foreignKey);
return [
SqlGenerator.alterTableSql(tableName),
SqlGenerator.dropSql(foreignKey)
].join(' ') + ';';
},
/*
Returns a query for selecting elements in the table <tableName>.
......
......@@ -8,6 +8,19 @@ var Utils = require('../../utils')
Escape a value (e.g. a string, number or date)
*/
var dialect = 'mssql';
var attributeMap = {
notNull:"NOT NULL",
allowNull:"NULL",
autoIncrement:"IDENTITY(1,1)",
defaultValue:"DEFAULT",
unique:"UNIQUE",
primaryKey:"PRIMARY KEY",
comment:"COMMENT",
references:"REFERENCES",
onDelete:"ON DELETE",
onUpdate:"ON UPDATE",
default:"DEFAULT"
};
//mssql doesnt support time zone
function escape(value, field) {
if (value && value._isSequelizeMethod) {
......@@ -49,6 +62,7 @@ function nameIndexes(indexes, rawTablename) {
});
}
function loadColumn(attributes){
var attrStr = [];
for (var attr in attributes) {
......@@ -65,9 +79,10 @@ function loadColumnWithTypes(attributes){
}
return attrStr;
}
function addTableExistsWrapper(tableName, query){
function addTableExistsWrapper(tableName, query, exists){
return [
"IF (NOT EXISTS (",
"IF (",
(exists ? "" : "NOT"), " EXISTS (",
"SELECT * FROM INFORMATION_SCHEMA.TABLES",
"WHERE TABLE_NAME='<%= unquotedTable %>'))",
"BEGIN",
......@@ -78,6 +93,9 @@ function addTableExistsWrapper(tableName, query){
module.exports = {
showTableSql: function(){
return 'SELECT name FROM sys.Tables;';
},
getCreateTableSql: function(tableName, attributes, options) {
var query = "CREATE TABLE <%= tableName %> (<%= attributes%>)";
var attrStr = []
......@@ -96,6 +114,23 @@ module.exports = {
query = addTableExistsWrapper(tableName, query);
return Utils._.template(query)(values).trim() + ";";
},
alterTableSql: function(tableName){
var query = 'ALTER TABLE <%= tableName %>';
var value = {
tableName : tableName
};
return Utils._.template(query)(value);
},
dropTableSql: function(tableName, options){
var query = "DROP TABLE <%= tableName %>";
var values = {
unquotedTable: tableName,
tableName: quoteIdentifier(tableName)
};
query = addTableExistsWrapper(tableName, query, true);
return Utils._.template(query)(values).trim() + ";";
},
insertSql: function(table, valueHash, modelAttributes, options) {
options = options || {};
var query
......@@ -137,7 +172,7 @@ module.exports = {
}
var replacements = {
table: this.quoteTable(table),
table: quoteIdentifier(table),
attributes: fields.join(','),
selFields: selFields.join(','),
values: values.join(',')
......@@ -147,6 +182,53 @@ module.exports = {
return Utils._.template(query)(replacements);
},
addColumnSql: function(key, dataType){
var attribute = Utils._.template('<%= key %> <%= definition %>')({
key: quoteIdentifier(key),
definition: this.attributeToSQL(dataType, {
context: 'addColumn'
})
});
return 'ADD ' + attribute;
},
alterColumnSql: function(){
return 'ALTER COLUMN';
},
renameColumnSql: function(tableName, attrBefore, newColumnName){
var query = 'EXEC SP_RENAME \'<%= tableName %>.<%= before %>\', \'<%= after %>\';';
var attrString = [];
var values = {
tableName: tableName
, before: attrBefore
, after: newColumnName
};
return Utils._.template(query)(values);
},
showIndexSql: function(tableName, options){
var sql = ["SELECT",
"TableName = t.name,",
"name = ind.name,",
"IndexId = ind.index_id,",
"ColumnId = ic.index_column_id,",
"ColumnName = col.name",
"FROM",
"sys.indexes ind",
"INNER JOIN",
"sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id",
"INNER JOIN",
"sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id",
"INNER JOIN",
"sys.tables t ON ind.object_id = t.object_id",
"WHERE t.name = '<%= tableName %>'<%= options %>"
].join(" ");
return Utils._.template(sql)({
tableName: tableName,
options: (options || {}).database ? ' FROM \'' + options.database + '\'' : ''
});
},
addIndexSql: function(tableName, attributes, options, rawTablename){
if (!options.name) {
// Mostly for cases where addIndex is called directly by the user without an options object (for example in migrations)
......@@ -185,17 +267,13 @@ module.exports = {
return Utils._.template(sql)(values);
},
attributeMap:{
notNull:"NOT NULL",
isNull:"NULL",
autoIncrement:"IDENTITY(1,1)",
defaultValue:"DEFAULT",
unique:"UNIQUE",
primaryKey:"PRIMARY KEY",
comment:"COMMENT",
references:"REFERENCES",
onDelete:"ON DELETE",
onUpdate:"ON UPDATE"
getEnumSql: function (attribute){
var template = 'VARCHAR(10) NOT NULL CHECK ("'
+ attribute.field + '" IN('
+ Utils._.map(attribute.values, function(value) {
return escape(value);
}.bind(this)).join(', ') + '))';
return template;
},
attributeToSQL: function(attribute, options) {
if (!Utils._.isPlainObject(attribute)) {
......@@ -204,81 +282,81 @@ module.exports = {
};
}
var template;
var isEnum = false;
var template = [];
//special enum query
if (attribute.type.toString() === DataTypes.ENUM.toString()) {
isEnum = true;
template = 'VARCHAR(10) NOT NULL CHECK ("'
+ attribute.field + '" IN('
+ Utils._.map(attribute.values, function(value) {
return escape(value);
}.bind(this)).join(', ') + '))';
template.push(this.getEnumSql(attribute));
} else {
template = attribute.type.toString();
//the everything else
template.push(attribute.type.toString());
//a primary key
if(attribute.primaryKey){
template.push(attributeMap.primaryKey);
//allow null
}else if(attribute.allowNull === false){
template.push(attributeMap.notNull);
//not nullable
}else{
template.push(attributeMap.allowNull);
}
template += ' ';
if (attribute.allowNull === false && !isEnum && !attribute.primaryKey) {
template += this.attributeMap.notNull;
}else if(!isEnum && !attribute.primaryKey){
template += this.attributeMap.isNull;
}else if(!isEnum) {
template += 'PRIMARY KEY';
}
//auto increment
if (attribute.autoIncrement) {
template += ' ' + this.attributeMap.autoIncrement;
template.push(attributeMap.autoIncrement);
}
// Blobs/texts cannot have a defaultValue
if (attribute.type !== 'TEXT'
&& attribute.type._binary !== true
&& attribute.type._binary === false
&& Utils.defaultValueSchemable(attribute.defaultValue)) {
if(options){
if(escape(attribute.defaultValue) !== 'NULL'){
template += ' DEFAULT ' + wrapSingleQuote(attribute.defaultValue);
}
if(options && escape(attribute.defaultValue)){
template.push(attributeMap.default + wrapSingleQuote(attribute.defaultValue));
}
}
if (attribute.unique === true) {
template += ' UNIQUE';
if (attribute.unique) {
template.push(attributeMap.unique);
}
if (attribute.references) {
template += ' REFERENCES ' + quoteIdentifier(attribute.references);
template.push(attributeMap.references + quoteIdentifier(attribute.references));
if (attribute.referencesKey) {
template += ' (' + quoteIdentifier(attribute.referencesKey) + ')';
template.push('(' + quoteIdentifier(attribute.referencesKey) + ')');
} else {
template += ' (' + quoteIdentifier('id') + ')';
template.push('(' + quoteIdentifier('id') + ')');
}
if (attribute.onDelete) {
if(attribute.onDelete.toUpperCase() !== 'RESTRICT'){
template += ' ON DELETE ' + attribute.onDelete.toUpperCase();
template.push(attributeMap.onDelete);
template.push(attribute.onDelete.toUpperCase());
}
}
if (attribute.onUpdate) {
template += ' ON UPDATE ' + attribute.onUpdate.toUpperCase();
template.push(attributeMap.onUpdate);
template.push(attribute.onUpdate.toUpperCase());
}
}
return template;
return template.join(' ');
},
describeTableSql: function(tableName, schema, schemaDelimiter){
var qry = ["SELECT c.Name, t.Name AS 'Type', c.IS_NULLABLE as IsNull",
var qry = [
"SELECT c.Name, t.Name AS 'Type', c.IS_NULLABLE as IsNull",
", object_definition(c.default_object_id) AS 'Default'",
"FROM sys.Columns c",
"INNER JOIN sys.types t",
"ON t.system_type_id = c.system_type_id",
"WHERE object_id = object_id(",
wrapSingleQuote(tableName),
");"].join(" ");
");"
].join(" ");
return qry;
},
......@@ -293,12 +371,23 @@ module.exports = {
"AND C.TABLE_NAME = ", wrapSingleQuote(tableName)
].join(" ");
},
dropForeignKeySql: function(tableName, foreignKey){
return ['ALTER TABLE',
quoteIdentifier(tableName),
dropSql: function(val){
return [
'DROP',
quoteIdentifier(foreignKey),
';'].join(' ');
quoteIdentifier(val)
].join(' ');
},
alterAttributesSql: function(attributes){
var attrString = [];
for (var attrName in attributes) {
var definition = attributes[attrName];
attrString.push(Utils._.template('"<%= attrName %>" <%= definition %>')({
attrName: attrName,
definition: definition
}));
}
return attrString.join(', ');
}
};
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!