Skip to content

Why is unique not a validator? #2640

Closed

Description

@NathanFlurry

Hello,

In my opinion, the unique property should be a validator. However, I do understand it's not quite a "validator", since it isn't part of the library. However, it would make mine (and I assume other developer's) life easier, since all the error messages would then be in one, uniform-formated response. The user should be able to know if the username is taken, along with other things wrong with it like length (but it wouldn't be taken in the first but, but you see my point).

If you could consider changing this, that'd be great.

Thanks again!

Activity

  1. dkushner commented on Dec 1, 2014

    @dkushner

    As far as I know, unique constraint errors present as a special object called, funnily enough, UniqueConstraintError. You can catch this specific type of object in a catch-all or per-route error handler and construct a ValidationError from the data contained within it. Barring that, I'd generally recommend writing a custom validation function to do your checking before it even hits the DB. Unique database constraints are the last line of defense against an inconsistent data set, not really something to be leaned on for validation, in my opinion.

  2. NathanFlurry commented on Dec 1, 2014

    @NathanFlurry
    Author

    @dkushner - Yes, I'm suggesting they are presented in the same JSON structure as validation errors. But thanks for the suggestion, I might add some more validators to do this myself.

  3. dkushner commented on Dec 1, 2014

    @dkushner

    @zoyt, the validation errors are not presented in any "JSON" structure to my knowledge, they're issued as JavaScript objects with a prototype of ValidationError and contain a number of ValidationErrorItems. Perhaps I'm mistaken, I haven't revisited our error handling code in a while.

  4. NathanFlurry commented on Dec 1, 2014

    @NathanFlurry
    Author

    @dkushner, Sorry, I wasn't very clear. What I meant was that, in my opinion, when an error comes up with an item not being unique, it should show up like an error in a validator. Here's what an error for in the validators looks like:

    {  
       "name":"SequelizeValidationError",
       "message":"Validation error",
       "errors":[  
          {  
             "message":"Username needs to be between 3 and 32 characters.",
             "type":"Validation error",
             "path":"username",
             "value":"Username needs to be between 3 and 32 characters.",
             "__raw":"Username needs to be between 3 and 32 characters."
          }
       ]
    }
    

    However, I figured out that I did not design my error system appropriately at all, so this is not really an issue.
    Thanks!

  5. janmeier commented on Dec 1, 2014

    @janmeier
    Member

    Well it depends on how you are using your unique constraint. If you expect there to be items violating the uniqueness constraint often, then yes it might make sense to do a SELECT in the validation phase. But in other cases the violation will happen very rarely, so there is no need to check before every insert.

    I can see the usecase for an actual validator for unique:

    attr: { 
      type ...
      validate: {
        unique: true
      }
    }

    Which would do a SELECT in the validation phase

  6. added
    type: feature
    on Dec 1, 2014
  7. yourcelf commented on Apr 28, 2015

    @yourcelf

    I've done this myself by defining an isUnique validator function, which I can reuse across different models that need unique fields:

    isUnique = function(modelName, field) {
      return function(value, next) {
        var Model = require("../models")[modelName];
        var query = {};
        query[field] = value;
        Model.find({where: query, attributes: ["id"]}).then(function(obj) {
          if (obj) {
            next(field + ' "' + value + '" is already in use');
          } else {
            next();
          }
        });
      };
    }
    

    In the model definition:

    validate: {
      isUnique: isUnique("User", "username")
    }
    
  8. janmeier commented on Apr 29, 2015

    @janmeier
    Member

    @yourcelf You are welcome to provide a pullrequest with that functionality. If we include the functionality in sequelize you wouldn't need to pass the table and column name either, since internal validators already have access to that.

    +1 If you can make it support composite unique keys as well! :)

  9. danpaz commented on May 15, 2015

    @danpaz

    +1 I'm having a possibly related problem with the differing implementation between UniqueConstraintError and ValidationError. In particular, since #1024 it is possible to customize the unique constraint error message, but that message doesn't propagate down to the error item.

    { [SequelizeUniqueConstraintError: That email is already registered.]
      name: 'SequelizeUniqueConstraintError',
      message: 'That email is already registered.',  // <-- my custom message
      errors:
       [ { message: 'email must be unique', // <-- sequelize's default message that didn't get overwritten
           type: 'unique violation',
           path: 'email',
           value: '[email protected]' } ],
      fields: { email: '[email protected]' } }

    This means that in my route I need to catch UniqueConstraintErrors and modify them to use the custom message.

    ...
    .catch(sequelize.UniqueConstraintError, function(err) {
              err.errors.map(function (errItem) {
                errItem.message = err.message;
              });
    
              res.status(400).send(err);

    I wonder if this is more likely a bug or a consequence of database errors not being treated as validation errors?

    I would tend to agree with @janmeier that whether to validate uniqueness before hitting the db depends on how frequently you expect that unique constraint to be violated. For my use case, it makes sense to let the db handle unique violations because it happens so infrequently and avoids making an additional db request.

  10. vanwalj commented on May 15, 2015

    @vanwalj

    This may become problematic if you use transactions for example, and definitely not performance friendly :)

  11. BridgeAR commented on May 24, 2015

    @BridgeAR
    Contributor

    It's one query more than you need, thus slowing the average use case. As @janmeier mentioned, it would only be a good consideration to use something like that if your application relies on a lot of unique duplicates (Edit: Probably more than 2/3 of all querys should be duplicates to legitimate something like this. If it's only 50%, there would still be a speed decrease). In most applications this is probably not the case.
    Besides that I'm always wondering if I'm the only one who'd never send out all model errors to the frontend as they occur... Those expose information that in most cases no one can handle in the frontend, provide information that the user should often not have and they are language specific so rewriting the application to support multiple languages will be... fun. Instead you could handle all errors in one place and decide what parts you really want to send to the frontend and how.

    To conclude: I'd not recommend implementing this into core. This might be a good choice for a plugin.

  12. angelxmoreno commented on Sep 3, 2015

    @angelxmoreno

    I will attempt to make a plugin for the use case mentioned by @janmeier

  13. angelxmoreno commented on Sep 3, 2015

    @angelxmoreno

    I started something sequelize-isunique-validator

  14. fadec commented on Feb 25, 2017

    @fadec

    Using a select before an insert isn't always going to work with concurrent connections. Perhaps just try to insert or update and then check the connection for the error code.

    I'm using postgress (npm "pg") and a unique violation error looks like this...

    { error: duplicate key value violates unique constraint "category_name_idx"
        at Connection.parseE (/home/sam/ykcorner/server/node_modules/pg/lib/connection.js:554:11)
        at Connection.parseMessage (/home/sam/ykcorner/server/node_modules/pg/lib/connection.js:381:17)
        at Socket.<anonymous> (/home/sam/ykcorner/server/node_modules/pg/lib/connection.js:117:22)
        at emitOne (events.js:96:13)
        at Socket.emit (events.js:189:7)
        at readableAddChunk (_stream_readable.js:176:18)
        at Socket.Readable.push (_stream_readable.js:134:10)
        at TCP.onread (net.js:551:20)
      name: 'error',
      length: 203,
      severity: 'ERROR',
      code: '23505',
      detail: 'Key (name)=(Dogs) already exists.',
      hint: undefined,
      position: undefined,
      internalPosition: undefined,
      internalQuery: undefined,
      where: undefined,
      schema: 'catalog',
      table: 'category',
      column: undefined,
      dataType: undefined,
      constraint: 'category_name_idx',
      file: 'nbtinsert.c',
      line: '433',
      routine: '_bt_check_unique' }
    

    DB error codes are the most correct and performant way to go. Look up SQLSTATE code 23505 (unique violation) in the following different docs and you'll see there is some level of standardization. Unfortunately, each product will probably need its own shim to generate nice error messages.

    https://www.postgresql.org/docs/current/static/errcodes-appendix.html
    http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzala/rzalaccl.htm
    http://docs.oracle.com/javadb/10.6.2.1/ref/rrefexcept71493.html

  15. 3 remaining items

  16. valeriu-dev commented on Nov 18, 2017

    @valeriu-dev

    Example of isUnique validator:

    phone: {
          type: Sequelize.STRING(18),
          validate: {
            isUnique(value, next) {
              user.find({
                where: { phone: value },
                attributes: ['id']
              }).done((user) => {
                if (user)
                  return next('errors.phone.unique');
    
                next();
              });
            }
          }
    
  17. stale commented on Jul 23, 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 🙂

  18. papb commented on Jul 31, 2019

    @papb
    Member

    I think most people, including your "average user", would prefer this approach as you wouldn't have to memorize that "some validators go here, some go there".

    This is a fair point, but I'd say this is a matter of documentation. There is a reason for the UNIQUE constraint to be in a different place than the other usual validators. The reason is that the UNIQUE constraint is enforced at the database level, i.e., the SQL itself contains this validator; the other usual validators are just javascript checks performed by sequelize.

  19. added
    docs
    and removed
    type: feature
    on Jul 31, 2019
  20. self-assigned this
    on Jul 31, 2019
  21. added
    status: wip
    and removed on Sep 6, 2019
  22. removed
    status: wip
    on Jan 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions