Skip to content

changeColumn does not remove NOT NULL contraint #9635

Description

@sigod

What are you doing?

await queryInterface.changeColumn('tariffs', 'operator_id', {
	type: Sequelize.INTEGER,
	allowNull: true, // note this
	references: {
		model: 'operators',
		key: 'id'
	},
});

What do you expect to happen?

I expect NOT NULL contraint to be removed from the column operator_id.

What is actually happening?

Nothing.

Except, operator_id_foreign_idx gets created. See #8147.

Output, either JSON or SQL

Dialect: postgres
Dialect version: 7.4.3
Database version: 9.6
Sequelize version: 4.37.10
Tested with latest release: Yes, tested with 4.38.0

Activity

  1. added
    type: bug
    on Jul 14, 2018
  2. mirkojotic commented on Jul 19, 2018

    @mirkojotic
    Contributor

    @sigod Have you tried excluding reference from changeColumn statement?

    like so:

    await queryInterface.changeColumn('tariffs', 'operator_id', {
    	type: Sequelize.INTEGER,
    	allowNull: true // note this
    });
    

    If this doesn't work, I'll look into fixing this behaviour.

  3. sigod commented on Jul 20, 2018

    @sigod
    Author

    If I remember correctly it then removes the foreign key.

  4. nsfm commented on Sep 17, 2018

    @nsfm

    I'm also experiencing this issue:

      up: function(queryInterface, Sequelize) {
        return queryInterface.changeColumn(table, column, {
          type: Sequelize.INTEGER,
          references: { model: 'orders', key: 'id' },
          allowNull: true
        });
      },
    
      down: function(queryInterface, Sequelize) {
        return queryInterface.changeColumn(table, column, {
          type: Sequelize.INTEGER,
          references: { model: 'orders', key: 'id' },
          allowNull: false
        });
      }
    

    The migration runs successfully, but there's no apparent change.

    I'll try without the references and see what happens.

  5. nsfm commented on Sep 17, 2018

    @nsfm

    Removing references from the changeColumn parameters worked - it changed allowNull to true without removing the foreign key. I assume that if I wanted to modify the constraint I'd use a combination of QueryInterface.removeConstraint and QueryInterface.addConstraint?

    I'm using Sequelize 4.38.0.

  6. srkimir commented on Nov 24, 2018

    @srkimir

    As @nsfm pointed out, following is working for me as well
    Sequelize CLI [Node: 8.12.0, CLI: 4.1.1, ORM: 4.38.0]

      up: (queryInterface, Sequelize) => {
        return queryInterface.changeColumn(tableName, columnName, {
          type: Sequelize.INTEGER,
          allowNull: true
        })
      },
    
      down: (queryInterface, Sequelize) => {
        return queryInterface.changeColumn(tableName, columnName, {
          type: Sequelize.INTEGER,
          allowNull: false
        })
      }
    
  7. BhuvaneshwaranR commented on Dec 31, 2018

    @BhuvaneshwaranR

    @srkimir Thanks. The aforementioned code is working.

  8. waldyrious commented on Mar 21, 2019

    @waldyrious
    Contributor

    The lack of the type property was the issue in my case:

    up(queryInterface, Sequelize) {
      return queryInterface.changeColumn(tableName, columnName, {
        allowNull: true
      })
    }

    doesn't work, but with

     up(queryInterface, Sequelize) {
       return queryInterface.changeColumn(tableName, columnName, {
    +    type: Sequelize.STRING,
         allowNull: true
       })
     }

    it works.

  9. LeoDoldan7 commented on May 24, 2019

    @LeoDoldan7

    It's good to mention that using changeColumn and setting allowNull: false DOES NOT remove the foreign key to the table, but it does remove the allowNull constraint. If you want to remove the foreign key, you have to use queryInterface.removeConstraint.

  10. steveify1 commented on Oct 15, 2020

    @steveify1
  11. vtolenti89 commented on Oct 30, 2020

    @vtolenti89

    I am also facing the same problem, but the above solutions did not work in my case. Here is my migration file:

      up: (queryInterface, Sequelize) => {
        return queryInterface.changeColumn('users', 'language_key', {
          type: Sequelize.STRING(5),
          onDelete: 'RESTRICT'
        })
      },
    
      down: (queryInterface, Sequelize) => {
        return queryInterface.changeColumn('users', 'language_key', {
          type: Sequelize.STRING(5),
          onDelete: 'CASCADE'
        })
      },
    };
    

    Any ideas what is mising?

  12. ThomasEg commented on Dec 3, 2020

    @ThomasEg

    I've had the same issues. I was adding a column to a MySQL table with a foreign key. So first adding the table allowing null(default=null), then running a migration step to populate the new column and finally a migrationstep to set allownull=false....

    But it isn't working 100% as expected...it runs fine...but the result is that the column is still nullable after the last step....

    I think it's because the "nullable property" is a really a property of the constraint of the foreign key and not of the column itself somehow... or at least somehow bound to it... if i try the same operation(set nullable=false) in MySQL workbench GUI and view the automatic generated SQL it seems to drop all contraints first, then apply the column change and then re-add the constraints...

    I think the lesson for me is to create the column WITHOUT the reference first(=no constraints)....then fill the column with the correct id's...and THEN apply the foreign key as the last step with allow-null=false...

  13. ThomasEg commented on Dec 3, 2020

    @ThomasEg

    Actually, i might think this is a bug...sortof...

    Running this does NOT make the column nullable, but it completes just fine and gives no errors:

        queryInterface.changeColumn(someTable, someColumn, {
          type: DataTypes.INTEGER,
          allowNull: false,
          references: { model: someOtherTable, key: 'id' },
        }),
    

    If i try the "same" thing using plain SQL:

        queryInterface.sequelize.query('ALTER TABLE someTable MODIFY someColumn INT(11) NOT NULL;'),
    

    ...i'll get an error:

    ERROR: Cannot change column 'someColumn': used in a foreign key constraint 'someConstraint'
    

    Shouldn't I get the same error during the first migration? If it had, i wouldn't have a gazillion columns to fix now :-/

  14. NeoN0x commented on Dec 16, 2020

    @NeoN0x

    I got the same issue.

    I'm doing a migration that adds a new column, update the information, and set the column to not nullable.

    // This does notwork
    await queryInterface.changeColumn('Documents', 'documentCategoryId', {
      type: Sequelize.INTEGER,
      allowNull: false,
      references: {
        model: 'DocumentCategories',
        key: 'id'
      }
    })
    

    // At this point, the column is nullable, but the reference is added

    But when splitting this, it seems to work.

    // This work using 2 changes instead
    await queryInterface.changeColumn('Documents', 'documentCategoryId', {
      type: Sequelize.INTEGER,
      allowNull: false
    })
    await queryInterface.changeColumn('Documents', 'documentCategoryId', {
      type: Sequelize.INTEGER,
      allowNull: false,
      references: {
        model: 'DocumentCategories',
        key: 'id'
      }
    })
    // At this point, the first one changed the column to being not nullable + adds the reference
    
  15. lilhamad commented on Jun 24, 2021

    @lilhamad

    MY OWN ISSUE WAS :
    I didn't change
    allowNull: false,
    allowNull: true,
    on my model.

  16. adi-manna commented on Sep 24, 2021

    @adi-manna

    sequelize's version: 6.6.5
    I think the issue was fixed because it worked for me:
    (both up and down functions)

      up: async (queryInterface, Sequelize) => {
        await queryInterface.changeColumn(
          'menu_item_review', 'restaurant_campaign_id',
          {
            type: Sequelize.INTEGER,
            allowNull: true, // Although not necessary - for the change to be clear
          },
        );
     
    
      down: async (queryInterface, Sequelize) => {
        await queryInterface.changeColumn(
          'menu_item_review', 'restaurant_campaign_id',
          {
            type: Sequelize.INTEGER,
            allowNull: false,
          },
        );
      };
    
    

    The 'references' is not needed it's just creating more and more FKs as you can see here:

    Screen Shot 2021-09-24 at 22 12 02

    Screen Shot 2021-09-24 at 22 12 29

  17. phu-viet-dang commented on May 7, 2023

    @phu-viet-dang

    If you guys want to change column that also a foreignKey, do not include the references, only type and allowNull is enough

          queryInterface.changeColumn({
            schema: schemaConfig.name,
            tableName: 'chat_sessions'
          }, 'to_user_id', {
            type: Sequelize.DataTypes.UUID,
            allowNull: true,
          })
    
  18. added theissue type on Mar 9, 2025
  19. removed
    type: bug
    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

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions