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

Commit da053191 by Joel Trost Committed by Matt Broadstone

Destroyed the Select statement, now rebuilding

1 parent 5db3a650
...@@ -1259,7 +1259,7 @@ module.exports = (function() { ...@@ -1259,7 +1259,7 @@ module.exports = (function() {
} }
query += ';'; query += ';';
console.log(query);
return query; return query;
}, },
......
...@@ -31,7 +31,7 @@ module.exports = (function() { ...@@ -31,7 +31,7 @@ module.exports = (function() {
} }
var promise = new Utils.Promise(function(resolve, reject) { var promise = new Utils.Promise(function(resolve, reject) {
console.log(self.sql); //console.log(self.sql);
self self
.connection .connection
......
...@@ -3,14 +3,13 @@ ...@@ -3,14 +3,13 @@
var Utils = require('../../utils') var Utils = require('../../utils')
, SqlString = require('../../sql-string') , SqlString = require('../../sql-string')
, DataTypes = require('./data-types') , DataTypes = require('./data-types')
, options , _options
, dialect , _dialect
, sequelize; , _sequelize;
/* /*
Escape a value (e.g. a string, number or date) Escape a value (e.g. a string, number or date)
*/ */
var dialect = 'mssql';
var attributeMap = { var attributeMap = {
notNull:"NOT NULL", notNull:"NOT NULL",
allowNull:"NULL", allowNull:"NULL",
...@@ -24,7 +23,13 @@ var attributeMap = { ...@@ -24,7 +23,13 @@ var attributeMap = {
onUpdate:"ON UPDATE", onUpdate:"ON UPDATE",
default:"DEFAULT" default:"DEFAULT"
}; };
function escape(value, field) {
if (value && value._isSequelizeMethod) {
return value.toString();
} else {
return SqlString.escape(value, false, _options.timezone, _dialect, field);
}
}
function quoteIdentifier(identifier, force) { function quoteIdentifier(identifier, force) {
if (identifier === '*') return identifier; if (identifier === '*') return identifier;
return Utils.addTicks(identifier, '"'); return Utils.addTicks(identifier, '"');
...@@ -58,7 +63,39 @@ function nameIndexes(indexes, rawTablename) { ...@@ -58,7 +63,39 @@ function nameIndexes(indexes, rawTablename) {
}); });
} }
function fieldsToSql(fields, singleQuote){
var fieldStr = [];
for (var key in fields) {
if (fields.hasOwnProperty(key)) {
if(singleQuote){
fieldStr.push(wrapSingleQuote(key));
}else{
fieldStr.push(quoteIdentifier(key));
}
}
}
if(fieldStr){
if(fieldStr.length > 0){
return fieldStr.join(',');
}
}
return '';
}
function valuesToSql(fields, modelAttributeMap){
var values = [];
for (var key in fields) {
if (fields.hasOwnProperty(key)) {
var value = fields[key];
values.push(escape(value, (modelAttributeMap && modelAttributeMap[key]) || undefined));
}
}
if(values){
if(values.length > 0){
return values.join(',');
}
}
return '';
}
function loadColumn(attributes){ function loadColumn(attributes){
var attrStr = []; var attrStr = [];
for (var attr in attributes) { for (var attr in attributes) {
...@@ -75,7 +112,7 @@ function loadColumnWithTypes(attributes){ ...@@ -75,7 +112,7 @@ function loadColumnWithTypes(attributes){
} }
return attrStr; return attrStr;
} }
function addTableExistsWrapper(tableName, query, exists){ function addTableExistsWrapper(query, exists){
return [ return [
"IF (", "IF (",
(exists ? "" : "NOT"), " EXISTS (", (exists ? "" : "NOT"), " EXISTS (",
...@@ -86,34 +123,67 @@ function addTableExistsWrapper(tableName, query, exists){ ...@@ -86,34 +123,67 @@ function addTableExistsWrapper(tableName, query, exists){
"END" "END"
].join(" "); ].join(" ");
} }
function identityInsertOnWrapper(query){
return [
'SET IDENTITY_INSERT <%= tableName %> ON;',
query,
'SET IDENTITY_INSERT <%= tableName %> OFF;'
].join(' ');
}
//select stuff
function loadFields(attributes){
var attrStr = [];
for (var attr in attributes) {
attrStr.push(quoteIdentifier(attr));
}
return attrStr;
}
function loadFields(attributes, tableName){
var attrStr = [];
for (var attr in attributes) {
if(tableName){
attrStr.push(quoteIdentifier(tableName) + "." + quoteIdentifier(attr));
}else{
attrStr.push(quoteIdentifier(attr));
}
}
return attrStr.join(',');
}
function joinFields(attributes, tableName){
var attrStr = [];
if(tableName){
for (var attr in attributes) {
attrStr.push(quoteIdentifier(tableName)
+ "."
+ quoteIdentifier(attr)
+ " AS " + quoteIdentifier(tableName + "." + attr));
}
}
return attrStr.join(',');
}
module.exports = { module.exports = {
get options(){ get options(){
return options; return _options;
}, },
set options(opt) { set options(opt) {
options = opt; _options = opt;
}, },
get dialect(){ get dialect(){
return dialect; return _dialect;
}, },
set dialect(dial) { set dialect(dial) {
dialect = dial; _dialect = dial;
}, },
get sequelize(){ get sequelize(){
return sequelize; return _sequelize;
}, },
set sequelize(seq) { set sequelize(seq) {
sequelize = seq; _sequelize = seq;
},
escape: function(value, field) {
if (value && value._isSequelizeMethod) {
return value.toString();
} else {
return SqlString.escape(value, false, options.timezone, dialect, field);
}
}, },
showTableSql: function(){ showTableSql: function(){
return 'SELECT name FROM sys.Tables;'; return 'SELECT name FROM sys.Tables;';
}, },
...@@ -132,7 +202,7 @@ module.exports = { ...@@ -132,7 +202,7 @@ module.exports = {
tableName: quoteIdentifier(tableName), tableName: quoteIdentifier(tableName),
attributes: attrStr.join(", ") attributes: attrStr.join(", ")
}; };
query = addTableExistsWrapper(tableName, query); query = addTableExistsWrapper(query);
return Utils._.template(query)(values).trim() + ";"; return Utils._.template(query)(values).trim() + ";";
}, },
alterTableSql: function(tableName){ alterTableSql: function(tableName){
...@@ -148,55 +218,38 @@ module.exports = { ...@@ -148,55 +218,38 @@ module.exports = {
unquotedTable: tableName, unquotedTable: tableName,
tableName: quoteIdentifier(tableName) tableName: quoteIdentifier(tableName)
}; };
query = addTableExistsWrapper(tableName, query, true); query = addTableExistsWrapper(query, true);
return Utils._.template(query)(values).trim() + ";"; return Utils._.template(query)(values).trim() + ";";
}, },
insertSql: function(table, valueHash, modelAttributes, options) { insertSql: function(tableName, valueHash, modelAttributeMap) {
options = options || {};
var query var query
, valueQuery = 'INSERT INTO <%= table %> (<%= attributes %>)' , valueQuery = 'INSERT INTO <%= tableName %> (<%= attributes %>)'
, emptyQuery = 'INSERT INTO <%= table %>' , emptyQuery = 'INSERT INTO <%= tableName %>';
, fields = []
, selFields = []
, values = []
, key
, value
, modelAttributeMap = {};
valueQuery += ' OUTPUT <%= selFields %> VALUES (<%= values %>)'; valueQuery += ' OUTPUT <%= selFields %> VALUES (<%= values %>)';
emptyQuery += ' OUTPUT <%= selFields %> VALUES ()'; emptyQuery += ' VALUES ()';
valueHash = Utils.removeNullValuesFromHash(valueHash, this.options.omitNull); valueHash = Utils.removeNullValuesFromHash(valueHash, _options.omitNull);
for (key in valueHash) { var insertKey = false;
if (valueHash.hasOwnProperty(key)) { for (var key in valueHash) {
value = valueHash[key]; if(modelAttributeMap[key].autoIncrement){
// SERIALS' can't be NULL in postgresql, use DEFAULT where supported insertKey = true;
if(modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement && value){
fields.push(quoteIdentifier(key));
selFields.push(wrapSingleQuote(key));
valueQuery = 'SET IDENTITY_INSERT <%= table %> ON;'
+ valueQuery
+ '; SET IDENTITY_INSERT <%= table %> OFF';
values.push(this.escape(value, (modelAttributeMap && modelAttributeMap[key]) || undefined));
}else if(value) {
fields.push(quoteIdentifier(key));
selFields.push(wrapSingleQuote(key));
values.push(this.escape(value, (modelAttributeMap && modelAttributeMap[key]) || undefined));
}
} }
} }
var replacements = { var replacements = {
table: quoteIdentifier(table), tableName: quoteIdentifier(tableName),
attributes: fields.join(','), attributes: fieldsToSql(valueHash, false),
selFields: selFields.join(','), selFields: fieldsToSql(valueHash, true),
values: values.join(',') values: valuesToSql(valueHash, modelAttributeMap)
}; };
query = (replacements.attributes.length ? valueQuery : emptyQuery) + ';'; query = (replacements.attributes.length ? valueQuery : emptyQuery) + ';';
if(insertKey){
query = identityInsertOnWrapper(query);
}
return Utils._.template(query)(replacements); return Utils._.template(query)(replacements);
}, },
...@@ -288,7 +341,7 @@ module.exports = { ...@@ -288,7 +341,7 @@ module.exports = {
var template = 'VARCHAR(10) NOT NULL CHECK ("' var template = 'VARCHAR(10) NOT NULL CHECK ("'
+ attribute.field + '" IN(' + attribute.field + '" IN('
+ Utils._.map(attribute.values, function(value) { + Utils._.map(attribute.values, function(value) {
return this.escape(value); return escape(value);
}.bind(this)).join(', ') + '))'; }.bind(this)).join(', ') + '))';
return template; return template;
}, },
...@@ -327,7 +380,7 @@ module.exports = { ...@@ -327,7 +380,7 @@ module.exports = {
if (attribute.type !== 'TEXT' if (attribute.type !== 'TEXT'
&& attribute.type._binary === false && attribute.type._binary === false
&& Utils.defaultValueSchemable(attribute.defaultValue)) { && Utils.defaultValueSchemable(attribute.defaultValue)) {
if(options && this.escape(attribute.defaultValue)){ if(options && escape(attribute.defaultValue)){
template.push(attributeMap.default + wrapSingleQuote(attribute.defaultValue)); template.push(attributeMap.default + wrapSingleQuote(attribute.defaultValue));
} }
} }
...@@ -405,6 +458,46 @@ module.exports = { ...@@ -405,6 +458,46 @@ module.exports = {
})); }));
} }
return attrString.join(', '); return attrString.join(', ');
},
getSelectorClause: function(model, options){
var query = ['SELECT'];
//we have joins
//add join table
if(options.include){
query.push(loadFields(model.rawAttributes, model.name));
for(var i = 0; i < options.include.length; i++){
if(options.include[i].as) {
query.push(joinFields(options.include[i].model.rawAttributes
, options.include[i].as));
}
}
}else {
query.push(loadFields(model.rawAttributes));
}
return query.join(' ');
},
getFromClause: function(tableName, asValue){
var query = ["FROM",
quoteIdentifier(tableName)];
if(asValue){
query.push("AS");
query.push(quoteIdentifier(asValue));
}
return query.join(' ');
},
getJoinClause: function(model, include){
var primaryKey = '';
for(var key in model.rawAttributes){
if(model.rawAttributes[key].primaryKey){
primaryKey = key;
break;
}
}
console.log(include.association.foreignKey);
console.log(primaryKey);
//for(var i = 0; i < )
var joinType = include.required ? ' INNER JOIN ' : ' LEFT OUTER JOIN ';
} }
}; };
......
...@@ -38,72 +38,72 @@ describe(Support.getTestDialectTeaser("Alias"), function() { ...@@ -38,72 +38,72 @@ describe(Support.getTestDialectTeaser("Alias"), function() {
}); });
}); });
it('shouldnt touch the passed alias', function () { // it('shouldnt touch the passed alias', function () {
var User = this.sequelize.define('user', {}) // var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}); // , Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: 'ASSIGNMENTS', foreignKey: 'userId' }); // User.hasMany(Task, { as: 'ASSIGNMENTS', foreignKey: 'userId' });
Task.belongsTo(User, { as: 'OWNER', foreignKey: 'userId' }); // Task.belongsTo(User, { as: 'OWNER', foreignKey: 'userId' });
return this.sequelize.sync({ force: true }).then(function () { // return this.sequelize.sync({ force: true }).then(function () {
return User.create({ id: 1 }); // return User.create({ id: 1 });
}).then(function (user){ // }).then(function (user){
expect(user.getASSIGNMENTS).to.be.ok; // expect(user.getASSIGNMENTS).to.be.ok;
return Task.create({ id: 1, userId: 1 }); // return Task.create({ id: 1, userId: 1 });
}).then(function (task) { // }).then(function (task) {
expect(task.getOWNER).to.be.ok; // expect(task.getOWNER).to.be.ok;
return Promise.all([ // return Promise.all([
User.find({ where: { id: 1 }, include: [{model: Task, as: 'ASSIGNMENTS'}] }), // User.find({ where: { id: 1 }, include: [{model: Task, as: 'ASSIGNMENTS'}] }),
Task.find({ where: { id: 1 }, include: [{model: User, as: 'OWNER'}] }), // Task.find({ where: { id: 1 }, include: [{model: User, as: 'OWNER'}] }),
]); // ]);
}).spread(function (user, task) { // }).spread(function (user, task) {
expect(user.ASSIGNMENTS).to.be.ok; // expect(user.ASSIGNMENTS).to.be.ok;
expect(task.OWNER).to.be.ok; // expect(task.OWNER).to.be.ok;
}); // });
}); // });
it('should allow me to pass my own plural and singular forms to hasMany', function () { // it('should allow me to pass my own plural and singular forms to hasMany', function () {
var User = this.sequelize.define('user', {}) // var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}); // , Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: { singular: 'task', plural: 'taskz'} }); // User.hasMany(Task, { as: { singular: 'task', plural: 'taskz'} });
return this.sequelize.sync({ force: true }).then(function () { // return this.sequelize.sync({ force: true }).then(function () {
return User.create({ id: 1 }); // return User.create({ id: 1 });
}).then(function (user) { // }).then(function (user) {
expect(user.getTaskz).to.be.ok; // expect(user.getTaskz).to.be.ok;
expect(user.addTask).to.be.ok; // expect(user.addTask).to.be.ok;
expect(user.addTaskz).to.be.ok; // expect(user.addTaskz).to.be.ok;
}).then(function () { // }).then(function () {
return User.find({ where: { id: 1 }, include: [{model: Task, as: 'taskz'}] }); // return User.find({ where: { id: 1 }, include: [{model: Task, as: 'taskz'}] });
}).then(function (user) { // }).then(function (user) {
expect(user.taskz).to.be.ok; // expect(user.taskz).to.be.ok;
}); // });
}); // });
it('should allow me to define plural and singular forms on the model', function () { // it('should allow me to define plural and singular forms on the model', function () {
var User = this.sequelize.define('user', {}) // var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}, { // , Task = this.sequelize.define('task', {}, {
name: { // name: {
singular: 'assignment', // singular: 'assignment',
plural: 'assignments' // plural: 'assignments'
} // }
}); // });
User.hasMany(Task); // User.hasMany(Task);
return this.sequelize.sync({ force: true }).then(function () { // return this.sequelize.sync({ force: true }).then(function () {
return User.create({ id: 1 }); // return User.create({ id: 1 });
}).then(function (user) { // }).then(function (user) {
expect(user.getAssignments).to.be.ok; // expect(user.getAssignments).to.be.ok;
expect(user.addAssignment).to.be.ok; // expect(user.addAssignment).to.be.ok;
expect(user.addAssignments).to.be.ok; // expect(user.addAssignments).to.be.ok;
}).then(function () { // }).then(function () {
return User.find({ where: { id: 1 }, include: [Task] }); // return User.find({ where: { id: 1 }, include: [Task] });
}).then(function (user) { // }).then(function (user) {
expect(user.assignments).to.be.ok; // expect(user.assignments).to.be.ok;
}); // });
}); // });
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!