Skip to content

UNIQUE identifier name too long in belongsToMany #9913

Closed

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

Activity

  1. added a commit that references this issue on Sep 12, 2018
    32cf738
  2. added
    type: feature
    on Sep 13, 2018
  3. RobertYoung commented on Oct 16, 2018

    @RobertYoung

    Which version of sequelize can I find this change in? It doesn't appear to be in the latest release of v4

  4. sushantdhiman commented on Oct 16, 2018

    @sushantdhiman
    Contributor

    @RobertYoung Not released, will be available in 5.0.0-beta.13

  5. RobertYoung commented on Oct 16, 2018

    @RobertYoung

    Cool, thanks for the quick response

  6. marcogbarcellos commented on Mar 19, 2019

    @marcogbarcellos
    Contributor

    Just updating this issue, but please correct me if I'm wrong... With v5 release We have this feature available through defining an uniqueKey property inside the belongsToMany option.

    Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })
    

    You can also check in the associations file on the docs of the project: https://github.com/sequelize/sequelize/blob/master/docs/associations.md

  7. iam-hussain commented on Jun 9, 2020

    @iam-hussain

    I prefer sequelize sync method with composite unique, If not passing indexes name u will get a error as below on adding many indexes in index array.

    error: SequelizeDatabaseError: Identifier name 'LONG_NAME' is too long

    https://stackoverflow.com/questions/42195348/how-to-define-unique-index-on-multiple-columns-in-sequelize/42199137

    module.exports = function (sequelize: any, DataTypes: any) { return sequelize.define('muln_user_goals_transaction', { id: { type: DataTypes.INTEGER(11), allowNull: false, autoIncrement: true, primaryKey: true, }, name: { type: DataTypes.STRING(), allowNull: false, }, email: { type: DataTypes.STRING(), allowNull: false, }, phone: { type: DataTypes.STRING(), allowNull: false, }, amount: { type: DataTypes.INTEGER(8), allowNull: false }, deleted: { type: DataTypes.BOOLEAN, defaultValue: false, }, }, { tableName: 'muln_user_goals_transaction', timestamps: false, indexes: [ { name: 'unique_index', unique: true, fields: ['name', 'email', 'phone', 'amount', 'deleted'] } ], defaultScope: { where: { deleted: false } } }); };

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

    type: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions