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

Commit 65df6b4f by Joel Trost Committed by Matt Broadstone

QueryInterface passes with refactor

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