Skip to content

Using defaultValue with mssql breaks sequelize.sync({ alter: true }) #17405

Closed as not planned

Description

@bluepuma77

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

Setting defaultValue with sequelize v6 with Microsoft SQL Server 2019 breaks sequelize.sync({ alter: true }).

It seems this is a know issue for years.

I created a docker-compose.yml file to spin up necessary mssql/server:2019 and node, Javascript is inline.

Run docker compose up --force-recreate to always have updated inline script.

Reproducible Example

# docker-compose.yml
services:
  sqlserver:
    image: mcr.microsoft.com/mssql/server:2019-latest
    container_name: sqlserver
    environment:
      ACCEPT_EULA: 'Y'
      SA_PASSWORD: 'Passw0rd!'

  node:
    image: node:20
    container_name: node
    configs:
      - source: package.json
        target: /home/node/package.json
      - source: index.js
        target: /home/node/index.js
    entrypoint: ""
    command: >
      sh -c "cd /home/node && npm install sequelize tedious sqlite3 && node index.js"

configs:

  package.json:
    content: |
      {
        "name": "sequelize-mssql",
        "version": "1.0.0",
        "main": "index.js",
        "type": "module",
        "scripts": {
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "license": "ISC"
      }

  index.js:
    content: |

      // ***** JAVASCRIPT STARTS HERE *****
      import { Sequelize, DataTypes } from 'sequelize';

      //const sequelize = new Sequelize('sqlite::memory:');
      const sequelize = new Sequelize('tempdb', 'SA', 'Passw0rd!', {
          host: 'sqlserver',
          dialect: 'mssql',
          dialectOptions: {
              options: {
                  encrypt: true,
                  trustServerCertificate: true
              }
          }
      });
      await sequelize.authenticate();

      const User = sequelize.define('User', {
        username: DataTypes.STRING,
        birthday: DataTypes.DATE,
        default: {
          type: DataTypes.STRING,
          defaultValue: 'test'
        },
        enum: {
          type: DataTypes.ENUM,
          values: ['1', '2', '3']
        }
      });

      console.log('Force table re-creation')
      await sequelize.sync({ force: true })

      const jane = await User.create({
        username: 'janedoe',
        birthday: new Date(1980, 6, 20),
      });

      const users = await User.findAll();
      console.log('users', users)

      console.log('Alter table')
      await sequelize.sync({ alter: true })

What do you expect to happen?

Successful migration, in this case nothing should happen, no errors.

What is actually happening?

node       | Alter table
node       | Executing (default): SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = N'Users' AND TABLE_SCHEMA = N'dbo'
node       | Executing (default): SELECT c.COLUMN_NAME AS 'Name', c.DATA_TYPE AS 'Type', c.CHARACTER_MAXIMUM_LENGTH AS 'Length', c.IS_NULLABLE as 'IsNull', COLUMN_DEFAULT AS 'Default', pk.CONSTRAINT_TYPE AS 'Constraint', COLUMNPROPERTY(OBJECT_ID('[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']'), c.COLUMN_NAME, 'IsIdentity') as 'IsIdentity', CAST(prop.value AS NVARCHAR) AS 'Comment' FROM INFORMATION_SCHEMA.TABLES t INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA LEFT JOIN (SELECT tc.table_schema, tc.table_name,  cu.column_name, tc.CONSTRAINT_TYPE  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc  JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE  cu  ON tc.table_schema=cu.table_schema and tc.table_name=cu.table_name  and tc.constraint_name=cu.constraint_name  and tc.CONSTRAINT_TYPE='PRIMARY KEY') pk  ON pk.table_schema=c.table_schema  AND pk.table_name=c.table_name  AND pk.column_name=c.column_name  INNER JOIN sys.columns AS sc ON sc.object_id = OBJECT_ID('[' + t.TABLE_SCHEMA + '].[' + t.TABLE_NAME + ']') AND sc.name = c.column_name LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id AND prop.minor_id = sc.column_id AND prop.name = 'MS_Description' WHERE t.TABLE_NAME = 'Users'
node       | Executing (default): SELECT constraint_name = OBJ.NAME, constraintName = OBJ.NAME, constraintCatalog = 'tempdb', constraintSchema = SCHEMA_NAME(OBJ.SCHEMA_ID), tableName = TB.NAME, tableSchema = SCHEMA_NAME(TB.SCHEMA_ID), tableCatalog = 'tempdb', columnName = COL.NAME, referencedTableSchema = SCHEMA_NAME(RTB.SCHEMA_ID), referencedCatalog = 'tempdb', referencedTableName = RTB.NAME, referencedColumnName = RCOL.NAME FROM sys.foreign_key_columns FKC INNER JOIN sys.objects OBJ ON OBJ.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID INNER JOIN sys.tables TB ON TB.OBJECT_ID = FKC.PARENT_OBJECT_ID INNER JOIN sys.columns COL ON COL.COLUMN_ID = PARENT_COLUMN_ID AND COL.OBJECT_ID = TB.OBJECT_ID INNER JOIN sys.tables RTB ON RTB.OBJECT_ID = FKC.REFERENCED_OBJECT_ID INNER JOIN sys.columns RCOL ON RCOL.COLUMN_ID = REFERENCED_COLUMN_ID AND RCOL.OBJECT_ID = RTB.OBJECT_ID WHERE TB.NAME ='Users'
node       | Executing (default): ALTER TABLE [Users] ALTER COLUMN [username] NVARCHAR(255) NULL;
node       | Executing (default): ALTER TABLE [Users] ALTER COLUMN [birthday] DATETIMEOFFSET NULL;
node       | Executing (default): ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';
node       | node:internal/modules/run_main:129
node       |     triggerUncaughtException(
node       |     ^
node       |
node       | Error
node       |     at Query.run (/home/node/node_modules/sequelize/lib/dialects/mssql/query.js:107:25)
node       |     at /home/node/node_modules/sequelize/lib/sequelize.js:315:28
node       |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
node       |     at async User.sync (/home/node/node_modules/sequelize/lib/model.js:984:11)
node       |     at async Sequelize.sync (/home/node/node_modules/sequelize/lib/sequelize.js:377:9)
node       |     at async file:///home/node/index.js:41:1 {
node       |   name: 'SequelizeDatabaseError',
node       |   parent: RequestError: Incorrect syntax near the keyword 'DEFAULT'.
node       |       at RequestTokenHandler.onErrorMessage (/home/node/node_modules/tedious/lib/token/handler.js:286:21)
node       |       at Readable.<anonymous> (/home/node/node_modules/tedious/lib/token/token-stream-parser.js:18:33)
node       |       at Readable.emit (node:events:519:28)
node       |       at addChunk (node:internal/streams/readable:559:12)
node       |       at readableAddChunkPushObjectMode (node:internal/streams/readable:536:3)
node       |       at Readable.push (node:internal/streams/readable:391:5)
node       |       at nextAsync (node:internal/streams/from:194:22)
node       |       at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
node       |     code: 'EREQUEST',
node       |     number: 156,
node       |     state: 1,
node       |     class: 15,
node       |     serverName: 'a7302390c4ae',
node       |     procName: '',
node       |     lineNumber: 1,
node       |     sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node       |     parameters: undefined
node       |   },
node       |   original: RequestError: Incorrect syntax near the keyword 'DEFAULT'.
node       |       at RequestTokenHandler.onErrorMessage (/home/node/node_modules/tedious/lib/token/handler.js:286:21)
node       |       at Readable.<anonymous> (/home/node/node_modules/tedious/lib/token/token-stream-parser.js:18:33)
node       |       at Readable.emit (node:events:519:28)
node       |       at addChunk (node:internal/streams/readable:559:12)
node       |       at readableAddChunkPushObjectMode (node:internal/streams/readable:536:3)
node       |       at Readable.push (node:internal/streams/readable:391:5)
node       |       at nextAsync (node:internal/streams/from:194:22)
node       |       at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
node       |     code: 'EREQUEST',
node       |     number: 156,
node       |     state: 1,
node       |     class: 15,
node       |     serverName: 'a7302390c4ae',
node       |     procName: '',
node       |     lineNumber: 1,
node       |     sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node       |     parameters: undefined
node       |   },
node       |   sql: "ALTER TABLE [Users] ALTER COLUMN [default] NVARCHAR(255) DEFAULT N'test';",
node       |   parameters: {}
node       | }
node       |
node       | Node.js v20.15.0
node exited with code 1

