Skip to content

[MSSQL]DataTypes.STRING should be Varchar or NVarchar ? #6036

Description

@p2227

Activity

  1. janmeier commented on Jun 7, 2016

    @janmeier
    Member

    return 'NVARCHAR(' + this._length + ')';

  2. komeilshahmoradi commented on Dec 24, 2018

    @komeilshahmoradi

    version 4.42.0
    I still have this problem
    please, how to solve this problem ?

  3. durango commented on Dec 31, 2018

    @durango
    Member

    @komeilshahmoradi check out this issue #8533 might help guide you on how to extend data types to your liking. I am not sure why SequelizeJS decided to opt for nvarchar but it is, in my opinion, incorrect. I'll ask the team and see why this decision was made and what are our options for the future.

    Alternatively, if you don't mind using varchar(255) you can use ENUM but this isn't really ideal

    ENUM.prototype.toSql = function() {

    Reopening because it is an issue

  4. bjagadeesan commented on Jan 22, 2019

    @bjagadeesan

    version: 4.42.0

    I have the same problem. I need to use varchar instead of nvarchar. I execute raw queries through sequelize. The replacements always converts to nvarchar and it is a performance bottleneck for my operation. The regular query with varchar runs in under a second and the one with nvarchar runs anywhere from 30 to 45 seconds.

    I tried overriding the tosql() method, but I couldn't get the extended version to be used in the program. Any help on that is much appreciated.

    Below is the code .

    import {DataTypes} from "sequelize";
    
    DataTypes.STRING.prototype.toSql = function() {
    	if (!this._binary) {
    		return "VARCHAR(" + this._length + ")";
    	} else{
    		return "BINARY(" + this._length + ")";
    	}
    };
    
    export {DataTypes};
    

    But ideally, adding an option to choose between nvarchar and varchar will be much helpful.

  5. stale commented on Apr 22, 2019

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  6. SheTechie commented on Jun 3, 2021

    @SheTechie

    I am using "sequelize": "^5.21.5"
    And still this issue causing a major impact on our operations.

  7. nareshy-quisitive commented on Mar 18, 2022

    @nareshy-quisitive

    Any update on this issue? Its impacting application performace.

  8. added
    performance
    on Mar 18, 2022
  9. WikiRik commented on Mar 18, 2022

    @WikiRik
    Member

    @ephys I think you can answer this

  10. nareshy-quisitive commented on Mar 18, 2022

    @nareshy-quisitive

    Issue is

    const searchResults = await models.file.findAll({
            where: {
              path: {
                [Op.like]: `%${queryStr}%`
              }
            },
            attributes: ['path', 'uuid']
          })
    

    Above code executing following query
    select [uuid],[path] from [omn].[file] where [path] like N'%abc%'
    which is taking around 7sec to complete the query. But if I execute the same query by removing 'N' from the query I am getting the same response within 1sec.

    Note: path is varchar data type in MSSQL DataBase

  11. ephys commented on Mar 18, 2022

    @ephys
    Member

    I don't want to change what DataTypes.STRING produces, even in a SemVer MAJOR release, because it would make migrating too difficult. But I would like to deprecate DataTypes.STRING, see #14259

    In the meantime, there is a workaround you can use that we just documented. You can use VARCHAR like this in mssql:

    image

    As for generating 'string' instead of N'string', it will need to wait until we have DataTypes.VARCHAR & DataTypes.VARCHAR.N so we can generate the appropriate string based on the DataType. This part will be tracked in #9107

  12. added
    P4: nice to have
    on Mar 19, 2022
  13. nareshy-quisitive commented on Mar 24, 2022

    @nareshy-quisitive

    @ephys suggestions are not working. We are using the 5.22.4 version. Do we need to upgrade this to the latest version?

  14. ephys commented on Mar 24, 2022

    @ephys
    Member

    I did a quick test in a SSCCE running with mssql and the following code:

    class User extends Model {}
    
    User.init({
      firstName: 'VARCHAR(50)',
    }, {
      sequelize,
    });
    
    await sequelize.sync({ force: true });

    Which resulted in the following SQL:

    IF OBJECT_ID('[Users]', 'U') IS NOT NULL DROP TABLE [Users];
    
    IF OBJECT_ID('[Users]', 'U') IS NULL CREATE TABLE [Users] ([id] INTEGER NOT NULL IDENTITY(1,1) , [firstName] VARCHAR(50) NULL, [createdAt] DATETIMEOFFSET NOT NULL, [updatedAt] DATETIMEOFFSET NOT NULL, PRIMARY KEY ([id]));
    
    EXEC sys.sp_helpindex @objname = N'[Users]';
    

    I was running it using Sequelize 6, it may be the case that this is not supported in Sequelize 5. There is a small number of breaking changes in Sequelize 6, I definitely recommend upgrading: https://sequelize.org/master/manual/upgrade-to-v6.html

  15. nareshy-quisitive commented on Apr 12, 2022

    @nareshy-quisitive

    I have tested this with the latest version 6.18.0. still facing the same issue
    here is my test model class

    const config = require('../config/index')
    const _ = require('lodash')
    const sequelize = new Sequelize(config.get('database'), config.get('username'), config.get('password'), {
      dialect: config.get('dialect'),
      host: config.get('host'),
      logging: _.get(config, 'logging', console.log),
      benchmark: true,
      port: 1433,
      dialectOptions: {
        options: {
          encrypt: true,
          trustServerCertificate: true
        },
      }
    })
    class File extends Model { }
    
    File.init({
      uuid: {
        allowNull: false,
        autoIncrement: false,
        primaryKey: true,
        type: DataTypes.UUID
      },
      path: {
        type: 'VARCHAR(500)'
      }
    }, {
      sequelize,
      freezeTableName: true
    });
    (async () => {
      await sequelize.sync({ force: true });
      // Code here
    })();
    
    module.exports = File
    

    and i am using this model as

    const Op = Sequelize.Op;
    const file = require('./models/file')
    file.findOne({
        where:{
            path:{
                [Op.like]:'%-1001_1101.xml'
            }
        }
    }).then((result) => {
        console.log(JSON.stringify(result))
    }).catch((e) => {
        console.log(e)
    })
    

    This is producing following query

    SELECT [uuid], [path], [createdAt], [updatedAt] FROM [File] AS [File] WHERE [File].[path] LIKE N'%-1001_1101.xml' ORDER BY [File].[uuid] OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
    

    The issue is with the N char after like in query. How to fix this?

  16. ephys commented on Apr 12, 2022

    @ephys
    Member

    @nareshy-quisitive That part is tracked over here #9107 but we won't be able to do that until we have a proper non-n varchar type, which I opened a RFC for here #14259

  17. removed
    P4: nice to have
    on Mar 9, 2025
  18. added theissue type on Mar 9, 2025
  19. removed
    performance
    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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions