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

Commit 75aea7cb by Benjamin Woodruff

Attempt to unify query escaping between dialects

All dialect implementations re-implemented escaping, resulting in
(roughly) the same code being written four times in the codebase. This
moves all of that into SqlString.
1 parent c876192a
var Utils = require("../../utils") var Utils = require("../../utils")
, DataTypes = require("../../data-types") , DataTypes = require("../../data-types")
, SqlString = require("../../sql-string")
, util = require("util") , util = require("util")
module.exports = (function() { module.exports = (function() {
...@@ -507,7 +508,7 @@ module.exports = (function() { ...@@ -507,7 +508,7 @@ module.exports = (function() {
} }
if (dataType.comment && Utils._.isString(dataType.comment) && dataType.comment.length) { if (dataType.comment && Utils._.isString(dataType.comment) && dataType.comment.length) {
template += " COMMENT " + Utils.escape(dataType.comment) template += " COMMENT " + this.escape(dataType.comment)
} }
result[name] = template result[name] = template
...@@ -554,12 +555,7 @@ module.exports = (function() { ...@@ -554,12 +555,7 @@ module.exports = (function() {
}, },
escape: function(value) { escape: function(value) {
if (value instanceof Date) { return SqlString.escape(value, false, null, "mysql")
value = Utils.toSqlDate(value)
} else if (typeof value === 'boolean') {
value = value ? 1 : 0
}
return Utils.escape(value)
} }
} }
......
var Utils = require("../../utils") var Utils = require("../../utils")
, util = require("util") , util = require("util")
, DataTypes = require("../../data-types") , DataTypes = require("../../data-types")
, SqlString = require("../../sql-string")
, tables = {} , tables = {}
, primaryKeys = {} , primaryKeys = {}
...@@ -679,12 +680,6 @@ module.exports = (function() { ...@@ -679,12 +680,6 @@ module.exports = (function() {
return (i < 10) ? '0' + i.toString() : i.toString() return (i < 10) ? '0' + i.toString() : i.toString()
}, },
pgSqlDate: function (dt) {
var date = [ dt.getUTCFullYear(), this.padInt(dt.getUTCMonth()+1), this.padInt(dt.getUTCDate()) ].join('-')
var time = [ dt.getUTCHours(), this.padInt(dt.getUTCMinutes()), this.padInt(dt.getUTCSeconds())].join(':')
return date + ' ' + time + '.' + ((dt.getTime() % 1000) * 1000) + 'Z'
},
pgDataTypeMapping: function (tableName, attr, dataType) { pgDataTypeMapping: function (tableName, attr, dataType) {
if (Utils._.includes(dataType, 'PRIMARY KEY')) { if (Utils._.includes(dataType, 'PRIMARY KEY')) {
primaryKeys[tableName].push(attr) primaryKeys[tableName].push(attr)
...@@ -735,29 +730,8 @@ module.exports = (function() { ...@@ -735,29 +730,8 @@ module.exports = (function() {
return identifiers.split('.').map(function(t) { return this.quoteIdentifier(t, force) }.bind(this)).join('.') return identifiers.split('.').map(function(t) { return this.quoteIdentifier(t, force) }.bind(this)).join('.')
}, },
escape: function (val) { escape: function(value) {
if (val === undefined || val === null) { return SqlString.escape(value, false, null, "postgres")
return 'NULL';
}
switch (typeof val) {
case 'boolean':
return (val) ? 'true' : 'false';
case 'number':
return val + '';
case 'object':
if (Array.isArray(val)) {
return 'ARRAY['+ val.map(function(it) { return this.escape(it) }.bind(this)).join(',') + ']';
}
}
if (val instanceof Date) {
val = this.pgSqlDate(val);
}
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
val = val.replace(/'/g, "''");
return "'" + val + "'";
} }
} }
......
var Utils = require("../../utils") var Utils = require("../../utils")
, DataTypes = require("../../data-types") , DataTypes = require("../../data-types")
, SqlString = require("../../sql-string")
var MySqlQueryGenerator = Utils._.extend( var MySqlQueryGenerator = Utils._.extend(
Utils._.clone(require("../query-generator")), Utils._.clone(require("../query-generator")),
...@@ -448,19 +449,7 @@ module.exports = (function() { ...@@ -448,19 +449,7 @@ module.exports = (function() {
}, },
escape: function(value) { escape: function(value) {
if (value instanceof Date) { return SqlString.escape(value, false, null, "sqlite")
value = Utils.toSqlDate(value)
}
if (typeof value === 'string') {
return "'" + value.replace(/'/g, "''") + "'";
} else if (typeof value === 'boolean') {
return value ? 1 : 0; // SQLite has no type boolean
} else if (value === null || value === undefined) {
return 'NULL';
} else {
return value;
}
} }
} }
......
...@@ -13,12 +13,16 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) { ...@@ -13,12 +13,16 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) {
} }
switch (typeof val) { switch (typeof val) {
case 'boolean': return (val) ? 'true' : 'false'; case 'boolean':
// SQLite doesn't have true/false support. MySQL aliases true/false to 1/0
// for us. Postgres actually has a boolean type with true/false literals,
// but sequelize doesn't use it yet.
return dialect !== 'mysql' ? +!!val : '' + !!val;
case 'number': return val+''; case 'number': return val+'';
} }
if (val instanceof Date) { if (val instanceof Date) {
val = SqlString.dateToString(val, timeZone || "Z"); val = SqlString.dateToString(val, timeZone || "Z", dialect);
} }
if (Buffer.isBuffer(val)) { if (Buffer.isBuffer(val)) {
...@@ -26,7 +30,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) { ...@@ -26,7 +30,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) {
} }
if (Array.isArray(val)) { if (Array.isArray(val)) {
return SqlString.arrayToList(val, timeZone); return SqlString.arrayToList(val, timeZone, dialect);
} }
if (typeof val === 'object') { if (typeof val === 'object') {
...@@ -37,7 +41,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) { ...@@ -37,7 +41,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) {
} }
} }
if (dialect === "postgres" || dialect === "sqlite") { if (dialect === 'postgres' || dialect === 'sqlite') {
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS // http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598 // http://stackoverflow.com/q/603572/130598
val = val.replace(/'/g, "''"); val = val.replace(/'/g, "''");
...@@ -57,11 +61,18 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) { ...@@ -57,11 +61,18 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect) {
return "'"+val+"'"; return "'"+val+"'";
}; };
SqlString.arrayToList = function(array, timeZone) { SqlString.arrayToList = function(array, timeZone, dialect) {
if (dialect === 'postgres') {
return 'ARRAY[' + array.map(function(v) {
return SqlString.escape(v, true, timeZone, dialect);
}).join(',') + ']';
} else {
return array.map(function(v) { return array.map(function(v) {
if (Array.isArray(v)) return '(' + SqlString.arrayToList(v) + ')'; if (Array.isArray(v))
return SqlString.escape(v, true, timeZone); return '(' + SqlString.arrayToList(v, timeZone, dialect) + ')';
return SqlString.escape(v, true, timeZone, dialect);
}).join(', '); }).join(', ');
}
}; };
SqlString.format = function(sql, values, timeZone, dialect) { SqlString.format = function(sql, values, timeZone, dialect) {
...@@ -76,7 +87,7 @@ SqlString.format = function(sql, values, timeZone, dialect) { ...@@ -76,7 +87,7 @@ SqlString.format = function(sql, values, timeZone, dialect) {
}); });
}; };
SqlString.dateToString = function(date, timeZone) { SqlString.dateToString = function(date, timeZone, dialect) {
var dt = new Date(date); var dt = new Date(date);
if (timeZone != 'local') { if (timeZone != 'local') {
...@@ -95,7 +106,13 @@ SqlString.dateToString = function(date, timeZone) { ...@@ -95,7 +106,13 @@ SqlString.dateToString = function(date, timeZone) {
var minute = zeroPad(dt.getMinutes()); var minute = zeroPad(dt.getMinutes());
var second = zeroPad(dt.getSeconds()); var second = zeroPad(dt.getSeconds());
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; return year + '-' +
month + '-' +
day + ' ' +
hour + ':' +
minute + ':' +
second +
(dialect === 'mysql' ? '.0Z' : '');
}; };
SqlString.bufferToString = function(buffer) { SqlString.bufferToString = function(buffer) {
......
...@@ -42,17 +42,6 @@ var Utils = module.exports = { ...@@ -42,17 +42,6 @@ var Utils = module.exports = {
isHash: function(obj) { isHash: function(obj) {
return Utils._.isObject(obj) && !Array.isArray(obj); return Utils._.isObject(obj) && !Array.isArray(obj);
}, },
pad: function (s) {
return s < 10 ? '0' + s : s
},
toSqlDate: function(date) {
return date.getUTCFullYear() + '-' +
this.pad(date.getUTCMonth()+1) + '-' +
this.pad(date.getUTCDate()) + ' ' +
this.pad(date.getUTCHours()) + ':' +
this.pad(date.getUTCMinutes()) + ':' +
this.pad(date.getUTCSeconds())
},
argsArePrimaryKeys: function(args, primaryKeys) { argsArePrimaryKeys: function(args, primaryKeys) {
var result = (args.length == Object.keys(primaryKeys).length) var result = (args.length == Object.keys(primaryKeys).length)
if (result) { if (result) {
...@@ -181,9 +170,6 @@ var Utils = module.exports = { ...@@ -181,9 +170,6 @@ var Utils = module.exports = {
removeTicks: function(s, tickChar) { removeTicks: function(s, tickChar) {
tickChar = tickChar || Utils.TICK_CHAR tickChar = tickChar || Utils.TICK_CHAR
return s.replace(new RegExp(tickChar, 'g'), "") return s.replace(new RegExp(tickChar, 'g'), "")
},
escape: function(s) {
return SqlString.escape(s, true, "local").replace(/\\"/g, '"')
} }
} }
......
...@@ -235,10 +235,10 @@ describe('QueryGenerator', function() { ...@@ -235,10 +235,10 @@ describe('QueryGenerator', function() {
context: {options: {omitNull: true}} context: {options: {omitNull: true}}
}, { }, {
arguments: ['myTable', {foo: false}], arguments: ['myTable', {foo: false}],
expectation: "INSERT INTO `myTable` (`foo`) VALUES (0);" expectation: "INSERT INTO `myTable` (`foo`) VALUES (false);"
}, { }, {
arguments: ['myTable', {foo: true}], arguments: ['myTable', {foo: true}],
expectation: "INSERT INTO `myTable` (`foo`) VALUES (1);" expectation: "INSERT INTO `myTable` (`foo`) VALUES (true);"
} }
], ],
...@@ -272,7 +272,7 @@ describe('QueryGenerator', function() { ...@@ -272,7 +272,7 @@ describe('QueryGenerator', function() {
context: {options: {omitNull: true}} // Note: As above context: {options: {omitNull: true}} // Note: As above
}, { }, {
arguments: ['myTable', [{name: "foo", value: true}, {name: 'bar', value: false}]], arguments: ['myTable', [{name: "foo", value: true}, {name: 'bar', value: false}]],
expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1),('bar',0);" expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',true),('bar',false);"
} }
], ],
...@@ -302,10 +302,10 @@ describe('QueryGenerator', function() { ...@@ -302,10 +302,10 @@ describe('QueryGenerator', function() {
context: {options: {omitNull: true}} context: {options: {omitNull: true}}
}, { }, {
arguments: ['myTable', {bar: false}, {name: 'foo'}], arguments: ['myTable', {bar: false}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=0 WHERE `name`='foo'" expectation: "UPDATE `myTable` SET `bar`=false WHERE `name`='foo'"
}, { }, {
arguments: ['myTable', {bar: true}, {name: 'foo'}], arguments: ['myTable', {bar: true}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=1 WHERE `name`='foo'" expectation: "UPDATE `myTable` SET `bar`=true WHERE `name`='foo'"
} }
], ],
...@@ -385,11 +385,11 @@ describe('QueryGenerator', function() { ...@@ -385,11 +385,11 @@ describe('QueryGenerator', function() {
}, },
{ {
arguments: [{ maple: false, bacon: true }], arguments: [{ maple: false, bacon: true }],
expectation: "`maple`=0 AND `bacon`=1" expectation: "`maple`=false AND `bacon`=true"
}, },
{ {
arguments: [{ beaver: [false, true] }], arguments: [{ beaver: [false, true] }],
expectation: "`beaver` IN (0,1)" expectation: "`beaver` IN (false,true)"
}, },
{ {
arguments: [{birthday: new Date(Date.UTC(2011, 6, 1, 10, 1, 55))}], arguments: [{birthday: new Date(Date.UTC(2011, 6, 1, 10, 1, 55))}],
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!