Environment

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance. (And don't know SQL, sequelize, tedious 😄)
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. added
    pending-approval
    type: bug
    on Jun 26, 2024
  2. bluepuma77 commented on Jun 26, 2024

    @bluepuma77
    Author

    Another related issue. I hope the easy option to reproduce helps.

  3. bluepuma77 commented on Jun 27, 2024

    @bluepuma77
    Author

    Interestingly, it works with UUID defaultValue:

        uuid: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            allowNull: false,
        },
    

    but breaks with STRING defaultValue:

        props: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '[]',
        }
    
  4. arunvvijayan commented on Oct 7, 2024

    @arunvvijayan

    ALTER TABLE [co_business] ALTER COLUMN [sites_allowed] INTEGER NOT NULL DEFAULT 1;

    this not the write SQL query to Alter and add an default constraint

    should be like this

    ALTER TABLE [co_business] ALTER COLUMN [sites_allowed] INTEGER NOT NULL;
    ALTER TABLE [co_business] ADD CONSTRAINT DF_sites_allowed DEFAULT 1 FOR [sites_allowed];

    but in the sequelize node modules -> node_modules\sequelize\lib\dialects\mssql\query-generator.js.map

    there is an function called changeColumnQuery(tableName, attributes)

    changeColumnQuery(tableName, attributes) {
        const attrString = [], constraintString = [];
        let commentString = "";
        for (const attributeName in attributes) {
          const quotedAttrName = this.quoteIdentifier(attributeName);
          let definition = attributes[attributeName];
          if (definition.includes("COMMENT ")) {
            const commentMatch = definition.match(/^(.+) (COMMENT.*)$/);
            const commentText = commentMatch[2].replace("COMMENT", "").trim();
            commentString += this.commentTemplate(commentText, tableName, attributeName);
            definition = commentMatch[1];
          }
          if (definition.includes("REFERENCES")) {
            constraintString.push(`FOREIGN KEY (${quotedAttrName}) ${definition.replace(/.+?(?=REFERENCES)/, "")}`);
          } else {
            attrString.push(`${quotedAttrName} ${definition}`);
          }
        }
        return Utils.joinSQLFragments([
          "ALTER TABLE",
          this.quoteTable(tableName),
          **attrString.length && `ALTER COLUMN ${attrString.join(", ")}`,
          constraintString.length && `ADD ${constraintString.join(", ")}`,**
          ";",
          commentString
        ]);
      }
    

    the highlighted lines have to update properly by @sequelize team,

    for the time being we can change the code,

    changeColumnQuery(tableName, attributes) {
      const alterColumnString = [];
      const addConstraintString = [];
     const constraintString = [];
      let commentString = "";
    
      for (const attributeName in attributes) {
        const quotedAttrName = this.quoteIdentifier(attributeName);
        let definition = attributes[attributeName];
    
        // Handle COMMENT in the definition
        if (definition.includes("COMMENT ")) {
          const commentMatch = definition.match(/^(.+) (COMMENT.*)$/);
          const commentText = commentMatch[2].replace("COMMENT", "").trim();
          commentString += this.commentTemplate(commentText, tableName, attributeName);
          definition = commentMatch[1];
        }
    
        if (definition.includes("REFERENCES")) {
          constraintString.push(`FOREIGN KEY (${quotedAttrName}) ${definition.replace(/.+?(?=REFERENCES)/, "")}`);
        }
    
        // Handle ALTER COLUMN logic
        if (!definition.includes("REFERENCES")) {
          // Alter column to modify its structure (e.g., NOT NULL)
          
          
          // Check for default value, and add a constraint separately
          if (definition.includes("DEFAULT")) {
            
              const defaultIndex = definition.indexOf("DEFAULT");
    
              const newDefinition = definition.substring(0, defaultIndex).trim();
    
             const defaultValue = definition.match(/DEFAULT\s+(.+)/)[1].trim();
           
            alterColumnString.push(`${quotedAttrName} ${newDefinition }`);
    
            addConstraintString.push(`CONSTRAINT DF_${attributeName} DEFAULT ${defaultValue} FOR ${quotedAttrName}`);
          } else{
           alterColumnString.push(`${quotedAttrName} ${definition}`);
          }
        }
      }
    
      // Construct SQL for altering the column and adding the default constraint
      return Utils.joinSQLFragments([
        "ALTER TABLE", this.quoteTable(tableName),
        alterColumnString.length && `ALTER COLUMN ${alterColumnString.join(", ")}`,";",  // Alter columns
       constraintString.length && 
        addConstraintString.length > 0 && `ALTER TABLE ${this.quoteTable(tableName)} ADD ${addConstraintString.join(", ")}`,  // Add default 
       constraintString.length && `ADD ${constraintString.join(", ")}`,
        ";",
        commentString  // Add comments if present
      ]);
    }
    

    this way we have add the default value to the MSSQL database table columns if you are using db.sync{alter: true}

    But if already Default Value present you should delete first and then you have to use the command

    appreciate if any find the proper solution

  5. arunvvijayan commented on Oct 7, 2024

    @arunvvijayan

    if you are using db.sync{alter: false}

    in -> node_modules\sequelize\lib\dialects\mssql\query-generator.js
    Add the DataTypes you want to add default value

    normalizeAttribute(attribute) {
        if (!_.isPlainObject(attribute)) {
          attribute = { type: attribute };
        }
        if (!attribute.type)
          return attribute;
        attribute.type = this.normalizeDataType(attribute.type);
        if (Object.prototype.hasOwnProperty.call(attribute, "defaultValue")) {
    
          **const defaultTypes = [
            DataTypes.NOW, 
            DataTypes.UUIDV1, 
            DataTypes.UUIDV4,
            DataTypes.INTEGER, // Example: handling INTEGER
            DataTypes.STRING,
            DataTypes.DECIMAL,
            DataTypes.TEXT,
            DataTypes.CHAR  // Example: handling STRING
            // Add more types as necessary
          ];**
    
          if (typeof attribute.defaultValue === "function" && defaultTypes.includes(attribute.defaultValue)) {
            attribute.defaultValue = new attribute.defaultValue();
          }
          
        }
        if (attribute.type instanceof DataTypes.ENUM) {
          if (attribute.values) {
            attribute.type.values = attribute.type.options.values = attribute.values;
          } else {
            attribute.values = attribute.type.values;
          }
          if (!attribute.values.length) {
            throw new Error("Values for ENUM have not been defined.");
          }
        }
        return attribute;
      }
    

    then

    attributeToSQL(attribute, options) {
        if (!_.isPlainObject(attribute)) {
          attribute = {
            type: attribute
          };
        }
        if (attribute.references) {
          if (attribute.Model && attribute.Model.tableName === attribute.references.model) {
            this.sequelize.log("MSSQL does not support self referencial constraints, we will remove it but we recommend restructuring your query");
            attribute.onDelete = "";
            attribute.onUpdate = "";
          }
        }
        let template;
        if (attribute.type instanceof DataTypes.ENUM) {
          if (attribute.type.values && !attribute.values)
            attribute.values = attribute.type.values;
          template = attribute.type.toSql();
          template += ` CHECK (${this.quoteIdentifier(attribute.field)} IN(${attribute.values.map((value) => {
            return this.escape(value);
          }).join(", ")}))`;
          return template;
        }
        template = attribute.type.toString();
        if (attribute.allowNull === false) {
          template += " NOT NULL";
        } else if (!attribute.primaryKey && !Utils.defaultValueSchemable(attribute.defaultValue)) {
          template += " NULL";
        }
        if (attribute.autoIncrement) {
          template += " IDENTITY(1,1)";
        }
        if (attribute.type !== "TEXT" && attribute.type._binary !== true && Utils.defaultValueSchemable(attribute.defaultValue)) {
          //template += ` DEFAULT ${this.escape(attribute.defaultValue)}`; // Orginal Code
         
    

    const itemvalue = this.escape(attribute.defaultValue);
    let newValue = itemvalue.startsWith("N") ? itemvalue.slice(1) : itemvalue;

      // Now correctly append the default value to the template
      template += ` DEFAULT ${newValue}`;
    
    }
      if (attribute.unique === true) {
        template += " UNIQUE";
      }
      if (attribute.primaryKey) {
        template += " PRIMARY KEY";
      }
      if ((!options || !options.withoutForeignKeyConstraints) && attribute.references) {
        template += ` REFERENCES ${this.quoteTable(attribute.references.model)}`;
        if (attribute.references.key) {
          template += ` (${this.quoteIdentifier(attribute.references.key)})`;
        } else {
          template += ` (${this.quoteIdentifier("id")})`;
        }
        if (attribute.onDelete) {
          template += ` ON DELETE ${attribute.onDelete.toUpperCase()}`;
        }
        if (attribute.onUpdate) {
          template += ` ON UPDATE ${attribute.onUpdate.toUpperCase()}`;
        }
      }
      if (attribute.comment && typeof attribute.comment === "string") {
        template += ` COMMENT ${attribute.comment}`;
      }
      return template;
    }
    

    By Adding the bellow code you can eliminate the N before the default values like DEFAULT N'T' -> DEFAULT 'T'
    this will be working solution if you are using db.sync({alter: false})
    I have done this and working fine. until we go for an column updates in existing table with data this solution is fine

    const itemvalue = this.escape(attribute.defaultValue);
        let newValue = itemvalue.startsWith("N") ? itemvalue.slice(1) : itemvalue;
        
        // Now correctly append the default value to the template
        template += ` DEFAULT ${newValue}`;
    

    @nodejs @sequelize teams should solve this issue.

  6. WikiRik commented on Oct 9, 2024

    @WikiRik
    Member

    I'm closing this in favour of #14294

    As was mentioned there by one of the maintainers;

    Unfortunately sync({ alter }) has a large number of bugs, but fixing them is low on our priority list.
    If you do end up having the time to resolve this issue, a PR would be fantastic :)

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

    pending-approvaltype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions