Skip to content

Many composite unique keys on same field #8148

Closed

Description

@glalaj

The schema:

TABLE person:
id (unique)
username (unique)
...

TABLE events:
id (unique)
person_id (foreign key to person.id, unique: person_start, unique: person_end)
event_start (unique: person_start)
event_end (unique: person_end), description
...

What I want to make happen:

I want to have two composite, unique keys. One key will make sure that there are no events that start at the same time involving the same person. The other key will make sure that there are no events that end at the same time involving the same person.

On a real-life scenario, every person may participate in as many events as they want even if they overlap, as long as they are present in both the start and end of the event. If two events start and / or end at the same time, the same person cannot be in two places at the same time, so they cannot participate in both events.

What is actually happening

I can create composite keys (by adding unique: 'key_name' in all fields that should create a unique combo).
But I cannot set more than one unique key in the same field (this case, person_id). Therefore I cannot create unique keys for both event_start and event_end.

Details

Dialect: mysql is priority, but I would prefer support for all dialects of sequelize
Sequelize version: 3.X.X

Activity

  1. Oikio commented on Sep 7, 2017

    @Oikio

    I have the same question regarding model definition.
    But you can create multiple composite keys using migrations with .addConstraint() method.

  2. stale commented on Dec 14, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  3. jilvin commented on Feb 12, 2018

    @jilvin

    This seems to be an important issue actually. There does not seem a provision to add a unique constraint as described below.

    table: blog_roles
    structure:
    id - INT - primary key
    role_name - VARCHAR(255) - unique - compositeIndex
    role_slug - VARCHAR(45) - unique - compositeIndex
    role_description - VARCHAR(2048)
    created_at TIMESTAMP
    updated_at TIMESTAMP

    ie role_name and role_slug should have unique constraint for each at the same time have a compositeIndex.

  4. jilvin commented on Feb 12, 2018

    @jilvin

    @sushantdhiman Could you please check on this when you get time?

  5. sushantdhiman commented on Feb 13, 2018

    @sushantdhiman
    Contributor

    This is actually quite easy to achieve if you look at docs http://docs.sequelizejs.com/manual/tutorial/models-definition.html#indexes

    const Model = sequelize.define('Model', {
      key1: {
        type: Sequelize.STRING,
        unique: true
      },
      key2: {
        type: Sequelize.STRING,
        unique: true
      }
    }, {
      indexes: [
        { fields: ['key1', 'key2'], unique: true }
      ]
    })

    This will create

    1. unique constraint on key1
    2. unique constraint on key2
    3. unique index on key1, key2
  6. glalaj commented on Feb 13, 2018

    @glalaj
    Author

    @sushantdhiman Your solution does seem to work, though I remember checking with the docs before posting the question. Not sure whether I missed it or it was e previous version of sequelize.

    Anyway, I'd suggest everybody concerned with the issue to give it a try (and read the docs :) )

  7. jilvin commented on Feb 13, 2018

    @jilvin

    @sushantdhiman Actually I knew there was a possible solution in that manner. I was wondering whether it will be good if one could implement it using just the unique key.

  8. sushantdhiman commented on Feb 14, 2018

    @sushantdhiman
    Contributor

    @jilvin Yes, using addConstraint you can do that (http://docs.sequelizejs.com/class/lib/query-interface.js~QueryInterface.html#instance-method-addConstraint)

    await sequelize.queryInterface.addConstraint('Table',  ['key1', 'key2'], {
      type: 'unique',
      name: 'custom_unique_constraint_name'
    })

    Downside of this approach is that constraint will not be generated with sync. As for model definition, currently there is no good way to express both composite and individual "unique constraint" (not indexes) on given set of keys.

  9. jilvin commented on Feb 14, 2018

    @jilvin

    @sushantdhiman @glalaj I think it would be great if such a feature can be provided in the future versions of sequelize.

  10. jilvin commented on Feb 28, 2018

    @jilvin

    @sushantdhiman What do you think?

  11. added
    type: feature
    and removed on Feb 28, 2018
  12. sushantdhiman commented on Feb 28, 2018

    @sushantdhiman
    Contributor

    constraints or references key works for me

  13. glalaj commented on Feb 28, 2018

    @glalaj
    Author

    I tried the following with Sequelize 3.23.4:

    model definition -> When db schema is being created from model definitions, indexes creates the two composite keys

    module.exports = function(sequelize, DataTypes) {
        var events = sequelize.define('events', {
            id: {
                type: DataTypes.BIGINT(20),
                allowNull: false,
                primaryKey: true,
                autoIncrement: true,
                unique: true
            },
           person_id: {
                type: DataTypes.INTEGER(11),
                allowNull: false
            },
            event_start: {
                type: DataTypes.DATE,
                allowNull: true
            },
            event_end: {
                type: DataTypes.DATE,
                allowNull: true
            },
            .....
        },
            {
            tableName: 'events',
            associate: function(models) {
                events.belongsTo(models.some_other_model, {foreignKey: 'some_other_fkey'});
                ....
            },
            indexes: [
                { fields: ['event_start', 'person_id'], unique: true },
                { fields: ['event_end', 'person_id'], unique: true }
            ]
        });
        return events;
    };
    

    Migration for old schema without the keys: -> When there is an existing schema without the composite keys, we could execute this migration file to update it. The migration failed (partially or completely) when there were rows violating any of the constraints, but I was expecting it.

    module.exports = {
      up: function (queryInterface, Sequelize) {
        queryInterface.addIndex('events', ['event_start', 'person_id'], {unique: true})
            .catch(function(err) {console.log('Adding unique constraint on event_start_person failed with error message: ',err.message);});
        queryInterface.addIndex('events', ['event_end', 'person_id'], {unique: true})
            .catch(function(err) {console.log('Adding unique constraint on  event_end_person failed with error message: ',err.message);});
      },
    
      down: function (queryInterface, Sequelize) {
        queryInterface.removeIndex('events', ['event_start', 'person_id'], {unique: true})
            .catch(function(err) {console.log('Removing unique constraint on event_start_person failed with error message: ',err.message);});
        queryInterface.removeIndex('events', ['event_end', 'person_id'], {unique: true})
            .catch(function(err) {console.log('Removing unique constraint on event_end_person failed with error message: ',err.message);});
      }
    };
    

    I have not and cannot try it with sync for now, though it would be a good idea for that feature to be available.

  14. jilvin commented on Mar 4, 2018

    @jilvin

    @sushantdhiman @glalaj

    I was wondering about the following case.

    table: blog_roles
    structure:
    id - INT - primary key
    role_name - VARCHAR(255) - unique
    role_slug - VARCHAR(45) - unique
    role_description - VARCHAR(2048)
    created_at TIMESTAMP
    updated_at TIMESTAMP

    In this case, if we already mark role_name and role_slug as unique, there does not arise a possibility where they might require a compositeIndex at all. Maybe that's why it was not included in Sequelize. I am not sure about this though. Can you think about it?

  15. jilvin commented on Mar 4, 2018

    @jilvin

    @sushantdhiman @glalaj

    Comment made by @glalaj

    The requirement specified by @glalaj seems a necessity though.

  16. glalaj commented on Mar 5, 2018

    @glalaj
    Author

    @jilvin : Yes, you are right. In your scenario there is no need to create a composite key made of role_name and role_slug because both fields are unique. That guarantees the degree of uniqueness that a composite key would, and more.

  17. stale commented on Jul 24, 2019

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

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