Skip to content

UNIQUE identifier name too long in belongsToMany #9913

@lgaticaq

Description

@lgaticaq

What are you doing?

I am add a belongsToMany relation betwen two models

// PersonaCursoPrincipal.js
module.exports = (sequelize, DataTypes) => {
  const PersonaCursoPrincipal = sequelize.define(
    'PersonaCursoPrincipal',
    {
      id: {
        type: DataTypes.INTEGER(10),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      id_curso_principal: {
        type: DataTypes.INTEGER(5),
        allowNull: false,
        defaultValue: 0
      },
      id_producto_agrupador: {
        type: DataTypes.INTEGER(5),
        allowNull: false,
        defaultValue: 0
      },
      deleted: {
        type: DataTypes.INTEGER(1),
        allowNull: false,
        defaultValue: 0
      },
      created: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      },
      modified: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      }
    },
    {
      tableName: 'personas_cursos_principales',
      timestamps: false,
      defaultScope: {
        where: {
          deleted: 0
        }
      }
    }
  )
  PersonaCursoPrincipal.associate = models => {
    PersonaCursoPrincipal.belongsTo(models.CursoPrincipal, {
      foreignKey: 'id_curso_principal',
      constraints: false
    })
    PersonaCursoPrincipal.belongsTo(models.ProductoAgrupador, {
      foreignKey: 'id_producto_agrupador',
      constraints: false
    })
  }
  return PersonaCursoPrincipal
}
// CursoPrincipal.js
module.exports = (sequelize, DataTypes) => {
  const CursoPrincipal = sequelize.define(
    'CursoPrincipal',
    {
      id: {
        type: DataTypes.INTEGER(3),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      nombre: {
        type: DataTypes.STRING(255),
        allowNull: false,
        defaultValue: ''
      },
      deleted: {
        type: DataTypes.INTEGER(1),
        allowNull: false,
        defaultValue: 0
      },
      created: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      },
      modified: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      }
    },
    {
      tableName: 'cursos_principales',
      timestamps: false,
      defaultScope: {
        where: {
          deleted: 0
        }
      }
    }
  )
  return CursoPrincipal
}
// ProductoAgrupador.js
module.exports = (sequelize, DataTypes) => {
  const ProductoAgrupador = sequelize.define(
    'ProductoAgrupador',
    {
      id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      deleted: {
        type: DataTypes.INTEGER(1),
        allowNull: false,
        defaultValue: 0
      },
      created: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      },
      modified: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: new Date()
      }
    },
    {
      tableName: 'productos_agrupadores',
      timestamps: false,
      defaultScope: {
        where: {
          deleted: 0
        }
      }
    }
  )
  return ProductoAgrupador
}
// index.js
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const logging = console.log // eslint-disable-line
const DATABASE = process.env.DATABASE || 'mysql://root:root@localhost/test'
const sequelize = new Sequelize(DATABASE, {
  logging: process.env.SEQUELIZE_DEBUG === 'true' ? logging : false,
  operatorsAliases: false
})
const db = {}
const models = fs
  .readdirSync(__dirname)
  .filter(
    file =>
      file.indexOf('.') !== 0 &&
      file !== path.basename(module.filename) &&
      file.slice(-3) === '.js'
  )
  .reduce((acc, file) => {
    const model = sequelize.import(path.join(__dirname, file))
    acc[model.name] = model
    return acc
  }, {})
Object.assign(db, models)
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})
db.sequelize = sequelize
db.Sequelize = Sequelize
db.CursoPrincipal.belongsToMany(db.ProductoAgrupador, {
  through: 'PersonaCursoPrincipal',
  foreignKey: 'id_curso_principal'
})
db.ProductoAgrupador.belongsToMany(db.CursoPrincipal, {
  through: 'PersonaCursoPrincipal',
  foreignKey: 'id_producto_agrupador'
})
db.sequelize.sync()

What do you expect to happen?

I wanted create tables in db with relations

What is actually happening?

But the throw an error

CREATE TABLE IF NOT EXISTS `personas_cursos_principales` (
  `id` INTEGER(10) NOT NULL auto_increment ,
  `id_persona` INTEGER(11) NOT NULL DEFAULT 0,
  `id_curso_principal` INTEGER(3) NOT NULL DEFAULT 0,
  `id_producto_agrupador` INTEGER(11) NOT NULL DEFAULT 0,
  `deleted` INTEGER(1) NOT NULL DEFAULT 0,
  `created` DATETIME NOT NULL DEFAULT '2018-09-12 15:55:45',
  `modified` DATETIME NOT NULL DEFAULT '2018-09-12 15:55:45',
  UNIQUE `personas_cursos_principales_id_persona_id_producto_agrupador_unique` (
    `id_persona`, `id_producto_agrupador`
  ),
  UNIQUE `personas_cursos_principales_id_persona_id_curso_principal_unique` (
    `id_curso_principal`
  ),
  PRIMARY KEY (`id`),
  FOREIGN KEY (`id_persona`)
    REFERENCES `personas` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (`id_curso_principal`)
    REFERENCES `cursos_principales` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (`id_producto_agrupador`)
    REFERENCES `productos_agrupadores` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
SequelizeDatabaseError: Identifier name 'personas_cursos_principales_id_persona_id_producto_agrupador_unique' is too long
      at Query.formatError (node_modules/sequelize/lib/dialects/mysql/query.js:247:16)
      at Query.handler [as onResult] (node_modules/sequelize/lib/dialects/mysql/query.js:68:23)
      at Query.Command.execute (node_modules/mysql2/lib/commands/command.js:30:12)
      at Connection.handlePacket (node_modules/mysql2/lib/connection.js:513:28)
      at PacketParser.onPacket (node_modules/mysql2/lib/connection.js:81:16)
      at PacketParser.executeStart (node_modules/mysql2/lib/packet_parser.js:76:14)
      at Socket.<anonymous> (node_modules/mysql2/lib/connection.js:89:29)
      at addChunk (_stream_readable.js:283:12)
      at readableAddChunk (_stream_readable.js:264:11)
      at Socket.Readable.push (_stream_readable.js:219:10)
      at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

Dialect: mysql (mysql2)
Dialect version: 1.6.1 (mysql2)
Database version: 5.6.38
Sequelize version: 4.38.1
Tested with latest release: Yes, 4.38.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: featureDEPRECATED: replace with the "feature" issue type

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions