Skip to content

New way to declare indices - #1024

Merged
janmeier merged 3 commits into
sequelize:masterfrom
durango:newindex
Jan 26, 2014
Merged

janmeier merged 3 commits into
sequelize:masterfrom
durango:newindex

Conversation

@durango

@durango durango commented Oct 30, 2013

Copy link
Copy Markdown
Member

There's now a new way to declare indices within DAOFactories.. as per the example...

    it('allows multiple column unique keys to be defined', function(done) {
      var User = this.sequelize.define('UserWithUniqueUsername', {
        username: { type: Sequelize.STRING, unique: 'user_and_email' },
        email: { type: Sequelize.STRING, unique: 'user_and_email' },
        aCol: { type: Sequelize.STRING, unique: 'a_and_b' },
        bCol: { type: Sequelize.STRING, unique: 'a_and_b' }
      })

      User.sync({ force: true }).on('sql', function(sql) {
        expect(sql).to.match(/UNIQUE\s*(uniq_UserWithUniqueUsernames_username_email)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/)
        expect(sql).to.match(/UNIQUE\s*(uniq_UserWithUniqueUsernames_aCol_bCol)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/)
        done()
      })
    })

    it('allows us to customize the error message for unique constraint', function(done) {
      var User = this.sequelize.define('UserWithUniqueUsername', {
        username: { type: Sequelize.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' }},
        email: { type: Sequelize.STRING, unique: 'user_and_email' },
        aCol: { type: Sequelize.STRING, unique: 'a_and_b' },
        bCol: { type: Sequelize.STRING, unique: 'a_and_b' }
      })

      User.sync({ force: true }).success(function() {
        User.create({username: 'tobi', email: '[email protected]'}).success(function() {
          User.create({username: 'tobi', email: '[email protected]'}).error(function(err) {
            expect(err).to.equal('User and email must be unique')
            done()
          })
        })
      })
    })

    it("doesn't allow duplicated records with unique:true", function(done) {
      var User = this.sequelize.define('UserWithUniqueUsername', {
        username: { type: Sequelize.STRING, unique: true }
      })

      User.sync({ force: true }).success(function() {
        User.create({ username:'foo' }).success(function() {
          User.create({ username: 'foo' }).error(function(err) {
            expect(err).to.exist

            if (dialect === "sqlite") {
              expect(err.message).to.match(/.*SQLITE_CONSTRAINT.*/)
            }
            else if (Support.dialectIsMySQL()) {
              expect(err.message).to.match(/.*Duplicate\ entry.*/)
            } else {
              expect(err.message).to.match(/.*duplicate\ key\ value.*/)
            }

            done()
          })
        })
      })
    })

    it("raises an error if created object breaks definition contraints", function(done) {
      var UserNull = this.sequelize.define('UserWithNonNullSmth', {
        username: { type: Sequelize.STRING, unique: true },
        smth:     { type: Sequelize.STRING, allowNull: false }
      })

      this.sequelize.options.omitNull = false

      UserNull.sync({ force: true }).success(function() {
        UserNull.create({ username: 'foo2', smth: null }).error(function(err) {
          expect(err).to.exist

          if (Support.dialectIsMySQL()) {
            // We need to allow two different errors for MySQL, see:
            // http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_strict_trans_tables
            expect(err.message).to.match(/(Column 'smth' cannot be null|Field 'smth' doesn't have a default value)/)
          }
          else if (dialect === "sqlite") {
            expect(err.message).to.match(/.*SQLITE_CONSTRAINT.*/)
          } else {
            expect(err.message).to.match(/.*column "smth" violates not-null.*/)
          }

          UserNull.create({ username: 'foo', smth: 'foo' }).success(function() {
            UserNull.create({ username: 'foo', smth: 'bar' }).error(function(err) {
              expect(err).to.exist

              if (dialect === "sqlite") {
                expect(err.message).to.match(/.*SQLITE_CONSTRAINT.*/)
              }
              else if (Support.dialectIsMySQL()) {
                expect(err.message).to.match(/Duplicate entry 'foo' for key 'username'/)
              } else {
                expect(err.message).to.match(/.*duplicate key value violates unique constraint.*/)
              }

              done()
            })
          })
        })
      })
    })

Closes #653
Closes #32

You can now declare unique indices like so:

var User = sequelize.define('User', {
	username: {
		type: DataTypes.STRING,
		unique: {
			name: 'username_and_email',
			msg: 'Your username and email must be unique!'
		}
	},
	email: {
		type: DataTypes.STRING,
		unique: 'username_and_email'
	},
	aCol: {
		type: DataTypes.STRING,
		unique: true
	}
})

Will create two unique indices one for username/email combo and the
other for aCol. If a unique constraint occurs for aCol, the old behavior
still occurs (emits a dialect returned error), but for username/email
index the returned error would be, "Your username and email must be
unique!"
Conflicts:
	lib/dialects/sqlite/query-generator.js
@sdepold

sdepold commented Oct 31, 2013

Copy link
Copy Markdown
Member

nice!

@sdepold

sdepold commented Jan 10, 2014

Copy link
Copy Markdown
Member

Could you rebase this?

@janmeier

Copy link
Copy Markdown
Member

Im rebasing this right now :)

@ruifortes

Copy link
Copy Markdown
Contributor

Index column order is important not only in primary key but other indexes to...at least in mysql.
Since sequelize.define method already has an "options" parameter(that relates to table/model properties) why not define "indexes" in there?

Something like:

indexes:[
    {
        type:"primary" // or "key", "unique", "fulltext",etc
        columns:["userId","classId"]
        name:"mypk" //optional, could default to generated name
    }
]

Of course...defining indexes in columns should also remain possible for single column indexes.

@mickhansen

Copy link
Copy Markdown
Contributor

@ruifortes please open a new issue with this feature request.

@cusspvz

cusspvz commented Sep 11, 2014

Copy link
Copy Markdown

Nice!!

@brunocasanova

Copy link
Copy Markdown

Cool!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

(Postgres) Unique Property Error, Can it be formatted as a Validation Error? Need ability to assign indexes and manually assign primary key column

7 participants