Skip to content
Merged
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
39 changes: 31 additions & 8 deletions lib/dialects/abstract/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class QueryGenerator {
const fields = [];
const values = [];
const bind = [];
const bindParam = this.bindParam(bind);
const bindParam = options.bindParam === undefined ? this.bindParam(bind) : options.bindParam;
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 @@ -343,6 +343,8 @@ class QueryGenerator {
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, options.omitNull, options);

const values = [];
const bind = [];
const bindParam = options.bindParam === undefined ? this.bindParam(bind) : options.bindParam;
const modelAttributeMap = {};
let query = '<%= tmpTable %>UPDATE <%= table %> SET <%= values %><%= output %> <%= where %>';
let outputFragment;
Expand Down Expand Up @@ -414,22 +416,34 @@ class QueryGenerator {
}

const value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }));

if (value instanceof Utils.SequelizeMethod || options.bindParam === false) {
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }));
} else {
values.push(this.quoteIdentifier(key) + '=' + this.format(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }, bindParam));
}
}

const whereOptions = _.defaults({ bindParam }, options);
const replacements = {
table: this.quoteTable(tableName),
values: values.join(','),
output: outputFragment,
where: this.whereQuery(where, options),
where: this.whereQuery(where, whereOptions),
tmpTable
};

if (values.length === 0) {
return '';
}

return _.template(query, this._templateSettings)(replacements).trim();
query = _.template(query, this._templateSettings)(replacements).trim();
// Used by Postgres upsertQuery and calls to here with options.exception set to true
const result = { query };
if (options.bindParam !== false) {
result.bind = bind;
}
return result;
}

