Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,12 @@ const sequelize = new Sequelize('database', 'username', 'password', {

// isolation level of each transaction
// defaults to dialect default
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ
isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ,

// Generate queries with bind parameters
// Currently only has an effect for non-bulk INSERTs
// - default: false
bindParams: true
})
```

Expand Down
64 changes: 53 additions & 11 deletions lib/dialects/abstract/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ class QueryGenerator {
const modelAttributeMap = {};
const fields = [];
const values = [];
const bind = [];
let query;
let valueQuery = '<%= tmpTable %>INSERT<%= ignoreDuplicates %> INTO <%= table %> (<%= attributes %>)<%= output %> VALUES (<%= values %>)';
let emptyQuery = '<%= tmpTable %>INSERT<%= ignoreDuplicates %> INTO <%= table %><%= output %>';
Expand Down Expand Up @@ -211,7 +212,12 @@ class QueryGenerator {
identityWrapperRequired = true;
}

values.push(this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'INSERT' }));
if (!options.bindParams || value instanceof Utils.SequelizeMethod) {
values.push(this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'INSERT' }));
} else {
bind.push(this.format(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'INSERT' }));
values.push('$' + bind.length);
}
}
}
}
Expand All @@ -234,7 +240,11 @@ class QueryGenerator {
].join(' ');
}

return _.template(query, this._templateSettings)(replacements);
query = _.template(query, this._templateSettings)(replacements);
if (options.bindParams) {
return { query, bind };
}
return query;
}

/**
Expand Down Expand Up @@ -961,15 +971,7 @@ class QueryGenerator {
return this.handleSequelizeMethod(value);
} else {
if (field && field.type) {
if (this.typeValidation && field.type.validate && value) {
if (options.isList && Array.isArray(value)) {
for (const item of value) {
field.type.validate(item, options);
}
} else {
field.type.validate(value, options);
}
}
this.validate(value, field, options);

if (field.type.stringify) {
// Users shouldn't have to worry about these args - just give them a function that takes a single arg
Expand All @@ -989,6 +991,46 @@ class QueryGenerator {
return SqlString.escape(value, this.options.timezone, this.dialect);
}

/*
Returns a bind parameter representation of a value (e.g. a string, number or date)
@private
*/
format(value, field, options) {
options = options || {};

if (value !== null && value !== undefined) {
if (value instanceof Utils.SequelizeMethod) {
throw new Error('Cannot pass SequelizeMethod as a bind parameter - use escape instead');
} else {
if (field && field.type) {
this.validate(value, field, options);

if (field.type.stringify) {
value = field.type.stringify(value, { escape: _.identity, field, timezone: this.options.timezone, operation: options.operation });
}
}
}
}

return value;
}

/*
Validate a value against a field specification
@private
*/
validate(value, field, options) {
if (this.typeValidation && field.type.validate && value) {
if (options.isList && Array.isArray(value)) {
for (const item of value) {
field.type.validate(item, options);
}
} else {
field.type.validate(value, options);
}
}
}

isIdentifierQuoted(identifier) {
return QuoteHelper.isIdentifierQuoted(identifier);
}
Expand Down
1 change: 1 addition & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,7 @@ class Model {
* @param {String} [options.initialAutoIncrement] Set the initial AUTO_INCREMENT value for the table in MySQL.
* @param {Object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
* @param {Object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error.
* @param {Boolean} [options.bindParams] Generate queries with bind parameters. Currently only has an effect for non-bulk INSERTs.

* @return {Model}
*/
Expand Down
1 change: 1 addition & 0 deletions lib/sequelize.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ class Sequelize {
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {Object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.
* @param {Boolean} [options.bindParams] Generate queries with bind parameters. Currently only has an effect for non-bulk INSERTs.
*
*/
constructor(database, username, password, options) {
Expand Down
27 changes: 27 additions & 0 deletions test/integration/model/create.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1437,6 +1437,33 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
});
});

it('should allow creates using bind parameters', function() {
const User = this.sequelize.define('UserUsingBindParams', {
'name': {
type: DataTypes.STRING
},
'children': {
type: DataTypes.INTEGER
},
'dob': {
type: DataTypes.DATE
}
}, {
bindParams: true
});

const date = new Date();
return this.sequelize.sync({force: true}).then(() => {
return User.create({ name: 'Test', children: 2, dob: date }, { bindParams: true }).then(user => {
return User.findById(user.id).then(user => {
expect(user.name).to.equal('Test');
expect(user.children).to.equal(2);
expect(user.dob).to.be.ok;
});
});
});
});
});

it('should return autoIncrement primary key (create)', function() {
Expand Down
9 changes: 7 additions & 2 deletions test/support.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ const Support = {
return url;
},

expectsql(query, expectations) {
expectsql(query, assertions) {
const expectations = assertions.query || assertions;
let expectation = expectations[Support.sequelize.dialect.name];

if (!expectation) {
Expand All @@ -229,7 +230,11 @@ const Support = {
if (_.isError(query)) {
expect(query.message).to.equal(expectation.message);
} else {
expect(query).to.equal(expectation);
expect(query.query || query).to.equal(expectation);
}

if (assertions.bind) {
expect(query.bind).to.deep.equal(assertions.bind);
}
}
};
Expand Down
8 changes: 8 additions & 0 deletions test/unit/dialects/abstract/query-generator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,5 +87,13 @@ describe('QueryGenerator', () => {
.to.throw('Invalid value { \'$in\': [ 4 ] }');
});
});

describe('format', () => {
it('should throw an error if passed SequelizeMethod', function() {
const QG = getAbstractQueryGenerator(this.sequelize);
const value = this.sequelize.fn('UPPER', 'test');
expect(() => QG.format(value)).to.throw(Error);
});
});
});

32 changes: 32 additions & 0 deletions test/unit/sql/insert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,40 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
postgres: 'INSERT INTO "users" ("user_name") VALUES (\'triggertest\') RETURNING *;',
default: "INSERT INTO `users` (`user_name`) VALUES ('triggertest');"
});

});

it('with bind parameters', () => {
const User = Support.sequelize.define('user', {
username: {
type: DataTypes.STRING,
field: 'user'
},
name: {
type: DataTypes.STRING,
field: 'name'
}
}, {
timestamps: false
});

const values = {
user: 'bindtest',
name: Support.sequelize.fn('UPPER', 'bindtest')
};
const options = {
bindParams: true
};
expectsql(sql.insertQuery(User.tableName, values, User.rawAttributes, options),
{
query: {
mssql: 'INSERT INTO [users] ([user],[name]) VALUES ($1,UPPER(N\'bindtest\'));',
postgres: 'INSERT INTO "users" ("user","name") VALUES ($1,UPPER(\'bindtest\'));',
default: 'INSERT INTO `users` (`user`,`name`) VALUES ($1,UPPER(\'bindtest\'));',
},
bind: ['bindtest']
});
});
});

describe('dates', () => {
Expand Down