sequelize: using uuid as primary key with auto-generated default value causes not-null constraint violation error

using master branch with postgres:

  var User = sequelize.define('User', {
    'id': {
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    // etc

this does not work unless i remove primaryKey: true. it causes error: null value in column "id" violates not-null constraint. it seems like the default value is not being generated when the column/property is a foreign key.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 1
  • Comments: 25 (12 by maintainers)

Most upvoted comments

Sequelize.UUIDV4 is an alias of DataTypes.UUIDV4, but yeah stick to DataTypes

However, DataTypes.UUIDV4 cannot be used in migrations, it can only be used in Model.init or sequelize.define. This is because DataTypes.UUIDV4 is handled in JavaScript, not SQL.

Related to https://github.com/sequelize/sequelize/issues/13224

I seem to be having this exact same problem. Relevant snippet of my migration file:

  up: (queryInterface, Sequelize) => {
    return queryInterface
      .createTable("Users", {
        id: {
          primaryKey: true,
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4
        },

The error I get when trying to insert a new user is this:

"name": "error",
"length": 311,
"severity": "ERROR",
"code": "23502",
"detail": "Failing row contains (null, test, test, test@test.com, $2b$10$JaPqzJrITxYN9.mhdOwBFOCPWXcu9s2fNw9jnNllRob4QFoYOyCdy, 2019-11-21 22:59:52.103+00, 2019-11-21 22:59:52.103+00).",
"schema": "public",
"table": "Users",
"column": "id",
"file": "execMain.c",
"line": "2042",
"routine": "ExecConstraints",
"sql": "INSERT INTO \"Users\" (\"id\",\"name\",\"username\",\"email\",\"password\",\"createdAt\",\"updatedAt\") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6) RETURNING *;",

Unsure if I have to do something else, I simply followed the documentation. I’m using the latest sequelize and pg versions.

"pg": "^7.14.0",
"sequelize": "^5.21.2",
"sequelize-cli": "^5.5.1",

@cjroth found updated docs on this.

In your model, use

TheNameOfYourModel.init(
    {
      your_uuid_primary_key: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

The older docs say do defaultValue: Sequelize.UUIDV4 but that’s incorrect. Use defaultValue: DataTypes.UUIDv4 instead.