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

belongs-to.test.js 23.5 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
/* jshint camelcase: false, expr: true */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , Sequelize = require('../../index')
  , Promise   = Sequelize.Promise
  , assert    = require('assert')
  , current   = Support.sequelize;

chai.config.includeStack = true

describe(Support.getTestDialectTeaser("BelongsTo"), function() {
  describe("Model.associations", function () {
    it("should store all assocations when associting to the same table multiple times", function () {
      var User  = this.sequelize.define('User', {})
        , Group = this.sequelize.define('Group', {})

      Group.belongsTo(User)
      Group.belongsTo(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' })
      Group.belongsTo(User, { foreignKey: 'secondaryGroupId', as: 'secondaryUsers' })

      expect(Object.keys(Group.associations)).to.deep.equal(['User', 'primaryUsers', 'secondaryUsers'])
    })
  })

  describe('getAssociation', function() {
    it('supports transactions', function(done) {
      Support.prepareTransactionTest(this.sequelize, function(sequelize) {
        var User  = sequelize.define('User', { username: Support.Sequelize.STRING })
          , Group = sequelize.define('Group', { name: Support.Sequelize.STRING })

        Group.belongsTo(User)

        sequelize.sync({ force: true }).success(function() {
          User.create({ username: 'foo' }).success(function(user) {
            Group.create({ name: 'bar' }).success(function(group) {
              sequelize.transaction().then(function(t) {
                group.setUser(user, { transaction: t }).success(function() {
                  Group.all().success(function(groups) {
                    groups[0].getUser().success(function(associatedUser) {
                      expect(associatedUser).to.be.null
                      Group.all({ transaction: t }).success(function(groups) {
                        groups[0].getUser({ transaction: t }).success(function(associatedUser) {
                          expect(associatedUser).to.be.not.null
                          t.rollback().success(function() {
                            done()
                          })
                        })
                      })
                    })
                  })
                })
              })
            })
          })
        })
      })
    })

    it('does not modify the passed arguments', function () {
      var User = this.sequelize.define('user', {})
        , Project = this.sequelize.define('project', {});

      User.belongsTo(Project);

      return this.sequelize.sync({ force: true }).bind(this).then(function () {
        return User.create({});
      }).then(function (user) {
        this.options = {};

        return user.getProject(this.options);
      }).then(function () {
        expect(this.options).to.deep.equal({});
      });
    });

    it('should be able to handle a where object that\'s a first class citizen.', function() {
      var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING, gender: Sequelize.STRING })
        , Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING, status: Sequelize.STRING })

      Task.belongsTo(User)

      return User.sync({ force: true }).then(function () {
        // Can't use Promise.all cause of foreign key references
        return Task.sync({ force: true });
      }).then(function () {
        return Promise.all([
          User.create({ username: 'foo', gender: 'male' }),
          User.create({ username: 'bar', gender: 'female' }),
          Task.create({ title: 'task', status: 'inactive' })
        ]);
      }).spread(function (userA, userB, task) {
        return task.setUserXYZ(userA).then(function () {
          return task.getUserXYZ({where: ['gender = ?', 'female']});
        });
      }).then(function (user) {
        expect(user).to.be.null;
      });
    })

    it('supports schemas', function () {
      var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING, gender: Sequelize.STRING }).schema('archive')
        , Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING, status: Sequelize.STRING }).schema('archive')
        , self = this

      Task.belongsTo(User)

      return self.sequelize.dropAllSchemas().then(function() {
        return self.sequelize.createSchema('archive');
      }).then(function () {
        return self.sequelize.sync({force: true });
      }).then(function () {
        return Promise.all([
          User.create({ username: 'foo', gender: 'male' }),
          Task.create({ title: 'task', status: 'inactive' })
        ]);
      }).spread(function (user, task) {
        return task.setUserXYZ(user).then(function () {
          return task.getUserXYZ();
        });
      }).then(function (user) {
        expect(user).to.be.ok;
      });
    })
  })

  describe('setAssociation', function() {
    it('supports transactions', function(done) {
      Support.prepareTransactionTest(this.sequelize, function(sequelize) {
        var User  = sequelize.define('User', { username: Support.Sequelize.STRING })
          , Group = sequelize.define('Group', { name: Support.Sequelize.STRING })

        Group.belongsTo(User)

        sequelize.sync({ force: true }).success(function() {
          User.create({ username: 'foo' }).success(function(user) {
            Group.create({ name: 'bar' }).success(function(group) {
              sequelize.transaction().then(function(t) {
                group.setUser(user, { transaction: t }).success(function() {
                  Group.all().success(function(groups) {
                    groups[0].getUser().success(function(associatedUser) {
                      expect(associatedUser).to.be.null
                      t.rollback().success(function() { done() })
                    })
                  })
                })
              })
            })
          })
        })
      })
    })

    it('can set the association with declared primary keys...', function(done) {
      var User = this.sequelize.define('UserXYZ', { user_id: {type: DataTypes.INTEGER, primaryKey: true }, username: DataTypes.STRING })
        , Task = this.sequelize.define('TaskXYZ', { task_id: {type: DataTypes.INTEGER, primaryKey: true }, title: DataTypes.STRING })

      Task.belongsTo(User, { foreignKey: 'user_id' })

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ user_id: 1, username: 'foo' }).success(function(user) {
          Task.create({ task_id: 1, title: 'task' }).success(function(task) {
            task.setUserXYZ(user).success(function() {
              task.getUserXYZ().success(function(user) {
                expect(user).not.to.be.null

                task.setUserXYZ(null).success(function() {
                  task.getUserXYZ().success(function(user) {
                    expect(user).to.be.null
                    done()
                  })
                })

              })
            })
          })
        })
      })
    })

    it('clears the association if null is passed', function(done) {
      var User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING })
        , Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING })

      Task.belongsTo(User)

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ username: 'foo' }).success(function(user) {
          Task.create({ title: 'task' }).success(function(task) {
            task.setUserXYZ(user).success(function() {
              task.getUserXYZ().success(function(user) {
                expect(user).not.to.be.null

                task.setUserXYZ(null).success(function() {
                  task.getUserXYZ().success(function(user) {
                    expect(user).to.be.null
                    done()
                  })
                })

              })
            })
          })
        })
      })
    })

    it('supports passing the primary key instead of an object', function () {
      var User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING })
        , Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING })

      Task.belongsTo(User)

      return this.sequelize.sync({ force :true }).then(function () {
        return User.create({ id: 15, username: 'jansemand' }).then(function (user) {
          return Task.create({}).then(function (task) {
            return task.setUserXYZ(user.id).then(function () {
              return  task.getUserXYZ().then(function (user) {
                expect(user.username).to.equal('jansemand')
              })
            })
          })
        })
      })
    })

    it('should not clobber atributes', function (done) {
      var Comment = this.sequelize.define('comment', {
        text: DataTypes.STRING
      });

      var Post = this.sequelize.define('post', {
        title: DataTypes.STRING
      });

      Post.hasOne(Comment);
      Comment.belongsTo(Post);

      this.sequelize.sync().done(function () {
        Post.create({
          title: 'Post title',
        }).done(function(err, post) {
          Comment.create({
            text: 'OLD VALUE',
          }).done(function(err, comment) {
            comment.setPost(post).done(function() {
              expect(comment.text).to.equal('UPDATED VALUE');
              done()
            });

            comment.text = 'UPDATED VALUE';
          });
        });
      })
    })
  })

  describe('createAssociation', function() {
    it('creates an associated model instance', function(done) {
      var User = this.sequelize.define('User', { username: DataTypes.STRING })
        , Task = this.sequelize.define('Task', { title: DataTypes.STRING })

      Task.belongsTo(User)

      this.sequelize.sync({ force: true }).success(function() {
        Task.create({ title: 'task' }).success(function(task) {
          task.createUser({ username: 'bob' }).success(function() {
            task.getUser().success(function(user) {
              expect(user).not.to.be.null
              expect(user.username).to.equal('bob')

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

    it('supports transactions', function(done) {
      Support.prepareTransactionTest(this.sequelize, function(sequelize) {
        var User  = sequelize.define('User', { username: Support.Sequelize.STRING })
          , Group = sequelize.define('Group', { name: Support.Sequelize.STRING })

        Group.belongsTo(User)

        sequelize.sync({ force: true }).success(function() {
          Group.create({ name: 'bar' }).success(function(group) {
            sequelize.transaction().then(function(t) {
              group.createUser({ username: 'foo' }, { transaction: t }).success(function() {
                group.getUser().success(function(user) {
                  expect(user).to.be.null

                  group.getUser({ transaction: t }).success(function(user) {
                    expect(user).not.to.be.null

                    t.rollback().success(function() { done() })
                  })
                })
              })
            })
          })
        })
      })
    })
  })

  describe("foreign key", function () {
    it('should lowercase foreign keys when using underscored', function () {
      var User  = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: true })
        , Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: true })

      User.belongsTo(Account)

      expect(User.rawAttributes.account_id).to.exist;
    });
    it('should use model name when using camelcase', function () {
      var User  = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: false })
        , Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: false })

      User.belongsTo(Account)

      expect(User.rawAttributes.AccountId).to.exist;
    });

    it('should support specifying the field of a foreign key', function () {
       var User  = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: false })
         , Account = this.sequelize.define('Account', { title: Sequelize.STRING }, { underscored: false });

      User.belongsTo(Account, {
        foreignKey: {
          name: 'AccountId',
          field: 'account_id'
        }
      });

      expect(User.rawAttributes.AccountId).to.exist;
      expect(User.rawAttributes.AccountId.field).to.equal('account_id');

      return Account.sync({ force: true }).then(function () {
        // Can't use Promise.all cause of foreign key references
        return  User.sync({ force: true });
      }).then(function () {
        return Promise.all([
          User.create({ username: 'foo' }),
          Account.create({ title: 'pepsico' })
        ]);
      }).spread(function (user, account) {
        return user.setAccount(account).then(function () {
          return user.getAccount();
        });
      }).then(function (user) {
        // the sql query should correctly look at task_id instead of taskId
        expect(user).to.not.be.null;
        return User.find({
          where: {username: 'foo'},
          include: [ Account ]
        })
      }).then(function(task) {
        expect(task.Account).to.exist;
      });
    });
  });

  describe("foreign key constraints", function() {
    it("are enabled by default", function(done) {
      var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
        , User = this.sequelize.define('User', { username: DataTypes.STRING })

      Task.belongsTo(User) // defaults to SET NULL

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ username: 'foo' }).success(function(user) {
          Task.create({ title: 'task' }).success(function(task) {
            task.setUser(user).success(function() {
              user.destroy().success(function() {
                task.reload().success(function() {
                  expect(task.UserId).to.equal(null)
                  done()
                })
              })
            })
          })
        })
      })
    })

    it("should be possible to disable them", function(done) {
      var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
        , User = this.sequelize.define('User', { username: Sequelize.STRING })

      Task.belongsTo(User, { constraints: false })

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ username: 'foo' }).success(function(user) {
          Task.create({ title: 'task' }).success(function(task) {
            task.setUser(user).success(function() {
              user.destroy().success(function() {
                task.reload().success(function() {
                  expect(task.UserId).to.equal(user.id)
                  done()
                })
              })
            })
          })
        })
      })
    })

    it("can cascade deletes", function(done) {
      var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
        , User = this.sequelize.define('User', { username: DataTypes.STRING })

      Task.belongsTo(User, {onDelete: 'cascade'})

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ username: 'foo' }).success(function(user) {
          Task.create({ title: 'task' }).success(function(task) {
            task.setUser(user).success(function() {
              user.destroy().success(function() {
                Task.findAll().success(function(tasks) {
                  expect(tasks).to.have.length(0)
                  done()
                })
              })
            })
          })
        })
      })
    })

    if (current.dialect.supports.constraints.restrict) {
      it("can restrict deletes", function(done) {
        var self = this
        var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
          , User = this.sequelize.define('User', { username: DataTypes.STRING })

        Task.belongsTo(User, {onDelete: 'restrict'})

        this.sequelize.sync({ force: true }).success(function() {
          User.create({ username: 'foo' }).success(function(user) {
            Task.create({ title: 'task' }).success(function(task) {
              task.setUser(user).success(function() {
                // Should fail due to FK restriction
                user.destroy().catch(self.sequelize.ForeignKeyConstraintError, function(err) {
                  expect(err).to.be.ok;
                  Task.findAll().success(function(tasks) {
                    expect(tasks).to.have.length(1)
                    done()
                  })
                })
              });
            })
          })
        })
      })

      it("can restrict updates", function(done) {
        var self = this
        var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
          , User = this.sequelize.define('User', { username: DataTypes.STRING })

        Task.belongsTo(User, {onUpdate: 'restrict'})

        this.sequelize.sync({ force: true }).success(function() {
          User.create({ username: 'foo' }).success(function(user) {
            Task.create({ title: 'task' }).success(function(task) {
              task.setUser(user).success(function() {

                // Changing the id of a DAO requires a little dance since
                // the `UPDATE` query generated by `save()` uses `id` in the
                // `WHERE` clause

                var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
                user.QueryInterface.update(user, tableName, {id: 999}, user.id)
                .catch(self.sequelize.ForeignKeyConstraintError, function() {
                  // Should fail due to FK restriction
                  Task.findAll().success(function(tasks) {
                    expect(tasks).to.have.length(1)
                    done()
                  })
                })
              })
            })
          })
        })
      })

    }

    it("can cascade updates", function(done) {
      var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
        , User = this.sequelize.define('User', { username: DataTypes.STRING })

      Task.belongsTo(User, {onUpdate: 'cascade'})

      this.sequelize.sync({ force: true }).success(function() {
        User.create({ username: 'foo' }).success(function(user) {
          Task.create({ title: 'task' }).success(function(task) {
            task.setUser(user).success(function() {

              // Changing the id of a DAO requires a little dance since
              // the `UPDATE` query generated by `save()` uses `id` in the
              // `WHERE` clause

              var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
              user.QueryInterface.update(user, tableName, {id: 999}, user.id)
              .success(function() {
                Task.findAll().success(function(tasks) {
                  expect(tasks).to.have.length(1)
                  expect(tasks[0].UserId).to.equal(999)
                  done()
                })
              })
            })
          })
        })
      })
    })

  })

  describe("Association column", function() {
    it('has correct type and name for non-id primary keys with non-integer type', function(done) {
      var User = this.sequelize.define('UserPKBT', {
        username: {
          type: DataTypes.STRING
        }
      })
        , self = this

      var Group = this.sequelize.define('GroupPKBT', {
        name: {
          type: DataTypes.STRING,
          primaryKey: true
        }
      })

      User.belongsTo(Group)

      self.sequelize.sync({ force: true }).success(function() {
        expect(User.rawAttributes.GroupPKBTName.type.toString()).to.equal(DataTypes.STRING.toString())
        done()
      })
    })
  })

  describe("Association options", function() {
    it('can specify data type for autogenerated relational keys', function(done) {
      var User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING })
        , dataTypes = [DataTypes.INTEGER, DataTypes.BIGINT, DataTypes.STRING]
        , self = this
        , Tasks = {}

      dataTypes.forEach(function(dataType) {
        var tableName = 'TaskXYZ_' + dataType.toString()
        Tasks[dataType] = self.sequelize.define(tableName, { title: DataTypes.STRING })

        Tasks[dataType].belongsTo(User, { foreignKey: 'userId', keyType: dataType, constraints: false })
      })

      self.sequelize.sync({ force: true })
      .success(function() {
        dataTypes.forEach(function(dataType, i) {
          expect(Tasks[dataType].rawAttributes.userId.type.toString())
            .to.equal(dataType.toString())

          if ((i+1) === dataTypes.length) {
            done()
          }
        })
      })
    })

    describe('allows the user to provide an attribute definition object as foreignKey', function () {
      it('works with a column that hasnt been defined before', function () {
        var Task = this.sequelize.define('task', {})
        , User = this.sequelize.define('user', {
          });

        Task.belongsTo(User, {
          foreignKey: {
            allowNull: false,
            name: 'uid'
          }
        });

        expect(Task.rawAttributes.uid).to.be.defined
        expect(Task.rawAttributes.uid.allowNull).to.be.false;
        expect(Task.rawAttributes.uid.references).to.equal(User.getTableName())
        expect(Task.rawAttributes.uid.referencesKey).to.equal('id')
      });

      it('works when taking a column directly from the object', function () {
        var User = this.sequelize.define('user', {
            uid: {
              type: Sequelize.INTEGER,
              primaryKey: true
            }
          })
        , Profile = this.sequelize.define('project', {
            user_id: {
              type: Sequelize.INTEGER,
              allowNull: false
            }
          })

        Profile.belongsTo(User, { foreignKey: Profile.rawAttributes.user_id})

        expect(Profile.rawAttributes.user_id).to.be.defined
        expect(Profile.rawAttributes.user_id.references).to.equal(User.getTableName())
        expect(Profile.rawAttributes.user_id.referencesKey).to.equal('uid')
        expect(Profile.rawAttributes.user_id.allowNull).to.be.false
      });

      it('works when merging with an existing definition', function () {
        var Task = this.sequelize.define('task', {
            projectId: {
              defaultValue: 42,
              type: Sequelize.INTEGER
            }
          })
        , Project = this.sequelize.define('project', {});

        Task.belongsTo(Project, { foreignKey: { allowNull: true }});

        expect(Task.rawAttributes.projectId).to.be.defined
        expect(Task.rawAttributes.projectId.defaultValue).to.equal(42);
        expect(Task.rawAttributes.projectId.allowNull).to.be.ok;
      })
    });

    it('should throw an error if foreignKey and as result in a name clash', function () {
      var Person = this.sequelize.define('person', {})
        , Car = this.sequelize.define('car', {})

      expect(Car.belongsTo.bind(Car, Person, {foreignKey: 'person'})).to
        .throw("Naming collision between attribute 'person' and association 'person' on model car. To remedy this, change either foreignKey or as in your association definition")
    })

    it('should throw an error if an association clashes with the name of an already define attribute', function () {
       var Person = this.sequelize.define('person', {})
        , Car = this.sequelize.define('car', {
            person: Sequelize.INTEGER
          })

        expect(Car.belongsTo.bind(Car, Person, {as: 'person'})).to
        .throw("Naming collision between attribute 'person' and association 'person' on model car. To remedy this, change either foreignKey or as in your association definition")
    })
  })
})