belongs-to.test.js
34 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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
'use strict';
const chai = require('chai'),
sinon = require('sinon'),
expect = chai.expect,
Support = require('../support'),
DataTypes = require('../../../lib/data-types'),
Sequelize = require('../../../index'),
current = Support.sequelize,
dialect = Support.getTestDialect();
describe(Support.getTestDialectTeaser('BelongsTo'), () => {
describe('Model.associations', () => {
it('should store all associations when associating to the same table multiple times', function() {
const 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('get', () => {
describe('multiple', () => {
it('should fetch associations for multiple instances', async function() {
const User = this.sequelize.define('User', {}),
Task = this.sequelize.define('Task', {});
Task.User = Task.belongsTo(User, { as: 'user' });
await this.sequelize.sync({ force: true });
const tasks = await Promise.all([Task.create({
id: 1,
user: { id: 1 }
}, {
include: [Task.User]
}), Task.create({
id: 2,
user: { id: 2 }
}, {
include: [Task.User]
}), Task.create({
id: 3
})]);
const result = await Task.User.get(tasks);
expect(result[tasks[0].id].id).to.equal(tasks[0].user.id);
expect(result[tasks[1].id].id).to.equal(tasks[1].user.id);
expect(result[tasks[2].id]).to.be.undefined;
});
});
});
describe('getAssociation', () => {
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
Group = sequelize.define('Group', { name: Support.Sequelize.STRING });
Group.belongsTo(User);
await sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const group = await Group.create({ name: 'bar' });
const t = await sequelize.transaction();
await group.setUser(user, { transaction: t });
const groups = await Group.findAll();
const associatedUser = await groups[0].getUser();
expect(associatedUser).to.be.null;
const groups0 = await Group.findAll({ transaction: t });
const associatedUser0 = await groups0[0].getUser({ transaction: t });
expect(associatedUser0).to.be.not.null;
await t.rollback();
});
}
it('should be able to handle a where object that\'s a first class citizen.', async function() {
const 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);
await User.sync({ force: true });
// Can't use Promise.all cause of foreign key references
await Task.sync({ force: true });
const [userA, , task] = await Promise.all([
User.create({ username: 'foo', gender: 'male' }),
User.create({ username: 'bar', gender: 'female' }),
Task.create({ title: 'task', status: 'inactive' })
]);
await task.setUserXYZ(userA);
const user = await task.getUserXYZ({ where: { gender: 'female' } });
expect(user).to.be.null;
});
it('supports schemas', async function() {
const 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');
Task.belongsTo(User);
await Support.dropTestSchemas(this.sequelize);
await this.sequelize.createSchema('archive');
await User.sync({ force: true });
await Task.sync({ force: true });
const [user0, task] = await Promise.all([
User.create({ username: 'foo', gender: 'male' }),
Task.create({ title: 'task', status: 'inactive' })
]);
await task.setUserXYZ(user0);
const user = await task.getUserXYZ();
expect(user).to.be.ok;
await this.sequelize.dropSchema('archive');
const schemas = await this.sequelize.showAllSchemas();
if (dialect === 'postgres' || dialect === 'mssql' || dialect === 'mariadb') {
expect(schemas).to.not.have.property('archive');
}
});
it('supports schemas when defining custom foreign key attribute #9029', async function() {
const User = this.sequelize.define('UserXYZ', {
uid: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
}
}).schema('archive'),
Task = this.sequelize.define('TaskXYZ', {
user_id: {
type: Sequelize.INTEGER,
references: { model: User, key: 'uid' }
}
}).schema('archive');
Task.belongsTo(User, { foreignKey: 'user_id' });
await Support.dropTestSchemas(this.sequelize);
await this.sequelize.createSchema('archive');
await User.sync({ force: true });
await Task.sync({ force: true });
const user0 = await User.create({});
const task = await Task.create({});
await task.setUserXYZ(user0);
const user = await task.getUserXYZ();
expect(user).to.be.ok;
await this.sequelize.dropSchema('archive');
});
});
describe('setAssociation', () => {
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
Group = sequelize.define('Group', { name: Support.Sequelize.STRING });
Group.belongsTo(User);
await sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const group = await Group.create({ name: 'bar' });
const t = await sequelize.transaction();
await group.setUser(user, { transaction: t });
const groups = await Group.findAll();
const associatedUser = await groups[0].getUser();
expect(associatedUser).to.be.null;
await t.rollback();
});
}
it('can set the association with declared primary keys...', async function() {
const 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' });
await this.sequelize.sync({ force: true });
const user = await User.create({ user_id: 1, username: 'foo' });
const task = await Task.create({ task_id: 1, title: 'task' });
await task.setUserXYZ(user);
const user1 = await task.getUserXYZ();
expect(user1).not.to.be.null;
await task.setUserXYZ(null);
const user0 = await task.getUserXYZ();
expect(user0).to.be.null;
});
it('clears the association if null is passed', async function() {
const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });
Task.belongsTo(User);
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUserXYZ(user);
const user1 = await task.getUserXYZ();
expect(user1).not.to.be.null;
await task.setUserXYZ(null);
const user0 = await task.getUserXYZ();
expect(user0).to.be.null;
});
it('should throw a ForeignKeyConstraintError if the associated record does not exist', async function() {
const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });
Task.belongsTo(User);
await this.sequelize.sync({ force: true });
await expect(Task.create({ title: 'task', UserXYZId: 5 })).to.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
const task = await Task.create({ title: 'task' });
await expect(Task.update({ title: 'taskUpdate', UserXYZId: 5 }, { where: { id: task.id } })).to.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
});
it('supports passing the primary key instead of an object', async function() {
const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING });
Task.belongsTo(User);
await this.sequelize.sync({ force: true });
const user = await User.create({ id: 15, username: 'jansemand' });
const task = await Task.create({});
await task.setUserXYZ(user.id);
const user0 = await task.getUserXYZ();
expect(user0.username).to.equal('jansemand');
});
it('should support logging', async function() {
const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
Task = this.sequelize.define('TaskXYZ', { title: DataTypes.STRING }),
spy = sinon.spy();
Task.belongsTo(User);
await this.sequelize.sync({ force: true });
const user = await User.create();
const task = await Task.create({});
await task.setUserXYZ(user, { logging: spy });
expect(spy.called).to.be.ok;
});
it('should not clobber atributes', async function() {
const Comment = this.sequelize.define('comment', {
text: DataTypes.STRING
});
const Post = this.sequelize.define('post', {
title: DataTypes.STRING
});
Post.hasOne(Comment);
Comment.belongsTo(Post);
await this.sequelize.sync();
const post = await Post.create({
title: 'Post title'
});
const comment = await Comment.create({
text: 'OLD VALUE'
});
comment.text = 'UPDATED VALUE';
await comment.setPost(post);
expect(comment.text).to.equal('UPDATED VALUE');
});
it('should set the foreign key value without saving when using save: false', async function() {
const Comment = this.sequelize.define('comment', {
text: DataTypes.STRING
});
const Post = this.sequelize.define('post', {
title: DataTypes.STRING
});
Post.hasMany(Comment, { foreignKey: 'post_id' });
Comment.belongsTo(Post, { foreignKey: 'post_id' });
await this.sequelize.sync({ force: true });
const [post, comment] = await Promise.all([Post.create(), Comment.create()]);
expect(comment.get('post_id')).not.to.be.ok;
const setter = await comment.setPost(post, { save: false });
expect(setter).to.be.undefined;
expect(comment.get('post_id')).to.equal(post.get('id'));
expect(comment.changed('post_id')).to.be.true;
});
it('supports setting same association twice', async function() {
const Home = this.sequelize.define('home', {});
const User = this.sequelize.define('user');
Home.belongsTo(User);
await this.sequelize.sync({ force: true });
const [home, user] = await Promise.all([
Home.create(),
User.create()
]);
await home.setUser(user);
expect(await home.getUser()).to.have.property('id', user.id);
});
});
describe('createAssociation', () => {
it('creates an associated model instance', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING }),
Task = this.sequelize.define('Task', { title: DataTypes.STRING });
Task.belongsTo(User);
await this.sequelize.sync({ force: true });
const task = await Task.create({ title: 'task' });
const user = await task.createUser({ username: 'bob' });
expect(user).not.to.be.null;
expect(user.username).to.equal('bob');
});
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Support.Sequelize.STRING }),
Group = sequelize.define('Group', { name: Support.Sequelize.STRING });
Group.belongsTo(User);
await sequelize.sync({ force: true });
const group = await Group.create({ name: 'bar' });
const t = await sequelize.transaction();
await group.createUser({ username: 'foo' }, { transaction: t });
const user = await group.getUser();
expect(user).to.be.null;
const user0 = await group.getUser({ transaction: t });
expect(user0).not.to.be.null;
await t.rollback();
});
}
});
describe('foreign key', () => {
it('should setup underscored field with foreign keys when using underscored', function() {
const 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.AccountId).to.exist;
expect(User.rawAttributes.AccountId.field).to.equal('account_id');
});
it('should use model name when using camelcase', function() {
const 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;
expect(User.rawAttributes.AccountId.field).to.equal('AccountId');
});
it('should support specifying the field of a foreign key', async function() {
const 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');
await Account.sync({ force: true });
// Can't use Promise.all cause of foreign key references
await User.sync({ force: true });
const [user1, account] = await Promise.all([
User.create({ username: 'foo' }),
Account.create({ title: 'pepsico' })
]);
await user1.setAccount(account);
const user0 = await user1.getAccount();
expect(user0).to.not.be.null;
const user = await User.findOne({
where: { username: 'foo' },
include: [Account]
});
// the sql query should correctly look at account_id instead of AccountId
expect(user.Account).to.exist;
});
it('should set foreignKey on foreign table', async function() {
const Mail = this.sequelize.define('mail', {}, { timestamps: false });
const Entry = this.sequelize.define('entry', {}, { timestamps: false });
const User = this.sequelize.define('user', {}, { timestamps: false });
Entry.belongsTo(User, {
as: 'owner',
foreignKey: {
name: 'ownerId',
allowNull: false
}
});
Entry.belongsTo(Mail, {
as: 'mail',
foreignKey: {
name: 'mailId',
allowNull: false
}
});
Mail.belongsToMany(User, {
as: 'recipients',
through: 'MailRecipients',
otherKey: {
name: 'recipientId',
allowNull: false
},
foreignKey: {
name: 'mailId',
allowNull: false
},
timestamps: false
});
Mail.hasMany(Entry, {
as: 'entries',
foreignKey: {
name: 'mailId',
allowNull: false
}
});
User.hasMany(Entry, {
as: 'entries',
foreignKey: {
name: 'ownerId',
allowNull: false
}
});
await this.sequelize.sync({ force: true });
await User.create({});
const mail = await Mail.create({});
await Entry.create({ mailId: mail.id, ownerId: 1 });
await Entry.create({ mailId: mail.id, ownerId: 1 });
// set recipients
await mail.setRecipients([1]);
const result = await Entry.findAndCountAll({
offset: 0,
limit: 10,
order: [['id', 'DESC']],
include: [
{
association: Entry.associations.mail,
include: [
{
association: Mail.associations.recipients,
through: {
where: {
recipientId: 1
}
},
required: true
}
],
required: true
}
]
});
expect(result.count).to.equal(2);
expect(result.rows[0].get({ plain: true })).to.deep.equal(
{
id: 2,
ownerId: 1,
mailId: 1,
mail: {
id: 1,
recipients: [{
id: 1,
MailRecipients: {
mailId: 1,
recipientId: 1
}
}]
}
}
);
});
});
describe('foreign key constraints', () => {
it('are enabled by default', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User); // defaults to SET NULL
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
await user.destroy();
await task.reload();
expect(task.UserId).to.equal(null);
});
it('sets to NO ACTION if allowNull: false', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User, { foreignKey: { allowNull: false } }); // defaults to NO ACTION
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
await Task.create({ title: 'task', UserId: user.id });
await expect(user.destroy()).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
const tasks = await Task.findAll();
expect(tasks).to.have.length(1);
});
it('should be possible to disable them', async function() {
const Task = this.sequelize.define('Task', { title: Sequelize.STRING }),
User = this.sequelize.define('User', { username: Sequelize.STRING });
Task.belongsTo(User, { constraints: false });
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
await user.destroy();
await task.reload();
expect(task.UserId).to.equal(user.id);
});
it('can cascade deletes', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User, { onDelete: 'cascade' });
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
await user.destroy();
const tasks = await Task.findAll();
expect(tasks).to.have.length(0);
});
if (current.dialect.supports.constraints.restrict) {
it('can restrict deletes', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User, { onDelete: 'restrict' });
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
await expect(user.destroy()).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
const tasks = await Task.findAll();
expect(tasks).to.have.length(1);
});
it('can restrict updates', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User, { onUpdate: 'restrict' });
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
const tableName = user.sequelize.getQueryInterface().queryGenerator.addSchema(user.constructor);
await expect(
user.sequelize.getQueryInterface().update(user, tableName, { id: 999 }, { id: user.id })
).to.eventually.be.rejectedWith(Sequelize.ForeignKeyConstraintError);
// Should fail due to FK restriction
const tasks = await Task.findAll();
expect(tasks).to.have.length(1);
});
}
// NOTE: mssql does not support changing an autoincrement primary key
if (Support.getTestDialect() !== 'mssql') {
it('can cascade updates', async function() {
const Task = this.sequelize.define('Task', { title: DataTypes.STRING }),
User = this.sequelize.define('User', { username: DataTypes.STRING });
Task.belongsTo(User, { onUpdate: 'cascade' });
await this.sequelize.sync({ force: true });
const user = await User.create({ username: 'foo' });
const task = await Task.create({ title: 'task' });
await task.setUser(user);
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
const tableName = user.sequelize.getQueryInterface().queryGenerator.addSchema(user.constructor);
await user.sequelize.getQueryInterface().update(user, tableName, { id: 999 }, { id: user.id });
const tasks = await Task.findAll();
expect(tasks).to.have.length(1);
expect(tasks[0].UserId).to.equal(999);
});
}
});
describe('association column', () => {
it('has correct type and name for non-id primary keys with non-integer type', async function() {
const User = this.sequelize.define('UserPKBT', {
username: {
type: DataTypes.STRING
}
});
const Group = this.sequelize.define('GroupPKBT', {
name: {
type: DataTypes.STRING,
primaryKey: true
}
});
User.belongsTo(Group);
await this.sequelize.sync({ force: true });
expect(User.rawAttributes.GroupPKBTName.type).to.an.instanceof(DataTypes.STRING);
});
it('should support a non-primary key as the association column on a target without a primary key', async function() {
const User = this.sequelize.define('User', { username: { type: DataTypes.STRING, unique: true } });
const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
User.removeAttribute('id');
Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });
await this.sequelize.sync({ force: true });
const newUser = await User.create({ username: 'bob' });
const newTask = await Task.create({ title: 'some task' });
await newTask.setUser(newUser);
const foundTask = await Task.findOne({ where: { title: 'some task' } });
const foundUser = await foundTask.getUser();
await expect(foundUser.username).to.equal('bob');
const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
expect(foreignKeysDescriptions[0]).to.includes({
referencedColumnName: 'username',
referencedTableName: 'Users',
columnName: 'user_name'
});
});
it('should support a non-primary unique key as the association column', async function() {
const User = this.sequelize.define('User', {
username: {
type: DataTypes.STRING,
field: 'user_name',
unique: true
}
});
const Task = this.sequelize.define('Task', {
title: DataTypes.STRING
});
Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });
await this.sequelize.sync({ force: true });
const newUser = await User.create({ username: 'bob' });
const newTask = await Task.create({ title: 'some task' });
await newTask.setUser(newUser);
const foundTask = await Task.findOne({ where: { title: 'some task' } });
const foundUser = await foundTask.getUser();
await expect(foundUser.username).to.equal('bob');
const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
expect(foreignKeysDescriptions[0]).to.includes({
referencedColumnName: 'user_name',
referencedTableName: 'Users',
columnName: 'user_name'
});
});
it('should support a non-primary key as the association column with a field option', async function() {
const User = this.sequelize.define('User', {
username: {
type: DataTypes.STRING,
field: 'the_user_name_field',
unique: true
}
});
const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
User.removeAttribute('id');
Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });
await this.sequelize.sync({ force: true });
const newUser = await User.create({ username: 'bob' });
const newTask = await Task.create({ title: 'some task' });
await newTask.setUser(newUser);
const foundTask = await Task.findOne({ where: { title: 'some task' } });
const foundUser = await foundTask.getUser();
await expect(foundUser.username).to.equal('bob');
const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
expect(foreignKeysDescriptions[0]).to.includes({
referencedColumnName: 'the_user_name_field',
referencedTableName: 'Users',
columnName: 'user_name'
});
});
it('should support a non-primary key as the association column in a table with a composite primary key', async function() {
const User = this.sequelize.define('User', {
username: {
type: DataTypes.STRING,
field: 'the_user_name_field',
unique: true
},
age: {
type: DataTypes.INTEGER,
field: 'the_user_age_field',
primaryKey: true
},
weight: {
type: DataTypes.INTEGER,
field: 'the_user_weight_field',
primaryKey: true
}
});
const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' });
await this.sequelize.sync({ force: true });
const newUser = await User.create({ username: 'bob', age: 18, weight: 40 });
const newTask = await Task.create({ title: 'some task' });
await newTask.setUser(newUser);
const foundTask = await Task.findOne({ where: { title: 'some task' } });
const foundUser = await foundTask.getUser();
await expect(foundUser.username).to.equal('bob');
const foreignKeysDescriptions = await this.sequelize.getQueryInterface().getForeignKeyReferencesForTable('Tasks');
expect(foreignKeysDescriptions[0]).to.includes({
referencedColumnName: 'the_user_name_field',
referencedTableName: 'Users',
columnName: 'user_name'
});
});
});
describe('association options', () => {
it('can specify data type for auto-generated relational keys', async function() {
const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING }),
dataTypes = [DataTypes.INTEGER, DataTypes.BIGINT, DataTypes.STRING],
Tasks = {};
dataTypes.forEach(dataType => {
const tableName = `TaskXYZ_${dataType.key}`;
Tasks[dataType] = this.sequelize.define(tableName, { title: DataTypes.STRING });
Tasks[dataType].belongsTo(User, { foreignKey: 'userId', keyType: dataType, constraints: false });
});
await this.sequelize.sync({ force: true });
dataTypes.forEach(dataType => {
expect(Tasks[dataType].rawAttributes.userId.type).to.be.an.instanceof(dataType);
});
});
describe('allows the user to provide an attribute definition object as foreignKey', () => {
it('works with a column that hasnt been defined before', function() {
const Task = this.sequelize.define('task', {}),
User = this.sequelize.define('user', {});
Task.belongsTo(User, {
foreignKey: {
allowNull: false,
name: 'uid'
}
});
expect(Task.rawAttributes.uid).to.be.ok;
expect(Task.rawAttributes.uid.allowNull).to.be.false;
expect(Task.rawAttributes.uid.references.model).to.equal(User.getTableName());
expect(Task.rawAttributes.uid.references.key).to.equal('id');
});
it('works when taking a column directly from the object', function() {
const 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.ok;
expect(Profile.rawAttributes.user_id.references.model).to.equal(User.getTableName());
expect(Profile.rawAttributes.user_id.references.key).to.equal('uid');
expect(Profile.rawAttributes.user_id.allowNull).to.be.false;
});
it('works when merging with an existing definition', function() {
const 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.ok;
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() {
const 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() {
const 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');
});
});
describe('Eager loading', () => {
beforeEach(function() {
this.Individual = this.sequelize.define('individual', {
name: Sequelize.STRING
});
this.Hat = this.sequelize.define('hat', {
name: Sequelize.STRING
});
this.Individual.belongsTo(this.Hat, {
as: 'personwearinghat'
});
});
it('should load with an alias', async function() {
await this.sequelize.sync({ force: true });
const [individual1, hat] = await Promise.all([
this.Individual.create({ name: 'Foo Bar' }),
this.Hat.create({ name: 'Baz' })
]);
await individual1.setPersonwearinghat(hat);
const individual0 = await this.Individual.findOne({
where: { name: 'Foo Bar' },
include: [{ model: this.Hat, as: 'personwearinghat' }]
});
expect(individual0.name).to.equal('Foo Bar');
expect(individual0.personwearinghat.name).to.equal('Baz');
const individual = await this.Individual.findOne({
where: { name: 'Foo Bar' },
include: [{
model: this.Hat,
as: { singular: 'personwearinghat' }
}]
});
expect(individual.name).to.equal('Foo Bar');
expect(individual.personwearinghat.name).to.equal('Baz');
});
it('should load all', async function() {
await this.sequelize.sync({ force: true });
const [individual0, hat] = await Promise.all([
this.Individual.create({ name: 'Foo Bar' }),
this.Hat.create({ name: 'Baz' })
]);
await individual0.setPersonwearinghat(hat);
const individual = await this.Individual.findOne({
where: { name: 'Foo Bar' },
include: [{ all: true }]
});
expect(individual.name).to.equal('Foo Bar');
expect(individual.personwearinghat.name).to.equal('Baz');
});
});
});