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

Commit 11b72c6f by Joel Trost Committed by Matt Broadstone

create.text.js all pass

1 parent 195e8554
...@@ -44,11 +44,14 @@ module.exports = (function() { ...@@ -44,11 +44,14 @@ module.exports = (function() {
schema: schema, schema: schema,
delimiter: schemaDelimiter || '.', delimiter: schemaDelimiter || '.',
toString: function() { toString: function() {
return self.quoteTable(this); return this.schema + this.delimiter + this.tableName;
} }
}; };
}, },
createSchema: function(schema){
return SqlGenerator.getCreateSchemaSql(schema);
},
/* /*
Returns a query for creating a table. Returns a query for creating a table.
Parameters: Parameters:
...@@ -145,20 +148,40 @@ module.exports = (function() { ...@@ -145,20 +148,40 @@ module.exports = (function() {
Parameters: table name + list of hashes of attribute-value-pairs. Parameters: table name + list of hashes of attribute-value-pairs.
*/ */
/* istanbul ignore next */ /* istanbul ignore next */
bulkInsertQuery: function(tableName, attrValueHashes,options) { bulkInsertQuery: function(tableName, attrValueHashes,options, attributes) {
var allAttributes = [], var query = '',
allAttributes = [],
insertKey = false,
isEmpty = true,
ignoreKeys = options.fields; ignoreKeys = options.fields;
Utils._.forEach(attrValueHashes, function(attrValueHash, i) { Utils._.forEach(attrValueHashes, function(attrValueHash, i) {
Utils._.forOwn(attrValueHash, function(value, key, hash) { Utils._.forOwn(attrValueHash, function(value, key, hash) {
if (allAttributes.indexOf(key) === -1) allAttributes.push(key); if (allAttributes.indexOf(key) === -1) allAttributes.push(key);
if (value !== null && ignoreKeys.indexOf(key) > 0) if (value !== null && ignoreKeys.indexOf(key) > -1){
ignoreKeys.splice(ignoreKeys.indexOf(key),1); ignoreKeys.splice(ignoreKeys.indexOf(key),1);
}else if(value !== null && attributes[key].autoIncrement){
insertKey = true;
}
if(value !== null){
isEmpty = false;
}
}); });
}); });
for(var i = 0; i < ignoreKeys.length; i++){
allAttributes.splice(allAttributes.indexOf(ignoreKeys[i]), 1); if(!isEmpty){
for(var i = 0; i < ignoreKeys.length; i++){
allAttributes.splice(allAttributes.indexOf(ignoreKeys[i]), 1);
}
query = SqlGenerator.bulkInsertSql(tableName, allAttributes, attrValueHashes,options);
if(insertKey){
query = SqlGenerator.identityInsertWrapper(query, tableName);
}
}else{
for(var j = 0; j < attrValueHashes.length; j++){
query += SqlGenerator.insertSql(tableName);
}
} }
return SqlGenerator.bulkInsertSql(tableName, allAttributes, attrValueHashes,options); return query;
}, },
/* /*
......
...@@ -130,13 +130,7 @@ function loadColumn(attributes){ ...@@ -130,13 +130,7 @@ function loadColumn(attributes){
} }
return attrStr; return attrStr;
} }
function identityInsertWrapper(query, table){
return[
'SET IDENTITY_INSERT', quoteIdentifier(table), 'ON;',
query,
'SET IDENTITY_INSERT', quoteIdentifier(table), 'OFF;',
].join(' ');
}
function addTableExistsWrapper(query, exists){ function addTableExistsWrapper(query, exists){
return [ return [
"IF (", "IF (",
...@@ -210,6 +204,22 @@ module.exports = { ...@@ -210,6 +204,22 @@ module.exports = {
showTableSql: function(){ showTableSql: function(){
return 'SELECT name FROM sys.Tables;'; return 'SELECT name FROM sys.Tables;';
}, },
identityInsertWrapper: function(query, table){
return[
'SET IDENTITY_INSERT', quoteIdentifier(table), 'ON;',
query,
'SET IDENTITY_INSERT', quoteIdentifier(table), 'OFF;',
].join(' ');
},
getCreateSchemaSql: function(schema){
return [
'IF NOT EXISTS (SELECT schema_name',
'FROM information_schema.schemata',
'WHERE schema_name = ', wrapSingleQuote(schema), ')',
'BEGIN',
'EXEC sp_executesql N\'CREATE SCHEMA', quoteIdentifier(schema),';\'',
"END;"].join(' ');
},
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 = []
...@@ -225,7 +235,7 @@ module.exports = { ...@@ -225,7 +235,7 @@ module.exports = {
var values = { var values = {
unquotedTable: tableName, unquotedTable: tableName,
tableName: quoteIdentifier(tableName), tableName: quoteIdentifier(tableName.toString()),
attributes: attrStr.join(", ") attributes: attrStr.join(", ")
}; };
query = addTableExistsWrapper(query); query = addTableExistsWrapper(query);
...@@ -240,15 +250,26 @@ module.exports = { ...@@ -240,15 +250,26 @@ module.exports = {
}, },
dropTableSql: function(tableName, options){ dropTableSql: function(tableName, options){
var query = "DROP TABLE <%= tableName %>"; var query = "DROP TABLE <%= tableName %>";
var values = { var values ={};
unquotedTable: tableName, if(tableName.tableName){
tableName: quoteIdentifier(tableName) values = {
}; unquotedTable: tableName,
tableName: quoteIdentifier(tableName.schema)
+ "." + quoteIdentifier(tableName.tableName)
};
}else{
values = {
unquotedTable: tableName,
tableName: quoteIdentifier(tableName)
};
}
query = addTableExistsWrapper(query, true); query = addTableExistsWrapper(query, true);
return Utils._.template(query)(values).trim() + ";"; return Utils._.template(query)(values).trim() + ";";
}, },
bulkInsertSql: function(tableName, attributeKeys, attributes,options) { bulkInsertSql: function(tableName, attributeKeys, attributes,options) {
var query = 'INSERT<%= ignoreDuplicates %> INTO <%= table %> (<%= attributes %>) VALUES <%= tuples %>;' var query = 'INSERT<%= ignoreDuplicates %> INTO <%= table %> (<%= attributes %>) VALUES <%= tuples %>;'
, emptyQuery = 'INSERT INTO <%= table %> DEFAULT VALUES'
, tuples = []; , tuples = [];
Utils._.forEach(attributes, function(attrValueHash, i) { Utils._.forEach(attributes, function(attrValueHash, i) {
...@@ -261,7 +282,7 @@ module.exports = { ...@@ -261,7 +282,7 @@ module.exports = {
var replacements = { var replacements = {
ignoreDuplicates: options && options.ignoreDuplicates ? ' IGNORE' : '', ignoreDuplicates: options && options.ignoreDuplicates ? ' IGNORE' : '',
table: quoteIdentifier(tableName), table: quoteIdentifier(tableName.toString()),
attributes: attributeKeys.map(function(attr) { attributes: attributeKeys.map(function(attr) {
return quoteIdentifier(attr); return quoteIdentifier(attr);
}.bind(this)).join(','), }.bind(this)).join(','),
...@@ -276,7 +297,10 @@ module.exports = { ...@@ -276,7 +297,10 @@ module.exports = {
, emptyQuery = 'INSERT INTO <%= tableName %>'; , emptyQuery = 'INSERT INTO <%= tableName %>';
valueQuery += ' OUTPUT <%= selFields %> VALUES (<%= values %>)'; valueQuery += ' OUTPUT <%= selFields %> VALUES (<%= values %>)';
emptyQuery += ' OUTPUT <%= selFields %> DEFAULT VALUES'; if(modelAttributeMap){
emptyQuery += ' OUTPUT <%= selFields %>';
}
emptyQuery += ' DEFAULT VALUES';
valueHash = Utils.removeNullValuesFromHash(valueHash, _options.omitNull); valueHash = Utils.removeNullValuesFromHash(valueHash, _options.omitNull);
...@@ -304,7 +328,7 @@ module.exports = { ...@@ -304,7 +328,7 @@ module.exports = {
query = (replacements.attributes.length ? valueQuery : emptyQuery) + ';'; query = (replacements.attributes.length ? valueQuery : emptyQuery) + ';';
if(insertKey){ if(insertKey){
query = identityInsertWrapper(query, tableName); query = this.identityInsertWrapper(query, tableName);
} }
return Utils._.template(query)(replacements); return Utils._.template(query)(replacements);
}, },
......
...@@ -1261,7 +1261,7 @@ module.exports = (function() { ...@@ -1261,7 +1261,7 @@ module.exports = (function() {
if (options.ignoreDuplicates && dialect === 'postgres') { if (options.ignoreDuplicates && dialect === 'postgres') {
return Promise.reject(new Error('Postgres does not support the \'ignoreDuplicates\' option.')); return Promise.reject(new Error('Postgres does not support the \'ignoreDuplicates\' option.'));
} }
if (options.updateOnDuplicate && ['mysql', 'mariadb'].indexOf(dialect) === -1) { if (options.updateOnDuplicate && ['mysql', 'mariadb', 'mssql'].indexOf(dialect) === -1) {
return Promise.reject(new Error(dialect + ' does not support the \'updateOnDuplicate\' option.')); return Promise.reject(new Error(dialect + ' does not support the \'updateOnDuplicate\' option.'));
} }
...@@ -1397,7 +1397,7 @@ module.exports = (function() { ...@@ -1397,7 +1397,7 @@ module.exports = (function() {
* @param {Boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) * @param {Boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
* @param {Boolean} [options.truncate=false] If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored * @param {Boolean} [options.truncate=false] If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored
* @param {Boolean} [options.cascade=false] Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. * @param {Boolean} [options.cascade=false] Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
* @param {Transaction} [options.transaction] * @param {Transaction} [options.transaction]
* @return {Promise<undefined>} * @return {Promise<undefined>}
*/ */
Model.prototype.destroy = function(options) { Model.prototype.destroy = function(options) {
...@@ -1465,7 +1465,7 @@ module.exports = (function() { ...@@ -1465,7 +1465,7 @@ module.exports = (function() {
* @param {Boolean} [options.hooks=true] Run before / after bulk restore hooks? * @param {Boolean} [options.hooks=true] Run before / after bulk restore hooks?
* @param {Boolean} [options.individualHooks=false] If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row * @param {Boolean} [options.individualHooks=false] If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
* @param {Number} [options.limit] How many rows to undelete * @param {Number} [options.limit] How many rows to undelete
* @param {Transaction} [options.transaction] * @param {Transaction} [options.transaction]
* *
* @return {Promise<undefined>} * @return {Promise<undefined>}
*/ */
...@@ -1535,7 +1535,7 @@ module.exports = (function() { ...@@ -1535,7 +1535,7 @@ module.exports = (function() {
* @param {Boolean} [options.individualHooks=false] Run before / after update hooks? * @param {Boolean} [options.individualHooks=false] Run before / after update hooks?
* @param {Boolean} [options.returning=false] Return the affected rows (only for postgres) * @param {Boolean} [options.returning=false] Return the affected rows (only for postgres)
* @param {Number} [options.limit] How many rows to update (only for mysql and mariadb) * @param {Number} [options.limit] How many rows to update (only for mysql and mariadb)
* @param {Transaction} [options.transaction] * @param {Transaction} [options.transaction]
* *
* @return {Promise<Array<affectedCount,affectedRows>>} * @return {Promise<Array<affectedCount,affectedRows>>}
*/ */
......
...@@ -1107,8 +1107,8 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -1107,8 +1107,8 @@ describe(Support.getTestDialectTeaser("Model"), function () {
it('stores the current date in createdAt', function(done) { it('stores the current date in createdAt', function(done) {
var self = this var self = this
, data = [{ username: 'Peter'}, , data = [{ username: 'Peter', uniqueName: '1'},
{ username: 'Paul'}] { username: 'Paul', uniqueName: '2'}]
this.User.bulkCreate(data).success(function() { this.User.bulkCreate(data).success(function() {
self.User.findAll({order: 'id'}).success(function(users) { self.User.findAll({order: 'id'}).success(function(users) {
...@@ -1244,7 +1244,8 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -1244,7 +1244,8 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
if (Support.getTestDialect() !== 'postgres') { //mssql does not support INSERT IGNORE
if (Support.getTestDialect() !== 'postgres' && dialect !== 'mssql') {
it("should support the ignoreDuplicates option", function(done) { it("should support the ignoreDuplicates option", function(done) {
var self = this var self = this
, data = [{ uniqueName: 'Peter', secretValue: '42' }, , data = [{ uniqueName: 'Peter', secretValue: '42' },
...@@ -1277,8 +1278,11 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -1277,8 +1278,11 @@ describe(Support.getTestDialectTeaser("Model"), function () {
self.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).error(function(err) { self.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).error(function(err) {
expect(err).to.exist expect(err).to.exist
expect(err.message).to.match(/Postgres does not support the \'ignoreDuplicates\' option./) if(dialect === 'mssql'){
expect(err.message).to.match(/MSSQL does not support the \'ignoreDuplicates\' option./)
}else{
expect(err.message).to.match(/Postgres does not support the \'ignoreDuplicates\' option./)
}
done(); done();
}) })
}) })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!