Skip to content

Commit

Permalink
fix(query): add escape of null character for postgres bind parameters (
Browse files Browse the repository at this point in the history
  • Loading branch information
holm authored and sushantdhiman committed Apr 8, 2019
1 parent 4c9d18f commit d6daaf1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/dialects/postgres/query.js
Expand Up @@ -20,11 +20,14 @@ class Query extends AbstractQuery {
* @private
*/
static formatBindParameters(sql, values, dialect) {
let bindParam = [];
const stringReplaceFunc = value => typeof value === 'string' ? value.replace(/\0/g, '\\0') : value;

let bindParam;
if (Array.isArray(values)) {
bindParam = values;
bindParam = values.map(stringReplaceFunc);
sql = AbstractQuery.formatBindParameters(sql, values, dialect, { skipValueReplace: true })[0];
} else {
bindParam = [];
let i = 0;
const seen = {};
const replacementFunc = (match, key, values) => {
Expand All @@ -33,7 +36,7 @@ class Query extends AbstractQuery {
}
if (values[key] !== undefined) {
i = i + 1;
bindParam.push(values[key]);
bindParam.push(stringReplaceFunc(values[key]));
seen[key] = `$${i}`;
return `$${i}`;
}
Expand Down
26 changes: 26 additions & 0 deletions test/unit/sql/insert.test.js
Expand Up @@ -98,6 +98,32 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
});
});

describe('strings', () => {
it('formats null characters correctly when inserting', () => {
const User = Support.sequelize.define('user', {
username: {
type: DataTypes.STRING,
field: 'user_name'
}
}, {
timestamps: false
});

expectsql(sql.insertQuery(User.tableName, { user_name: 'null\0test' }, User.rawAttributes),
{
query: {
postgres: 'INSERT INTO "users" ("user_name") VALUES ($1);',
mssql: 'INSERT INTO [users] ([user_name]) VALUES ($1);',
default: 'INSERT INTO `users` (`user_name`) VALUES ($1);'
},
bind: {
postgres: ['null\u0000test'],
default: ['null\0test']
}
});
});
});

describe('bulkCreate', () => {
it('bulk create with onDuplicateKeyUpdate', () => {
const User = Support.sequelize.define('user', {
Expand Down

0 comments on commit d6daaf1

Please sign in to comment.