Skip to content

MSSQL: Implicit conversion causes table scan -- Prepending N to strings precludes index use on varchar columns #9107

Description

@dbellandi

What are you doing?

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.

create table names (
  name varchar(100) not null primary 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.

The code in question begins here.

Workaround

A workaround is possible for raw queries but not model-generated ones.

Example:

sequelize.query('select * from names where name=cast(:name as varchar(100)), { replacements: { name: 'hello' } });

Dialect: mssql
Database version: All (Tested SQL Server 2012/2016)
Sequelize version: 4.34.0
Tested with latest release: Yes

Activity

  1. jerfowler commented on Feb 27, 2018

    @jerfowler
    Contributor

    You can use the shorter CONVERT syntax for the workaround and not need the data length if the value is under 30 characters:

    sequelize.query('select * from courses where name = CONVERT(varchar, :name)', {
      replacements: {
        name: 'test1',
      }
    })
    

    Here is how you would do it with model-generated queries:

    const value = sequelize.escape('test1');
    Course.findAll({
      where: {
        name: {
          $eq: sequelize.literal(`CONVERT(varchar, ${value})`),
        }
      }
    })
    

    However, I agree you should be able to specify whether a string value and STRING data type is ASCII or Unicode. Perhaps something like:

    const ascii = sequelize.ascii('test1'); // 'test1'
    const unicode = sequelize.unicode('test1'); // N'test1'
    
    const Course = sequelize.define('course', {
      name: Sequelize.STRING, // Defaults to NVARCHAR for mssql (maintain backward compatability)
      nameAscii: Sequelize.ASCII, // Clearly uses VARCHAR type
      nameUnicode:  Sequelize.UNICODE, // Clearly uses NVARCHAR type
    });
    
    // select * from courses where nameAscii='test1' or nameUnicode=N'test1'
    sequelize.query('select * from courses where nameAscii=:nameAscii or nameUnicode=:nameUnicode', {
      replacements: {
        nameAscii: sequelize.ascii('test1'), 
        nameUnicode: sequelize.unicode('test1'),
      },
    });
    
    // SELECT [id], [name], [createdAt], [updatedAt] FROM [courses] AS [course] 
    // WHERE ([course].[nameAscii] = 'test1' OR [course].[nameUnicode] = N'test1');
    
    Course.findAll({
      where: {
        [Sequelize.Op.or]: [
          {
            nameAscii: {
              $eq: sequelize.ascii('test1'),
            },
          },
          {
            nameUnicode: {
              $eq: sequelize.unicode('test1'),
            },
          },
        ],
      },
    });
    
  2. dbellandi commented on Feb 28, 2018

    @dbellandi
    Author

    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:

    const Course = sequelize.define('course', {
      nameAscii: {
        type: Sequelize.STRING,
        ascii: true
      }
    });

    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.

  3. sushantdhiman commented on Apr 7, 2018

    @sushantdhiman
    Contributor
  4. added
    type: feature
    dialect: mssql
    on Apr 7, 2018
  5. damonmiller513 commented on Nov 15, 2018

    @damonmiller513

    Any movement on this one? These implicit conversions are a performance killer! And would hate to muddy up all our queries with CONVERT() calls.

  6. rconstantine commented on Dec 7, 2018

    @rconstantine

    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.

  7. rconstantine commented on Dec 7, 2018

    @rconstantine

    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')
    }

  8. damonmiller513 commented on Dec 7, 2018

    @damonmiller513

    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.

  9. rconstantine commented on Dec 8, 2018

    @rconstantine

    @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.

  10. bjagadeesan commented on Jan 26, 2019

    @bjagadeesan

    @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.

  11. damonmiller513 commented on Jan 30, 2019

    @damonmiller513

    @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.

  12. ianthetechie commented on Mar 11, 2019

    @ianthetechie

    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.

  13. damonmiller513 commented on Apr 19, 2019

    @damonmiller513

    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?

  14. damonmiller513 commented on Apr 19, 2019

    @damonmiller513

    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. :(

  15. mvoorberg commented on May 30, 2019

    @mvoorberg

    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: new String('hello') } });

    ...and the prefix is gone.

    Read through the escape() function to see where it gets applied.

  16. dsbert commented on Jul 9, 2019

    @dsbert

    Based on some of the above comments, you can monkey patch this out using the following snippet.

    const SqlString = require("sequelize/lib/sql-string");
    SqlString.original_escape = SqlString.escape;
    SqlString.escape = function escape(val, timeZone, dialect, format) {
      if (typeof val === 'string') {
        return SqlString.original_escape(new String(val), timeZone, dialect, format);
      }
      return SqlString.original_escape(val, timeZone, dialect, format);
    }
  17. scottclayton commented on Nov 12, 2019

    @scottclayton

    Thanks for the suggestion @dsbert . Your patch also works with replacements that are arrays of strings—e.g. where in (:someArray).

  18. rconstantine commented on Nov 15, 2019

    @rconstantine

    @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:

    import Sequelize from 'sequelize';
    import config from './inpatientDBConfig';

    and obviously the config is in the file just included.

    also in appDB.js is this:

    const seq2 = new Sequelize(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:

    [Op.eq]: Sequelize.literal(`'${filterObj.lr_csn}'`)

    with this:

    [Op.eq]: Sequelize.SqlString(filterObj.lr_csn)
  19. dsbert commented on Nov 16, 2019

    @dsbert

    @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)

    // in sequelize-fixes.js
    const SqlString = require("sequelize/lib/sql-string");
    SqlString.original_escape = SqlString.escape;
    SqlString.escape = function escape(val, timeZone, dialect, format) {
      if (typeof val === 'string') {
        return SqlString.original_escape(new String(val), timeZone, dialect, format);
      }
      return SqlString.original_escape(val, timeZone, dialect, format);
    }
    
    
    // in index.js
    require('./sequelize-fixes');
    import Sequelize from 'sequelize';
    import config from './inpatientDBConfig';
  20. added
    existing workaround
    status: understood
    on Jan 15, 2020
  21. rconstantine commented on Mar 10, 2022

    @rconstantine

    Anyone know if this has been fixed? It's time I look at updating all dependencies for my primary application at work.

  22. ashish19977 commented on Jun 16, 2023

    @ashish19977

    @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.

    const queryGenerator = require(/"sequelize/lib/dialects/abstract/query-generator");
    
    const originalEscape = queryGenerator.prototype.escape;
    const modifiedEscape = function(value, field, options) {
      const originalVal = originalEscape.call(this ,value, field, options)
      if (typeof value === 'string' && ['practice_id'].includes(field?.name)) {
        return originalVal.substring(0, 1) === 'N' ? originalVal.substring(1) : originalVal;
      }
      return originalVal;
    }
    queryGenerator.prototype.escape = modifiedEscape
  23. added theissue type on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dialect: mssqlexisting workaroundstatus: understoodtype: feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions