databasesequelize.jspsql

null value in column "id" of relation violates not-null constraint with AutoIncrementIdentity via Sequelize


i've created a migration file and state field to be like the following. for an example "project" table , then i ready a seed file , but because of the following error that cause seed failure but if i change autoIncrementIdentiy to autoIncrement :true everything will works fine ,but i don't know why cannot i use "autoIncrementIdentiy i need to solve it , please share your idea on how to seed data it with autoIncrementIdentity

psql version: 17 (docker image)

Sequelize version: 6.37.5

Debever: 24.3.1

error:

"ERROR: null value in column "id" of relation "projects" violates not-null constraint
ERROR DETAIL: Failing row contains (null, {"theme": "light", "layout": "grid"}, Project Alpha, 2024-12-25 05:56:28.86+00, 2024-12-25 05:56:28.86+00).
"

Seed file:

const convertToString = (attributes) => `${JSON.stringify(attributes)}`;

    // Seed projects and get the inserted IDs
    await queryInterface.bulkInsert(
      "projects",
      [
        {
          attributes: convertToString({ layout: "grid", theme: "light" }),
          name: "Project Alpha",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        {
          attributes: convertToString({ layout: "flex", theme: "dark" }),
          name: "Project Beta",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      ],
      { returning: true }
    );

Migration File

await queryInterface.createTable("projects", {
  id: {
    primaryKey: true,
    type: Sequelize.INTEGER,
    autoIncrementIdentity: true,
  },
  attributes: {
    type: Sequelize.JSONB,
    allowNull: true,
  },
  name: {
    type: Sequelize.STRING(64),
    allowNull: false,
  },
  createdAt: {
    allowNull: false,
    type: Sequelize.DATE,
    defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"),
  },
  updatedAt: {
    allowNull: false,
    type: Sequelize.DATE,
    defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"),
    onUpdate: Sequelize.literal("CURRENT_TIMESTAMP"), // Automatically updates on modification
  },
});

Solution

  • autoIncrementIdentity option is set to false by default and works only in conjunction with autoIncrement option so you definitely need to turn both of them on to make it all work.

    See model initialization here

    attributes.column.autoIncrementIdentity
    default: false
    If true, combined with autoIncrement=true, will use Postgres GENERATED BY DEFAULT AS IDENTITY instead of SERIAL. Postgres 10+ only.