不要怂,就是干,撸起袖子干!

bulk-create.test.js 27.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
'use strict';

const chai = require('chai'),
  Sequelize = require('../../../index'),
  Op = Sequelize.Op,
  Promise = Sequelize.Promise,
  expect = chai.expect,
  Support = require('../support'),
  DataTypes = require('../../../lib/data-types'),
  dialect = Support.getTestDialect(),
  current = Support.sequelize;

describe(Support.getTestDialectTeaser('Model'), () => {
  beforeEach(function() {
    return Support.prepareTransactionTest(this.sequelize).then(sequelize => {
      this.sequelize = sequelize;

      this.User = this.sequelize.define('User', {
        username: DataTypes.STRING,
        secretValue: {
          type: DataTypes.STRING,
          field: 'secret_value'
        },
        data: DataTypes.STRING,
        intVal: DataTypes.INTEGER,
        theDate: DataTypes.DATE,
        aBool: DataTypes.BOOLEAN,
        uniqueName: { type: DataTypes.STRING, unique: true }
      });
      this.Account = this.sequelize.define('Account', {
        accountName: DataTypes.STRING
      });
      this.Student = this.sequelize.define('Student', {
        no: { type: DataTypes.INTEGER, primaryKey: true },
        name: { type: DataTypes.STRING, allowNull: false }
      });
      this.Car = this.sequelize.define('Car', {
        plateNumber: {
          type: DataTypes.STRING,
          primaryKey: true,
          field: 'plate_number'
        },
        color: {
          type: DataTypes.TEXT
        }
      });

      return this.sequelize.sync({ force: true });
    });
  });

  describe('bulkCreate', () => {
    if (current.dialect.supports.transactions) {
      it('supports transactions', function() {
        const User = this.sequelize.define('User', {
          username: DataTypes.STRING
        });
        let transaction, count1;
        return User.sync({ force: true })
          .then(() => this.sequelize.transaction())
          .then(t => {
            transaction = t;
            return User.bulkCreate([{ username: 'foo' }, { username: 'bar' }], { transaction });
          })
          .then(() => User.count())
          .then(count => {
            count1 = count;
            return User.count({ transaction });
          })
          .then(count2 => {
            expect(count1).to.equal(0);
            expect(count2).to.equal(2);
            return transaction.rollback();
          });
      });
    }

    it('should be able to set createdAt and updatedAt if using silent: true', function() {
      const User = this.sequelize.define('user', {
        name: DataTypes.STRING
      }, {
        timestamps: true
      });

      const createdAt = new Date(2012, 10, 10, 10, 10, 10);
      const updatedAt = new Date(2011, 11, 11, 11, 11, 11);
      const values = new Array(10).fill({
        createdAt,
        updatedAt
      });

      return User.sync({ force: true }).then(() => {
        return User.bulkCreate(values, {
          silent: true
        }).then(() => {
          return User.findAll({
            where: {
              updatedAt: {
                [Op.ne]: null
              }
            }
          }).then(users => {
            users.forEach(user => {
              expect(createdAt.getTime()).to.equal(user.get('createdAt').getTime());
              expect(updatedAt.getTime()).to.equal(user.get('updatedAt').getTime());
            });
          });
        });
      });
    });

    it('should not fail on validate: true and individualHooks: true', function() {
      const User = this.sequelize.define('user', {
        name: Sequelize.STRING
      });

      return User.sync({ force: true }).then(() => {
        return User.bulkCreate([
          { name: 'James' }
        ], { validate: true, individualHooks: true });
      });
    });

    it('should not map instance dataValues to fields with individualHooks: true', function() {
      const User = this.sequelize.define('user', {
        name: Sequelize.STRING,
        type: {
          type: Sequelize.STRING,
          allowNull: false,
          field: 'user_type'
        },
        createdAt: {
          type: Sequelize.DATE,
          allowNull: false,
          field: 'created_at'
        },
        updatedAt: {
          type: Sequelize.DATE,
          field: 'modified_at'
        }
      });

      return User.sync({ force: true }).then(() => {
        return User.bulkCreate([
          { name: 'James', type: 'A' },
          { name: 'Alan', type: 'Z' }
        ], { individualHooks: true });
      });
    });

    it('should not insert NULL for unused fields', function() {
      const Beer = this.sequelize.define('Beer', {
        style: Sequelize.STRING,
        size: Sequelize.INTEGER
      });

      return Beer.sync({ force: true }).then(() => {
        return Beer.bulkCreate([{
          style: 'ipa'
        }], {
          logging(sql) {
            if (dialect === 'postgres') {
              expect(sql).to.include('INSERT INTO "Beers" ("id","style","createdAt","updatedAt") VALUES (DEFAULT');
            } else if (dialect === 'mssql') {
              expect(sql).to.include('INSERT INTO [Beers] ([style],[createdAt],[updatedAt]) ');
            } else { // mysql, sqlite
              expect(sql).to.include('INSERT INTO `Beers` (`id`,`style`,`createdAt`,`updatedAt`) VALUES (NULL');
            }
          }
        });
      });
    });

    it('properly handles disparate field lists', function() {
      const data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
        { username: 'Paul', uniqueName: '2' },
        { username: 'Steve', uniqueName: '3' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ where: { username: 'Paul' } }).then(users => {
          expect(users.length).to.equal(1);
          expect(users[0].username).to.equal('Paul');
          expect(users[0].secretValue).to.be.null;
        });
      });
    });

    it('inserts multiple values respecting the white list', function() {
      const data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
        { username: 'Paul', secretValue: '23', uniqueName: '2' }];

      return this.User.bulkCreate(data, { fields: ['username', 'uniqueName'] }).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(users[0].secretValue).to.be.null;
          expect(users[1].username).to.equal('Paul');
          expect(users[1].secretValue).to.be.null;
        });
      });
    });

    it('should store all values if no whitelist is specified', function() {
      const data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
        { username: 'Paul', secretValue: '23', uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(users[0].secretValue).to.equal('42');
          expect(users[1].username).to.equal('Paul');
          expect(users[1].secretValue).to.equal('23');
        });
      });
    });

    it('should set isNewRecord = false', function() {
      const data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
        { username: 'Paul', secretValue: '23', uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          users.forEach(user => {
            expect(user.isNewRecord).to.equal(false);
          });
        });
      });
    });

    it('saves data with single quote', function() {
      const quote = "Single'Quote",
        data = [{ username: 'Peter', data: quote, uniqueName: '1' },
          { username: 'Paul', data: quote, uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(users[0].data).to.equal(quote);
          expect(users[1].username).to.equal('Paul');
          expect(users[1].data).to.equal(quote);
        });
      });
    });

    it('saves data with double quote', function() {
      const quote = 'Double"Quote',
        data = [{ username: 'Peter', data: quote, uniqueName: '1' },
          { username: 'Paul', data: quote, uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(users[0].data).to.equal(quote);
          expect(users[1].username).to.equal('Paul');
          expect(users[1].data).to.equal(quote);
        });
      });
    });

    it('saves stringified JSON data', function() {
      const json = JSON.stringify({ key: 'value' }),
        data = [{ username: 'Peter', data: json, uniqueName: '1' },
          { username: 'Paul', data: json, uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(users[0].data).to.equal(json);
          expect(users[1].username).to.equal('Paul');
          expect(users[1].data).to.equal(json);
        });
      });
    });

    it('properly handles a model with a length column', function() {
      const UserWithLength = this.sequelize.define('UserWithLength', {
        length: Sequelize.INTEGER
      });

      return UserWithLength.sync({ force: true }).then(() => {
        return UserWithLength.bulkCreate([{ length: 42 }, { length: 11 }]);
      });
    });

    it('stores the current date in createdAt', function() {
      const data = [{ username: 'Peter', uniqueName: '1' },
        { username: 'Paul', uniqueName: '2' }];

      return this.User.bulkCreate(data).then(() => {
        return this.User.findAll({ order: ['id'] }).then(users => {
          expect(users.length).to.equal(2);
          expect(users[0].username).to.equal('Peter');
          expect(parseInt(+users[0].createdAt / 5000, 10)).to.be.closeTo(parseInt(+new Date() / 5000, 10), 1.5);
          expect(users[1].username).to.equal('Paul');
          expect(parseInt(+users[1].createdAt / 5000, 10)).to.be.closeTo(parseInt(+new Date() / 5000, 10), 1.5);
        });
      });
    });

    it('emits an error when validate is set to true', function() {
      const Tasks = this.sequelize.define('Task', {
        name: {
          type: Sequelize.STRING,
          allowNull: false
        },
        code: {
          type: Sequelize.STRING,
          validate: {
            len: [3, 10]
          }
        }
      });

      return Tasks.sync({ force: true }).then(() => {
        return Tasks.bulkCreate([
          { name: 'foo', code: '123' },
          { code: '1234' },
          { name: 'bar', code: '1' }
        ], { validate: true }).catch(errors => {
          const expectedValidationError = 'Validation len on code failed';
          const expectedNotNullError = 'notNull Violation: Task.name cannot be null';

          expect(errors).to.be.instanceof(Promise.AggregateError);
          expect(errors.toString()).to.include(expectedValidationError)
            .and.to.include(expectedNotNullError);
          expect(errors).to.have.length(2);

          const e0name0 = errors[0].errors.get('name')[0];

          expect(errors[0].record.code).to.equal('1234');
          expect(e0name0.type || e0name0.origin).to.equal('notNull Violation');

          expect(errors[1].record.name).to.equal('bar');
          expect(errors[1].record.code).to.equal('1');
          expect(errors[1].errors.get('code')[0].message).to.equal(expectedValidationError);
        });
      });
    });

    it("doesn't emit an error when validate is set to true but our selectedValues are fine", function() {
      const Tasks = this.sequelize.define('Task', {
        name: {
          type: Sequelize.STRING,
          validate: {
            notEmpty: true
          }
        },
        code: {
          type: Sequelize.STRING,
          validate: {
            len: [3, 10]
          }
        }
      });

      return Tasks.sync({ force: true }).then(() => {
        return Tasks.bulkCreate([
          { name: 'foo', code: '123' },
          { code: '1234' }
        ], { fields: ['code'], validate: true });
      });
    });

    it('should allow blank arrays (return immediately)', function() {
      const Worker = this.sequelize.define('Worker', {});
      return Worker.sync().then(() => {
        return Worker.bulkCreate([]).then(workers => {
          expect(workers).to.be.ok;
          expect(workers.length).to.equal(0);
        });
      });
    });

    it('should allow blank creates (with timestamps: false)', function() {
      const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
      return Worker.sync().then(() => {
        return Worker.bulkCreate([{}, {}]).then(workers => {
          expect(workers).to.be.ok;
        });
      });
    });

    it('should allow autoincremented attributes to be set', function() {
      const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
      return Worker.sync().then(() => {
        return Worker.bulkCreate([
          { id: 5 },
          { id: 10 }
        ]).then(() => {
          return Worker.findAll({ order: [['id', 'ASC']] }).then(workers => {
            expect(workers[0].id).to.equal(5);
            expect(workers[1].id).to.equal(10);
          });
        });
      });
    });

    it('should support schemas', function() {
      const Dummy = this.sequelize.define('Dummy', {
        foo: DataTypes.STRING,
        bar: DataTypes.STRING
      }, {
        schema: 'space1',
        tableName: 'Dummy'
      });

      return Support.dropTestSchemas(this.sequelize).then(() => {
        return this.sequelize.createSchema('space1');
      }).then(() => {
        return Dummy.sync({ force: true });
      }).then(() => {
        return Dummy.bulkCreate([
          { foo: 'a', bar: 'b' },
          { foo: 'c', bar: 'd' }
        ]);
      });
    });

    if (current.dialect.supports.inserts.ignoreDuplicates ||
        current.dialect.supports.inserts.onConflictDoNothing) {
      it('should support the ignoreDuplicates option', function() {
        const data = [
          { uniqueName: 'Peter', secretValue: '42' },
          { uniqueName: 'Paul', secretValue: '23' }
        ];

        return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'] }).then(() => {
          data.push({ uniqueName: 'Michael', secretValue: '26' });

          return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).then(() => {
            return this.User.findAll({ order: ['id'] }).then(users => {
              expect(users.length).to.equal(3);
              expect(users[0].uniqueName).to.equal('Peter');
              expect(users[0].secretValue).to.equal('42');
              expect(users[1].uniqueName).to.equal('Paul');
              expect(users[1].secretValue).to.equal('23');
              expect(users[2].uniqueName).to.equal('Michael');
              expect(users[2].secretValue).to.equal('26');
            });
          });
        });
      });
    } else {
      it('should throw an error when the ignoreDuplicates option is passed', function() {
        const data = [
          { uniqueName: 'Peter', secretValue: '42' },
          { uniqueName: 'Paul', secretValue: '23' }
        ];

        return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'] }).then(() => {
          data.push({ uniqueName: 'Michael', secretValue: '26' });

          return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).catch(err => {
            expect(err.message).to.equal(`${dialect} does not support the ignoreDuplicates option.`);
          });
        });
      });
    }

    if (current.dialect.supports.inserts.updateOnDuplicate) {
      describe('updateOnDuplicate', () => {
        it('should support the updateOnDuplicate option', function() {
          const data = [
            { uniqueName: 'Peter', secretValue: '42' },
            { uniqueName: 'Paul', secretValue: '23' }
          ];

          return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], updateOnDuplicate: ['secretValue'] }).then(() => {
            const new_data = [
              { uniqueName: 'Peter', secretValue: '43' },
              { uniqueName: 'Paul', secretValue: '24' },
              { uniqueName: 'Michael', secretValue: '26' }
            ];
            return this.User.bulkCreate(new_data, { fields: ['uniqueName', 'secretValue'], updateOnDuplicate: ['secretValue'] }).then(() => {
              return this.User.findAll({ order: ['id'] }).then(users => {
                expect(users.length).to.equal(3);
                expect(users[0].uniqueName).to.equal('Peter');
                expect(users[0].secretValue).to.equal('43');
                expect(users[1].uniqueName).to.equal('Paul');
                expect(users[1].secretValue).to.equal('24');
                expect(users[2].uniqueName).to.equal('Michael');
                expect(users[2].secretValue).to.equal('26');
              });
            });
          });
        });

        describe('should support the updateOnDuplicate option with primary keys', () => {
          it('when the primary key column names and model field names are the same', function() {
            const data = [
              { no: 1, name: 'Peter' },
              { no: 2, name: 'Paul' }
            ];

            return this.Student.bulkCreate(data, { fields: ['no', 'name'], updateOnDuplicate: ['name'] }).then(() => {
              const new_data = [
                { no: 1, name: 'Peterson' },
                { no: 2, name: 'Paulson' },
                { no: 3, name: 'Michael' }
              ];
              return this.Student.bulkCreate(new_data, { fields: ['no', 'name'], updateOnDuplicate: ['name'] }).then(() => {
                return this.Student.findAll({ order: ['no'] }).then(students => {
                  expect(students.length).to.equal(3);
                  expect(students[0].name).to.equal('Peterson');
                  expect(students[0].no).to.equal(1);
                  expect(students[1].name).to.equal('Paulson');
                  expect(students[1].no).to.equal(2);
                  expect(students[2].name).to.equal('Michael');
                  expect(students[2].no).to.equal(3);
                });
              });
            });
          });

          it('when the primary key column names and model field names are different', function() {
            const data = [
              { plateNumber: 'abc', color: 'Grey' },
              { plateNumber: 'def', color: 'White' }
            ];

            return this.Car.bulkCreate(data, { fields: ['plateNumber', 'color'], updateOnDuplicate: ['color'] }).then(() => {
              const new_data = [
                { plateNumber: 'abc', color: 'Red' },
                { plateNumber: 'def', color: 'Green' },
                { plateNumber: 'ghi', color: 'Blue' }
              ];
              return this.Car.bulkCreate(new_data, { fields: ['plateNumber', 'color'], updateOnDuplicate: ['color'] }).then(() => {
                return this.Car.findAll({ order: ['plateNumber'] }).then(cars => {
                  expect(cars.length).to.equal(3);
                  expect(cars[0].plateNumber).to.equal('abc');
                  expect(cars[0].color).to.equal('Red');
                  expect(cars[1].plateNumber).to.equal('def');
                  expect(cars[1].color).to.equal('Green');
                  expect(cars[2].plateNumber).to.equal('ghi');
                  expect(cars[2].color).to.equal('Blue');
                });
              });
            });
          });
        });

        it('should reject for non array updateOnDuplicate option', function() {
          const data = [
            { uniqueName: 'Peter', secretValue: '42' },
            { uniqueName: 'Paul', secretValue: '23' }
          ];

          return expect(
            this.User.bulkCreate(data, { updateOnDuplicate: true })
          ).to.be.rejectedWith('updateOnDuplicate option only supports non-empty array.');
        });

        it('should reject for empty array updateOnDuplicate option', function() {
          const data = [
            { uniqueName: 'Peter', secretValue: '42' },
            { uniqueName: 'Paul', secretValue: '23' }
          ];

          return expect(
            this.User.bulkCreate(data, { updateOnDuplicate: [] })
          ).to.be.rejectedWith('updateOnDuplicate option only supports non-empty array.');
        });
      });
    }

    if (current.dialect.supports.returnValues) {
      describe('return values', () => {
        it('should make the auto incremented values available on the returned instances', function() {
          const User = this.sequelize.define('user', {});

          return User
            .sync({ force: true })
            .then(() => User.bulkCreate([
              {},
              {},
              {}
            ], {
              returning: true
            }))
            .then(users =>
              User.findAll({ order: ['id'] })
                .then(actualUsers => [users, actualUsers])
            )
            .then(([users, actualUsers]) => {
              expect(users.length).to.eql(actualUsers.length);
              users.forEach((user, i) => {
                expect(user.get('id')).to.be.ok;
                expect(user.get('id')).to.equal(actualUsers[i].get('id'))
                  .and.to.equal(i + 1);
              });
            });
        });

        it('should make the auto incremented values available on the returned instances with custom fields', function() {
          const User = this.sequelize.define('user', {
            maId: {
              type: DataTypes.INTEGER,
              primaryKey: true,
              autoIncrement: true,
              field: 'yo_id'
            }
          });

          return User
            .sync({ force: true })
            .then(() => User.bulkCreate([
              {},
              {},
              {}
            ], {
              returning: true
            }))
            .then(users =>
              User.findAll({ order: ['maId'] })
                .then(actualUsers => [users, actualUsers])
            )
            .then(([users, actualUsers]) => {
              expect(users.length).to.eql(actualUsers.length);
              users.forEach((user, i) => {
                expect(user.get('maId')).to.be.ok;
                expect(user.get('maId')).to.equal(actualUsers[i].get('maId'))
                  .and.to.equal(i + 1);
              });
            });
        });
      });
    }

    describe('enums', () => {
      it('correctly restores enum values', function() {
        const Item = this.sequelize.define('Item', {
          state: { type: Sequelize.ENUM, values: ['available', 'in_cart', 'shipped'] },
          name: Sequelize.STRING
        });

        return Item.sync({ force: true }).then(() => {
          return Item.bulkCreate([{ state: 'in_cart', name: 'A' }, { state: 'available', name: 'B' }]).then(() => {
            return Item.findOne({ where: { state: 'available' } }).then(item => {
              expect(item.name).to.equal('B');
            });
          });
        });
      });
    });

    it('should properly map field names to attribute names', function() {
      const Maya = this.sequelize.define('Maya', {
        name: Sequelize.STRING,
        secret: {
          field: 'secret_given',
          type: Sequelize.STRING
        },
        createdAt: {
          field: 'created_at',
          type: Sequelize.DATE
        },
        updatedAt: {
          field: 'updated_at',
          type: Sequelize.DATE
        }
      });

      const M1 = { id: 1, name: 'Prathma Maya', secret: 'You are on list #1' };
      const M2 = { id: 2, name: 'Dwitiya Maya', secret: 'You are on list #2' };

      return Maya.sync({ force: true }).then(() => Maya.create(M1))
        .then(m => {
          expect(m.createdAt).to.be.ok;
          expect(m.id).to.be.eql(M1.id);
          expect(m.name).to.be.eql(M1.name);
          expect(m.secret).to.be.eql(M1.secret);

          return Maya.bulkCreate([M2]);
        }).then(([m]) => {

          // only attributes are returned, no fields are mixed
          expect(m.createdAt).to.be.ok;
          expect(m.created_at).to.not.exist;
          expect(m.secret_given).to.not.exist;
          expect(m.get('secret_given')).to.be.undefined;
          expect(m.get('created_at')).to.be.undefined;

          // values look fine
          expect(m.id).to.be.eql(M2.id);
          expect(m.name).to.be.eql(M2.name);
          expect(m.secret).to.be.eql(M2.secret);
        });
    });

    describe('handles auto increment values', () => {
      it('should return auto increment primary key values', function() {
        const Maya = this.sequelize.define('Maya', {});

        const M1 = {};
        const M2 = {};

        return Maya.sync({ force: true })
          .then(() => Maya.bulkCreate([M1, M2], { returning: true }))
          .then(ms => {
            expect(ms[0].id).to.be.eql(1);
            expect(ms[1].id).to.be.eql(2);
          });
      });

      it('should return supplied values on primary keys', function() {
        const User = this.sequelize.define('user', {});

        return User
          .sync({ force: true })
          .then(() => User.bulkCreate([
            { id: 1 },
            { id: 2 },
            { id: 3 }
          ], { returning: true }))
          .then(users =>
            User.findAll({ order: [['id', 'ASC']] })
              .then(actualUsers => [users, actualUsers])
          )
          .then(([users, actualUsers]) => {
            expect(users.length).to.eql(actualUsers.length);

            expect(users[0].get('id')).to.equal(1).and.to.equal(actualUsers[0].get('id'));
            expect(users[1].get('id')).to.equal(2).and.to.equal(actualUsers[1].get('id'));
            expect(users[2].get('id')).to.equal(3).and.to.equal(actualUsers[2].get('id'));
          });
      });

      it('should return supplied values on primary keys when some instances already exists', function() {
        const User = this.sequelize.define('user', {});

        return User
          .sync({ force: true })
          .then(() => User.bulkCreate([
            { id: 1 },
            { id: 3 }
          ]))
          .then(() => User.bulkCreate([
            { id: 2 },
            { id: 4 },
            { id: 5 }
          ], { returning: true }))
          .then(users => {
            expect(users.length).to.eql(3);

            expect(users[0].get('id')).to.equal(2);
            expect(users[1].get('id')).to.equal(4);
            expect(users[2].get('id')).to.equal(5);
          });
      });
    });

    describe('virtual attribute', () => {
      beforeEach(function() {
        this.User = this.sequelize.define('user', {
          password: {
            type: Sequelize.VIRTUAL,
            validate: {
              customValidator: () => {
                throw new Error('always invalid');
              }
            }
          }
        });
      });

      it('should validate', function() {
        return this.User
          .sync({ force: true })
          .then(() => this.User.bulkCreate([
            { password: 'password' }
          ], { validate: true }))
          .then(() => {
            expect.fail();
          }, error => {
            expect(error.length).to.equal(1);
            expect(error[0].message).to.match(/.*always invalid.*/);
          });
      });

      it('should not validate', function() {
        return this.User
          .sync({ force: true })
          .then(() => this.User.bulkCreate([
            { password: 'password' }
          ], { validate: false }))
          .then(users => {
            expect(users.length).to.equal(1);
          })
          .then(() => this.User.bulkCreate([
            { password: 'password' }
          ]))
          .then(users => {
            expect(users.length).to.equal(1);
          });
      });
    });
  });
});