You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
MSSQL: Implicit conversion causes table scan -- Prepending N to strings precludes index use on varchar columns #9107
dialect: mssqlFor issues and PRs. Things that involve MSSQL (and do not involve all dialects).existing workaroundFor issues. There is a known workaround for this issue.status: understoodFor issues. Applied when the issue is understood / reproducible.type: featureDEPRECATED: replace with the "feature" issue type
Querying a table and filtering on a varchar column. The issue is most easily illustrated using raw query code although it applies to both raw queries and model-generated ones.
createtablenames (
name varchar(100) not nullprimary key clustered
)
sequelize.query('select * from names where name=:name',{replacements: {name: 'hello'}});
What do you expect to happen?
Sequelize to construct SQL without prepending N to :name
SQL sent to server:
select*from names where name='hello'
SQL Server performs an index seek using index defined above.
What is actually happening?
N is prepended.
SQL sent to server:
select*from names where name=N'hello'
SQL Server performs a table scan after doing an implicit conversion on N'hello'
Notes
I believe this problem was introduced in response to issue #3752 to handle unicode strings in mssql. The problem is that automatically treating all strings as unicode precludes index use on varchar columns which can significantly hurt performance.
Yeah, this is really needed. I was spinning my wheels for a while trying to figure out why my SSMS version took 1 second and the Sequelize version was taking up to 2 minutes.
I actually solved for this by creating a custom data types folder and I created a STRING_ASCII type so that I would not have to use the "literal" function everywhere.
import Sequelize from 'sequelize';
class STRING_ASCII extends Sequelize.STRING {
constructor(length, binary) {
super(length, binary);
this.escape = false;
this.key = 'STRING_ASCII';
}
toSql() {
if (!this._binary) {
return `VARCHAR(${this._length})`;
}
return `BINARY(${this._length})`;
}
_stringify(value, options) {
if (this._binary) {
return Sequelize.BLOB.prototype._stringify(value);
}
let data = options.escape(value);
data = data.substring(0, 1) === 'N' ? data.substring(1) : data;
return data;
}
}
export default STRING_ASCII;
Then where I initialize Sequelize I import all my custom data types and loop over them to make them available.
import DataTypes from '../../datatypes';
...
for (const dataType in DataTypes) {
Sequelize[dataType] = DataTypes[dataType];
}
I am not sure if I did everything right but its been working for me.
I will say that while being able to extend the data types with your own is a great feature, however, for out of the box support for MSSQL this should not be necessary and this still should be addressed in the core code.
Reacted by borderBite, rconstantine and Jean Carlos
@Damonmiller thanks for that. I will give that a try next week. I would love to not use literal everywhere as well.
Another issue I found was that if I mixed and matched different methods of declaring bits of my where clause, some of it wouldn't show up in the query. Before using literal anywhere, the query was properly constructed, so I don't know what was being screwed up behind the scenes.
So yeah, I'd like this to get fixed out-of-the-box at some point.
@Damonmiller Thank you very much for the suggestion.
Do you know how do I use these extended datatype in raw query through replacement option ? . I have been looking into this as my query is performing poorly because of nvarchar implicit conversion.
@Damonmiller Thank you very much for the suggestion.
Do you know how do I use these extended datatype in raw query through replacement option ? . I have been looking into this as my query is performing poorly because of nvarchar implicit conversion.
@BalajiJagadeesan Unfortunately I do not. I have not used a raw query at all so have not looked into a any workarounds.
Oh geez what the heck is going on here?! Now I know why the performance of our API has been tanking lately. Wow... Does nobody actually use MSSQL in production? This behavior is positively atrocious.
EDIT: Why is the label on this "feature?" This is a straight-up bug.
We recently updated to Sequelize v5 and I can no longer get my previous custom data type to work. The constructor is fired, but the _stringify() method is ignored and it uses the parent method instead. Anyone know of a way to work around this? Really wish that we did not have to continue to workaround this very terrible bug in Sequelize for MSSQL.... Any chance of getting this fixed in the core?
The escaping and 'N' prefix are applied based on the result of calling typeof against the parameter. By wrapping the parameter in an Object, it avoids the statement that introduces the 'N' prefix.
Therefore:
sequelize.query('select * from names where name=:name',{replacements: {name: 'hello'}});
becomes:
sequelize.query('select * from names where name=:name',{replacements: {name: newString('hello')}});
and obviously the config is in the file just included.
also in appDB.js is this:
constseq2=newSequelize(config);
What I'm not understanding is where to include your code and also how to use it. I'm sure it's obvious, but I wasn't familiar with "monkey patching" before running into this thread. Will it simply overwrite the old way so I don't have to rewrite any calls?
Or maybe I add it to its own file and just import where I'm going to build a query? Like replace this:
You just need to add that code before you actually perform any queries. You don't need to modify any other code.
Something like this should work (I think)
// in sequelize-fixes.jsconstSqlString=require("sequelize/lib/sql-string");SqlString.original_escape=SqlString.escape;SqlString.escape=functionescape(val,timeZone,dialect,format){if(typeofval==='string'){returnSqlString.original_escape(newString(val),timeZone,dialect,format);}returnSqlString.original_escape(val,timeZone,dialect,format);}// in index.jsrequire('./sequelize-fixes');importSequelizefrom'sequelize';importconfigfrom'./inpatientDBConfig';
Reacted by Jon Anderson
Reacted by Jon Anderson, KreativJos, Josemar Furegatti de Abreu Silva and Matheus Sá dos Santos
@dsbert your code works with all the string comparisons, that's great. But it can cause problems while working with nvarchar column type where we are storing multilingual data(specifically in case of korean, japanese, chinese language).
attaching a monkey patch where we can check column name and decide if we need to remove N or not.
dialect: mssqlFor issues and PRs. Things that involve MSSQL (and do not involve all dialects).existing workaroundFor issues. There is a known workaround for this issue.status: understoodFor issues. Applied when the issue is understood / reproducible.type: featureDEPRECATED: replace with the "feature" issue type
Activity
jerfowler commentedon Feb 27, 2018
You can use the shorter
CONVERTsyntax for the workaround and not need the data length if the value is under 30 characters:Here is how you would do it with model-generated queries:
However, I agree you should be able to specify whether a string value and STRING data type is ASCII or Unicode. Perhaps something like:
dbellandi commentedon Feb 28, 2018
Thanks @jerfowler -- that's helpful for the model-generated query workaround.
(CAST also defaults to varchar(30) if no length is specified -- I just prefer the CAST syntax for whatever reason.)
I had originally imagined adapting model definitions like:
To keep the type as Sequelize.STRING, avoiding needing to map a different type for other dialects.
Ideally, specifying the where object on model-generated queries would know based on type whether to prepend the N or not.
Raw queries would still benefit from being able to indicate something like sequelize.ascii or sequelize.unicode though.
sushantdhiman commentedon Apr 7, 2018
I would like to follow same pattern that we already use http://docs.sequelizejs.com/manual/tutorial/models-definition.html#data-types
damonmiller513 commentedon Nov 15, 2018
Any movement on this one? These implicit conversions are a performance killer! And would hate to muddy up all our queries with CONVERT() calls.
rconstantine commentedon Dec 7, 2018
Yeah, this is really needed. I was spinning my wheels for a while trying to figure out why my SSMS version took 1 second and the Sequelize version was taking up to 2 minutes.
rconstantine commentedon Dec 7, 2018
BTW, I got the following to work, which is shorter than the in-model solution presented above: I didn't need to use the escape function.
lr_rslt_id: {
[Op.eq]: Sequelize.literal(
'WBC')}
damonmiller513 commentedon Dec 7, 2018
I actually solved for this by creating a custom data types folder and I created a STRING_ASCII type so that I would not have to use the "literal" function everywhere.
Then where I initialize Sequelize I import all my custom data types and loop over them to make them available.
I am not sure if I did everything right but its been working for me.
I will say that while being able to extend the data types with your own is a great feature, however, for out of the box support for MSSQL this should not be necessary and this still should be addressed in the core code.
rconstantine commentedon Dec 8, 2018
@Damonmiller thanks for that. I will give that a try next week. I would love to not use literal everywhere as well.
Another issue I found was that if I mixed and matched different methods of declaring bits of my where clause, some of it wouldn't show up in the query. Before using literal anywhere, the query was properly constructed, so I don't know what was being screwed up behind the scenes.
So yeah, I'd like this to get fixed out-of-the-box at some point.
bjagadeesan commentedon Jan 26, 2019
@Damonmiller Thank you very much for the suggestion.
Do you know how do I use these extended datatype in raw query through replacement option ? . I have been looking into this as my query is performing poorly because of nvarchar implicit conversion.
damonmiller513 commentedon Jan 30, 2019
@BalajiJagadeesan Unfortunately I do not. I have not used a raw query at all so have not looked into a any workarounds.
ianthetechie commentedon Mar 11, 2019
Oh geez what the heck is going on here?! Now I know why the performance of our API has been tanking lately. Wow... Does nobody actually use MSSQL in production? This behavior is positively atrocious.
EDIT: Why is the label on this "feature?" This is a straight-up bug.
damonmiller513 commentedon Apr 19, 2019
We recently updated to Sequelize v5 and I can no longer get my previous custom data type to work. The constructor is fired, but the _stringify() method is ignored and it uses the parent method instead. Anyone know of a way to work around this? Really wish that we did not have to continue to workaround this very terrible bug in Sequelize for MSSQL.... Any chance of getting this fixed in the core?
damonmiller513 commentedon Apr 19, 2019
I've made sure that my custom data type is following this: http://docs.sequelizejs.com/manual/data-types.html#extending-datatypes. Still does not use my _stringify() method but does use my constructor. At this point, I have given up as I have a deadline to meet and I have gone back to Sequelize v4. :(
mvoorberg commentedon May 30, 2019
The escaping and 'N' prefix are applied based on the result of calling
typeofagainst the parameter. By wrapping the parameter in an Object, it avoids the statement that introduces the 'N' prefix.Therefore:
becomes:
...and the prefix is gone.
Read through the escape() function to see where it gets applied.
dsbert commentedon Jul 9, 2019
Based on some of the above comments, you can monkey patch this out using the following snippet.
scottclayton commentedon Nov 12, 2019
Thanks for the suggestion @dsbert . Your patch also works with replacements that are arrays of strings—e.g.
where in (:someArray).rconstantine commentedon Nov 15, 2019
@dsbert Sorry if I'm being obtuse, but where do I add your code? I have the following brief file structure:
index.js is the app entry point
appDB.js is where I have this:
and obviously the config is in the file just included.
also in appDB.js is this:
What I'm not understanding is where to include your code and also how to use it. I'm sure it's obvious, but I wasn't familiar with "monkey patching" before running into this thread. Will it simply overwrite the old way so I don't have to rewrite any calls?
Or maybe I add it to its own file and just import where I'm going to build a query? Like replace this:
with this:
dsbert commentedon Nov 16, 2019
@rconstantine
You just need to add that code before you actually perform any queries. You don't need to modify any other code.
Something like this should work (I think)
rconstantine commentedon Mar 10, 2022
Anyone know if this has been fixed? It's time I look at updating all dependencies for my primary application at work.
ashish19977 commentedon Jun 16, 2023
@dsbert your code works with all the string comparisons, that's great. But it can cause problems while working with nvarchar column type where we are storing multilingual data(specifically in case of korean, japanese, chinese language).
attaching a monkey patch where we can check column name and decide if we need to remove N or not.