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

You need to sign in or sign up before continuing.
Commit 24002321 by Rui Marinho

Add support for tagged SQL queries

Tagged SQL queries are queries constructed via ES6 tagged template
strings. For instance, one can do:

```js
var result = sql`SELECT ${1} AS "var"`;
```

The `sql` tag can transform the template string so that it returns
something like:

```js
var result = { query: 'SELECT ? AS "var"', values: [1] };
```

This makes it ideal for writing elegant SQL by passing the tagged query,
containing the `query` and `values` properties to `sequelize.query`.
1 parent 2eadf0c7
......@@ -665,7 +665,6 @@ module.exports = (function() {
*/
Sequelize.prototype.query = function(sql, callee, options, replacements) {
var self = this;
sql = sql.trim();
if (arguments.length === 4) {
deprecated('passing raw query replacements as the 4th argument to sequelize.query is deprecated. Please use options.replacements instead');
options.replacements = replacements;
......@@ -682,6 +681,22 @@ module.exports = (function() {
options = { raw: true };
}
if (Utils._.isPlainObject(sql)) {
if (sql.hasOwnProperty('values')) {
if (options.hasOwnProperty('replacements')) {
throw new Error('Both `sql.values` and `options.replacements` cannot be set at the same time');
}
options.replacements = sql.values;
}
if (sql.hasOwnProperty('query')) {
sql = sql.query;
}
}
sql = sql.trim();
if (!(callee instanceof Sequelize.Model)) {
// When callee is not set, assume raw query
options.raw = true;
......
......@@ -308,6 +308,19 @@ describe(Support.getTestDialectTeaser('Sequelize'), function() {
});
});
it('throw an exception if `values` and `options.replacements` are both passed', function() {
var self = this;
expect(function() {
self.sequelize.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, null, { raw: true, replacements: [1, 2] });
}).to.throw(Error, 'Both `sql.values` and `options.replacements` cannot be set at the same time');
});
it('uses properties `query` and `values` if query is tagged', function() {
return this.sequelize.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, null, { type: this.sequelize.QueryTypes.SELECT }).success(function(result) {
expect(result).to.deep.equal([{ foo: 1, bar: 2 }]);
});
});
it('dot separated attributes when doing a raw query without nest', function() {
var tickChar = (dialect === 'postgres' || dialect === 'mssql') ? '"' : '`'
, sql = 'select 1 as ' + Sequelize.Utils.addTicks('foo.bar.baz', tickChar);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!