/**
Expand Down Expand Up @@ -2106,8 +2120,14 @@ class QueryGenerator {
}
}

if (value === null) {
const opValue = options.bindParam ? 'NULL' : this.escape(value, field);
return this._joinKeyValue(key, opValue, this.OperatorMap[Op.is], options.prefix);
}

if (!value) {
return this._joinKeyValue(key, this.escape(value, field), value === null ? this.OperatorMap[Op.is] : this.OperatorMap[Op.eq], options.prefix);
const opValue = options.bindParam ? this.format(value, field, options, options.bindParam) : this.escape(value, field);
return this._joinKeyValue(key, opValue, this.OperatorMap[Op.eq], options.prefix);
}

if (value instanceof Utils.SequelizeMethod && !(key !== undefined && value instanceof Utils.Fn)) {
Expand Down Expand Up @@ -2137,7 +2157,8 @@ class QueryGenerator {
}

if (isArray && fieldType instanceof DataTypes.ARRAY) {
return this._joinKeyValue(key, this.escape(value, field), this.OperatorMap[Op.eq], options.prefix);
const opValue = options.bindParam ? this.format(value, field, options, options.bindParam) : this.escape(value, field);
return this._joinKeyValue(key, opValue, this.OperatorMap[Op.eq], options.prefix);
}

if (isPlainObject && fieldType instanceof DataTypes.JSON && options.json !== false) {
Expand All @@ -2160,10 +2181,12 @@ class QueryGenerator {
}

if (key === Op.placeholder) {
return this._joinKeyValue(this.OperatorMap[key], this.escape(value, field), this.OperatorMap[Op.eq], options.prefix);
const opValue = options.bindParam ? this.format(value, field, options, options.bindParam) : this.escape(value, field);
return this._joinKeyValue(this.OperatorMap[key], opValue, this.OperatorMap[Op.eq], options.prefix);
}

return this._joinKeyValue(key, this.escape(value, field), this.OperatorMap[Op.eq], options.prefix);
const opValue = options.bindParam ? this.format(value, field, options, options.bindParam) : this.escape(value, field);
return this._joinKeyValue(key, opValue, this.OperatorMap[Op.eq], options.prefix);
}

_findField(key, options) {
Expand Down
3 changes: 3 additions & 0 deletions lib/dialects/mssql/data-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ module.exports = BaseTypes => {
return options.escape(value);
}
};
STRING.prototype._bindParam = function _bindParam(value, options) {
return options.bindParam(this._binary ? Buffer.from(value) : value);
};

function TEXT(length) {
if (!(this instanceof TEXT)) return new TEXT(length);
Expand Down
4 changes: 2 additions & 2 deletions lib/dialects/mssql/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -350,10 +350,10 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
}

updateQuery(tableName, attrValueHash, where, options, attributes) {
let sql = super.updateQuery(tableName, attrValueHash, where, options, attributes);
const sql = super.updateQuery(tableName, attrValueHash, where, options, attributes);
if (options.limit) {
const updateArgs = `UPDATE TOP(${this.escape(options.limit)})`;
sql = sql.replace('UPDATE', updateArgs);
sql.query = sql.query.replace('UPDATE', updateArgs);
}
return sql;
}
Expand Down
10 changes: 5 additions & 5 deletions lib/dialects/postgres/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,19 +344,19 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
upsertQuery(tableName, insertValues, updateValues, where, model, options) {
const primaryField = this.quoteIdentifier(model.primaryKeyField);

const insertOptions = _.defaults({ bindParam: false }, options);
const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, insertOptions);
let update = this.updateQuery(tableName, updateValues, where, options, model.rawAttributes);
const upsertOptions = _.defaults({ bindParam: false }, options);
const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions);
const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes);

insert.query = insert.query.replace('RETURNING *', `RETURNING ${primaryField} INTO primary_key`);
update = update.replace('RETURNING *', `RETURNING ${primaryField} INTO primary_key`);
update.query = update.query.replace('RETURNING *', `RETURNING ${primaryField} INTO primary_key`);

return this.exceptionFn(
'sequelize_upsert',
tableName,
'OUT created boolean, OUT primary_key text',
`${insert.query} created := true;`,
`${update}; created := false`
`${update.query}; created := false`
);
}

Expand Down
29 changes: 22 additions & 7 deletions lib/dialects/sqlite/query-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,11 +200,14 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
upsertQuery(tableName, insertValues, updateValues, where, model, options) {
options.ignoreDuplicates = true;

const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, options);
const update = this.updateQuery(tableName, updateValues, where, options, model.rawAttributes);
const bind = [];
const bindParam = this.bindParam(bind);

const query = insert.query + ' ' + update;
const bind = insert.bind;
const upsertOptions = _.defaults({ bindParam }, options);
const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions);
const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes);

const query = insert.query + ' ' + update.query;

return { query, bind };
}
Expand All @@ -217,6 +220,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {

const modelAttributeMap = {};
const values = [];
const bind = [];
const bindParam = options.bindParam || this.bindParam(bind);

if (attributes) {
_.each(attributes, (attribute, key) => {
Expand All @@ -229,14 +234,24 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {

for (const key in attrValueHash) {
const value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }));

if (value instanceof Utils.SequelizeMethod || options.bindParam === false) {
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }));
} else {
values.push(this.quoteIdentifier(key) + '=' + this.format(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }, bindParam));
}
}

let query;
const whereOptions = _.defaults({ bindParam }, options);

if (options.limit) {
return `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(tableName)} ${this.whereQuery(where, options)} LIMIT ${this.escape(options.limit)})`;
query = `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(tableName)} ${this.whereQuery(where, whereOptions)} LIMIT ${this.escape(options.limit)})`;
} else {
return `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} ${this.whereQuery(where, options)}`;
query = `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} ${this.whereQuery(where, whereOptions)}`;
}

return { query, bind };
}

truncateTableQuery(tableName) {
Expand Down
2 changes: 1 addition & 1 deletion lib/dialects/sqlite/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class Query extends AbstractQuery {
const method = this.getDatabaseMethod();
if (method === 'exec') {
// exec does not support bind parameter
sql = AbstractQuery.formatBindParameters(sql, this.options.bind, this.options.dialect, { skipUnescape: true })[0];
sql = AbstractQuery.formatBindParameters(sql, this.options.bind, this.options.dialect || 'sqlite', { skipUnescape: true })[0];
this.sql = sql;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2763,7 +2763,7 @@ class Model {

attrValueHash[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
options.omitNull = false;
return this.QueryInterface.bulkUpdate(this.getTableName(options), attrValueHash, options.where, options, this._timestampAttributes.deletedAt);
return this.QueryInterface.bulkUpdate(this.getTableName(options), attrValueHash, options.where, options, this.rawAttributes);
}).tap(() => {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
Expand Down
8 changes: 7 additions & 1 deletion test/integration/data-types.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,15 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
return testSuccess(Type, 'foobar');
});

it('calls parse and stringify for STRING', () => {
it('calls parse and stringify/bindParam for STRING', () => {
const Type = new Sequelize.STRING();

// mssql has a _bindParam function that checks if STRING was created with
// the boolean param (if so it outputs a Buffer bind param). This override
// isn't needed for other dialects
if (dialect === 'mssql') {
return testSuccess(Type, 'foobar', { useBindParam: true });
}
return testSuccess(Type, 'foobar');
});

Expand Down
2 changes: 1 addition & 1 deletion test/integration/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
if (dialect === 'mssql') {
expect(sql).to.not.contain('createdAt');
} else {
expect(sql).to.match(/UPDATE\s+[`"]+User1s[`"]+\s+SET\s+[`"]+secretValue[`"]='43',[`"]+updatedAt[`"]+='[^`",]+'\s+WHERE [`"]+id[`"]+\s=\s1/);
expect(sql).to.match(/UPDATE\s+[`"]+User1s[`"]+\s+SET\s+[`"]+secretValue[`"]=(\$1|\?),[`"]+updatedAt[`"]+=(\$2|\?)\s+WHERE [`"]+id[`"]+\s=\s(\$3|\?)/);
}
}
});
Expand Down
80 changes: 35 additions & 45 deletions test/integration/model/create.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -940,59 +940,49 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});

it('does not cast arrays for postgresql insert', function() {
if (dialect !== 'postgres') {
expect('').to.equal('');
return void 0;
}

const User = this.sequelize.define('UserWithArray', {
myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) },
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
});

let test = false;
return User.sync({force: true}).then(() => {
return User.create({myvals: [], mystr: []}, {
logging(sql) {
test = true;
expect(sql).not.to.contain('ARRAY[]::INTEGER[]');
expect(sql).not.to.contain('ARRAY[]::VARCHAR(255)[]');
}
if (dialect === 'postgres') {
it('does not cast arrays for postgresql insert', function() {
const User = this.sequelize.define('UserWithArray', {
myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) },
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
});
}).then(() => {
expect(test).to.be.true;
});
});

it('casts empty array correct for postgres update', function() {
if (dialect !== 'postgres') {
expect('').to.equal('');
return void 0;
}

const User = this.sequelize.define('UserWithArray', {
myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) },
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
});
let test = false;

return User.sync({force: true}).then(() => {
return User.create({myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four']}).then(user => {
user.myvals = [];
user.mystr = [];
return user.save({
let test = false;
return User.sync({force: true}).then(() => {
return User.create({myvals: [], mystr: []}, {
logging(sql) {
test = true;
expect(sql).to.contain('ARRAY[]::INTEGER[]');
expect(sql).to.contain('ARRAY[]::VARCHAR(255)[]');
expect(sql).to.contain('INSERT INTO "UserWithArrays" ("id","myvals","mystr","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4)');
}
});
}).then(() => {
expect(test).to.be.true;
});
}).then(() => {
expect(test).to.be.true;
});
});

it('does not cast arrays for postgres update', function() {
const User = this.sequelize.define('UserWithArray', {
myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) },
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
});
let test = false;

return User.sync({force: true}).then(() => {
return User.create({myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four']}).then(user => {
user.myvals = [];
user.mystr = [];
return user.save({
logging(sql) {
test = true;
expect(sql).to.contain('UPDATE "UserWithArrays" SET "myvals"=$1,"mystr"=$2,"updatedAt"=$3 WHERE "id" = $4');
}
});
});
}).then(() => {
expect(test).to.be.true;
});
});
}

it("doesn't allow duplicated records with unique:true", function() {
const self = this,
Expand Down
Loading