-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
model.test.js
2883 lines (2468 loc) · 96.4 KB
/
model.test.js
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const chai = require('chai');
const expect = chai.expect;
const Support = require('./support');
const { DataTypes, Sequelize, Op, AggregateError } = require('@sequelize/core');
const dialectName = Support.getTestDialect();
const dialect = Support.sequelize.dialect;
const sinon = require('sinon');
const _ = require('lodash');
const dayjs = require('dayjs');
const current = Support.sequelize;
const semver = require('semver');
const pMap = require('p-map');
const { expectsql } = require('../support');
describe(Support.getTestDialectTeaser('Model'), () => {
let isMySQL8;
before(function () {
this.clock = sinon.useFakeTimers();
});
after(function () {
this.clock.restore();
});
beforeEach(async function () {
isMySQL8 = dialectName === 'mysql' && semver.satisfies(current.options.databaseVersion, '>=8.0.0');
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
secretValue: DataTypes.STRING,
data: DataTypes.STRING,
intVal: DataTypes.INTEGER,
theDate: DataTypes.DATE,
aBool: DataTypes.BOOLEAN,
});
await this.User.sync({ force: true });
});
describe('constructor', () => {
it('uses the passed dao name as tablename if freezeTableName', function () {
const User = this.sequelize.define('FrozenUser', {}, { freezeTableName: true });
expect(User.tableName).to.equal('FrozenUser');
});
it('uses the pluralized dao name as tablename unless freezeTableName', function () {
const User = this.sequelize.define('SuperUser', {}, { freezeTableName: false });
expect(User.tableName).to.equal('SuperUsers');
});
it('uses checks to make sure dao factory is not leaking on multiple define', function () {
this.sequelize.define('SuperUser', {}, { freezeTableName: false });
const factorySize = this.sequelize.modelManager.all.length;
this.sequelize.define('SuperUser', {}, { freezeTableName: false });
const factorySize2 = this.sequelize.modelManager.all.length;
expect(factorySize).to.equal(factorySize2);
});
it('allows us to predefine the ID column with our own specs', async function () {
const User = this.sequelize.define('UserCol', {
id: {
type: DataTypes.STRING,
defaultValue: 'User',
primaryKey: true,
},
});
await User.sync({ force: true });
expect(await User.create({ id: 'My own ID!' })).to.have.property('id', 'My own ID!');
});
it('throws an error if 2 autoIncrements are passed', function () {
expect(() => {
this.sequelize.define('UserWithTwoAutoIncrements', {
userid: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userscore: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
});
}).to.throw(Error, 'Invalid Instance definition. Only one autoincrement field allowed.');
});
it('throws an error if a custom model-wide validation is not a function', function () {
expect(() => {
this.sequelize.define('Foo', {
field: DataTypes.INTEGER,
}, {
validate: {
notFunction: 33,
},
});
}).to.throw(Error, 'Members of the validate option must be functions. Model: Foo, error with validate member notFunction');
});
it('throws an error if a custom model-wide validation has the same name as a field', function () {
expect(() => {
this.sequelize.define('Foo', {
field: DataTypes.INTEGER,
}, {
validate: {
field() {},
},
});
}).to.throw(Error, 'A model validator function must not have the same name as a field. Model: Foo, field/validation name: field');
});
it('should allow me to set a default value for createdAt and updatedAt', async function () {
const UserTable = this.sequelize.define('UserCol', {
aNumber: DataTypes.INTEGER,
createdAt: {
type: DataTypes.DATE,
defaultValue: dayjs('2012-01-01').toDate(),
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: dayjs('2012-01-02').toDate(),
},
}, { timestamps: true });
await UserTable.sync({ force: true });
const user = await UserTable.create({ aNumber: 5 });
await UserTable.bulkCreate([{ aNumber: 10 }, { aNumber: 12 }]);
const users = await UserTable.findAll({ where: { aNumber: { [Op.gte]: 10 } } });
expect(dayjs(user.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01');
expect(dayjs(user.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02');
for (const u of users) {
expect(dayjs(u.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01');
expect(dayjs(u.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02');
}
});
it('should allow me to set a function as default value', async function () {
const defaultFunction = sinon.stub().returns(5);
const UserTable = this.sequelize.define('UserCol', {
aNumber: {
type: DataTypes.INTEGER,
defaultValue: defaultFunction,
},
}, { timestamps: true });
await UserTable.sync({ force: true });
const user = await UserTable.create();
const user2 = await UserTable.create();
expect(user.aNumber).to.equal(5);
expect(user2.aNumber).to.equal(5);
expect(defaultFunction.callCount).to.equal(2);
});
it('should throw `TypeError` when value for updatedAt, createdAt, or deletedAt is neither string nor boolean', async function () {
const modelName = 'UserCol';
const attributes = { aNumber: DataTypes.INTEGER };
expect(() => {
this.sequelize.define(modelName, attributes, { timestamps: true, updatedAt: {} });
}).to.throw(Error, 'Value for "updatedAt" option must be a string or a boolean, got object');
expect(() => {
this.sequelize.define(modelName, attributes, { timestamps: true, createdAt: 100 });
}).to.throw(Error, 'Value for "createdAt" option must be a string or a boolean, got number');
expect(() => {
this.sequelize.define(modelName, attributes, { timestamps: true, deletedAt: () => {} });
}).to.throw(Error, 'Value for "deletedAt" option must be a string or a boolean, got function');
});
it('should allow me to use `true` as a value for updatedAt, createdAt, and deletedAt fields', async function () {
const UserTable = this.sequelize.define(
'UserCol',
{
aNumber: DataTypes.INTEGER,
},
{
timestamps: true,
updatedAt: true,
createdAt: true,
deletedAt: true,
paranoid: true,
},
);
await UserTable.sync({ force: true });
const user = await UserTable.create({ aNumber: 4 });
expect(user.true).to.not.exist;
expect(user.updatedAt).to.exist;
expect(user.createdAt).to.exist;
await user.destroy();
await user.reload({ paranoid: false });
expect(user.deletedAt).to.exist;
});
it('should allow me to override updatedAt, createdAt, and deletedAt fields', async function () {
const UserTable = this.sequelize.define('UserCol', {
aNumber: DataTypes.INTEGER,
}, {
timestamps: true,
updatedAt: 'updatedOn',
createdAt: 'dateCreated',
deletedAt: 'deletedAtThisTime',
paranoid: true,
});
await UserTable.sync({ force: true });
const user = await UserTable.create({ aNumber: 4 });
expect(user.updatedOn).to.exist;
expect(user.dateCreated).to.exist;
await user.destroy();
await user.reload({ paranoid: false });
expect(user.deletedAtThisTime).to.exist;
});
it('should allow me to disable some of the timestamp fields', async function () {
const UpdatingUser = this.sequelize.define('UpdatingUser', {
name: DataTypes.STRING,
}, {
timestamps: true,
updatedAt: false,
createdAt: false,
deletedAt: 'deletedAtThisTime',
paranoid: true,
});
await UpdatingUser.sync({ force: true });
let user = await UpdatingUser.create({ name: 'heyo' });
expect(user.createdAt).not.to.exist;
expect(user.false).not.to.exist; // because, you know we might accidentally add a field named 'false'
user.name = 'heho';
user = await user.save();
expect(user.updatedAt).not.to.exist;
await user.destroy();
await user.reload({ paranoid: false });
expect(user.deletedAtThisTime).to.exist;
});
it('returns proper defaultValues after save when setter is set', async function () {
const titleSetter = sinon.spy();
const Task = this.sequelize.define('TaskBuild', {
title: {
type: DataTypes.STRING(50),
allowNull: false,
defaultValue: '',
},
}, {
setterMethods: {
title: titleSetter,
},
});
await Task.sync({ force: true });
const record = await Task.build().save();
expect(record.title).to.be.a('string');
expect(record.title).to.equal('');
expect(titleSetter.notCalled).to.be.ok; // The setter method should not be invoked for default values
});
it('should work with both paranoid and underscored being true', async function () {
const UserTable = this.sequelize.define('UserCol', {
aNumber: DataTypes.INTEGER,
}, {
paranoid: true,
underscored: true,
});
await UserTable.sync({ force: true });
await UserTable.create({ aNumber: 30 });
expect(await UserTable.count()).to.equal(1);
});
it('allows unique on column with field aliases', async function () {
const User = this.sequelize.define('UserWithUniqueFieldAlias', {
userName: { type: DataTypes.STRING, unique: 'user_name_unique', field: 'user_name' },
});
await User.sync({ force: true });
const indexes = (await this.sequelize.queryInterface.showIndex(User.getTableName()))
.filter(index => !index.primary);
expect(indexes).to.have.length(1);
const index = indexes[0];
expect(index.primary).to.equal(false);
expect(index.unique).to.equal(true);
expect(index.name).to.equal('user_name_unique');
switch (dialectName) {
case 'mariadb':
case 'mysql': {
expect(index.fields).to.deep.equal([{ attribute: 'user_name', length: undefined, order: 'ASC' }]);
expect(index.type).to.equal('BTREE');
break;
}
case 'postgres': {
expect(index.fields).to.deep.equal([{ attribute: 'user_name', collate: undefined, order: undefined, length: undefined }]);
break;
}
case 'db2':
case 'mssql': {
expect(index.fields).to.deep.equal([{ attribute: 'user_name', collate: undefined, length: undefined, order: 'ASC' }]);
break;
}
case 'sqlite':
default: {
expect(index.fields).to.deep.equal([{ attribute: 'user_name', length: undefined, order: undefined }]);
break;
}
}
});
if (dialectName !== 'ibmi') {
it('allows us to customize the error message for unique constraint', async function () {
const User = this.sequelize.define('UserWithUniqueUsername', {
username: { type: DataTypes.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' } },
email: { type: DataTypes.STRING, unique: 'user_and_email' },
});
await User.sync({ force: true });
try {
await Promise.all([
User.create({ username: 'tobi', email: 'tobi@tobi.me' }),
User.create({ username: 'tobi', email: 'tobi@tobi.me' }),
]);
} catch (error) {
if (!(error instanceof Sequelize.UniqueConstraintError)) {
throw error;
}
expect(error.message).to.equal('User and email must be unique');
}
});
// If you use migrations to create unique indexes that have explicit names and/or contain fields
// that have underscore in their name. Then sequelize must use the index name to map the custom message to the error thrown from db.
it('allows us to map the customized error message with unique constraint name', async function () {
// Fake migration style index creation with explicit index definition
let User = this.sequelize.define('UserWithUniqueUsername', {
user_id: { type: DataTypes.INTEGER },
email: { type: DataTypes.STRING },
}, {
indexes: [
{
name: 'user_and_email_index',
msg: 'User and email must be unique',
unique: true,
method: 'BTREE',
fields: ['user_id', { attribute: 'email', collate: dialectName === 'sqlite' ? 'RTRIM' : 'en_US', order: 'DESC', length: 5 }],
}],
});
await User.sync({ force: true });
// Redefine the model to use the index in database and override error message
User = this.sequelize.define('UserWithUniqueUsername', {
user_id: { type: DataTypes.INTEGER, unique: { name: 'user_and_email_index', msg: 'User and email must be unique' } },
email: { type: DataTypes.STRING, unique: 'user_and_email_index' },
});
try {
await Promise.all([
User.create({ user_id: 1, email: 'tobi@tobi.me' }),
User.create({ user_id: 1, email: 'tobi@tobi.me' }),
]);
} catch (error) {
if (!(error instanceof Sequelize.UniqueConstraintError)) {
throw error;
}
expect(error.message).to.equal('User and email must be unique');
}
});
}
describe('descending indices (MySQL 8 specific)', () => {
it('complains about missing support for descending indexes', async function () {
if (!isMySQL8) {
return;
}
const indices = [{
name: 'a_b_uniq',
unique: true,
method: 'BTREE',
fields: [
'fieldB',
{
attribute: 'fieldA',
collate: 'en_US',
order: 'DESC',
length: 5,
},
],
}];
this.sequelize.define('model', {
fieldA: DataTypes.STRING,
fieldB: DataTypes.INTEGER,
fieldC: DataTypes.STRING,
fieldD: DataTypes.STRING,
}, {
indexes: indices,
engine: 'MyISAM',
});
try {
await this.sequelize.sync();
expect.fail();
} catch (error) {
expect(error.message).to.include('The storage engine for the table doesn\'t support descending indexes');
}
});
it('works fine with InnoDB', async function () {
if (!isMySQL8) {
return;
}
const indices = [{
name: 'a_b_uniq',
unique: true,
method: 'BTREE',
fields: [
'fieldB',
{
attribute: 'fieldA',
collate: 'en_US',
order: 'DESC',
length: 5,
},
],
}];
this.sequelize.define('model', {
fieldA: DataTypes.STRING,
fieldB: DataTypes.INTEGER,
fieldC: DataTypes.STRING,
fieldD: DataTypes.STRING,
}, {
indexes: indices,
engine: 'InnoDB',
});
await this.sequelize.sync();
});
});
it('should allow the user to specify indexes in options', async function () {
const indices = [{
name: 'a_b_uniq',
unique: true,
method: 'BTREE',
fields: [
'fieldB',
{
attribute: 'fieldA',
collate: dialectName === 'sqlite' ? 'RTRIM' : 'en_US',
order: dialectName === 'ibmi' ? ''
// MySQL doesn't support DESC indexes (will throw)
// MariaDB doesn't support DESC indexes (will silently replace it with ASC)
: (dialectName === 'mysql' || dialectName === 'mariadb') ? 'ASC'
: `DESC`,
length: 5,
},
],
}];
if (!['mssql', 'db2', 'ibmi'].includes(dialectName)) {
indices.push({
type: 'FULLTEXT',
fields: ['fieldC'],
concurrently: true,
}, {
type: 'FULLTEXT',
fields: ['fieldD'],
});
}
const Model = this.sequelize.define('model', {
fieldA: DataTypes.STRING,
fieldB: DataTypes.INTEGER,
fieldC: DataTypes.STRING,
fieldD: DataTypes.STRING,
}, {
indexes: indices,
engine: 'MyISAM',
});
await this.sequelize.sync();
await this.sequelize.sync(); // The second call should not try to create the indices again
const args = await this.sequelize.queryInterface.showIndex(Model.tableName);
let primary;
let idx1;
let idx2;
let idx3;
switch (dialectName) {
case 'sqlite': {
// PRAGMA index_info does not return the primary index
idx1 = args[0];
idx2 = args[1];
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldB', length: undefined, order: undefined },
{ attribute: 'fieldA', length: undefined, order: undefined },
]);
expect(idx2.fields).to.deep.equal([
{ attribute: 'fieldC', length: undefined, order: undefined },
]);
break;
}
case 'db2': {
idx1 = args[1];
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldB', length: undefined, order: 'ASC', collate: undefined },
{ attribute: 'fieldA', length: undefined, order: 'DESC', collate: undefined },
]);
break;
}
case 'ibmi': {
idx1 = args[0];
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldA', length: undefined, order: undefined, collate: undefined },
{ attribute: 'fieldB', length: undefined, order: undefined, collate: undefined },
]);
break;
}
case 'mssql': {
idx1 = args[0];
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldB', length: undefined, order: 'ASC', collate: undefined },
{ attribute: 'fieldA', length: undefined, order: 'DESC', collate: undefined },
]);
break;
}
case 'postgres': {
// Postgres returns indexes in alphabetical order
primary = args[2];
idx1 = args[0];
idx2 = args[1];
idx3 = args[2];
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldB', length: undefined, order: undefined, collate: undefined },
{ attribute: 'fieldA', length: undefined, order: 'DESC', collate: 'en_US' },
]);
expect(idx2.fields).to.deep.equal([
{ attribute: 'fieldC', length: undefined, order: undefined, collate: undefined },
]);
expect(idx3.fields).to.deep.equal([
{ attribute: 'fieldD', length: undefined, order: undefined, collate: undefined },
]);
break;
}
default: {
// And finally mysql returns the primary first, and then the rest in the order they were defined
primary = args[0];
idx1 = args[1];
idx2 = args[2];
expect(primary.primary).to.be.ok;
expect(idx1.type).to.equal('BTREE');
expect(idx2.type).to.equal('FULLTEXT');
expect(idx1.fields).to.deep.equal([
{ attribute: 'fieldB', length: undefined, order: 'ASC' },
{
attribute: 'fieldA',
length: 5,
// mysql & mariadb don't support DESC indexes
order: 'ASC',
},
]);
expect(idx2.fields).to.deep.equal([
{ attribute: 'fieldC', length: undefined, order: undefined },
]);
}
}
expect(idx1.name).to.equal('a_b_uniq');
expect(idx1.unique).to.be.ok;
if (!['mssql', 'db2', 'ibmi'].includes(dialectName)) {
expect(idx2.name).to.equal('models_field_c');
expect(idx2.unique).not.to.be.ok;
}
});
});
describe('build', () => {
it('doesn\'t create database entries', async function () {
this.User.build({ username: 'John Wayne' });
expect(await this.User.findAll()).to.have.length(0);
});
it('fills the objects with default values', function () {
const Task = this.sequelize.define('TaskBuild', {
title: { type: DataTypes.STRING, defaultValue: 'a task!' },
foo: { type: DataTypes.INTEGER, defaultValue: 2 },
bar: { type: DataTypes.DATE },
foobar: { type: DataTypes.TEXT, defaultValue: 'asd' },
flag: { type: DataTypes.BOOLEAN, defaultValue: false },
});
expect(Task.build().title).to.equal('a task!');
expect(Task.build().foo).to.equal(2);
expect(Task.build().bar).to.not.be.ok;
expect(Task.build().foobar).to.equal('asd');
expect(Task.build().flag).to.be.false;
});
it('fills the objects with default values', function () {
const Task = this.sequelize.define('TaskBuild', {
title: { type: DataTypes.STRING, defaultValue: 'a task!' },
foo: { type: DataTypes.INTEGER, defaultValue: 2 },
bar: { type: DataTypes.DATE },
foobar: { type: DataTypes.TEXT, defaultValue: 'asd' },
flag: { type: DataTypes.BOOLEAN, defaultValue: false },
}, { timestamps: false });
expect(Task.build().title).to.equal('a task!');
expect(Task.build().foo).to.equal(2);
expect(Task.build().bar).to.not.be.ok;
expect(Task.build().foobar).to.equal('asd');
expect(Task.build().flag).to.be.false;
});
it('attaches getter and setter methods from attribute definition', function () {
const Product = this.sequelize.define('ProductWithSettersAndGetters1', {
price: {
type: DataTypes.INTEGER,
get() {
return `answer = ${this.getDataValue('price')}`;
},
set(v) {
return this.setDataValue('price', v + 42);
},
},
});
expect(Product.build({ price: 42 }).price).to.equal('answer = 84');
const p = Product.build({ price: 1 });
expect(p.price).to.equal('answer = 43');
p.price = 0;
expect(p.price).to.equal('answer = 42');
});
it('attaches getter and setter methods from options', function () {
const Product = this.sequelize.define('ProductWithSettersAndGetters2', {
priceInCents: DataTypes.INTEGER,
}, {
setterMethods: {
price(value) {
this.dataValues.priceInCents = value * 100;
},
},
getterMethods: {
price() {
return `$${this.getDataValue('priceInCents') / 100}`;
},
priceInCents() {
return this.dataValues.priceInCents;
},
},
});
expect(Product.build({ price: 20 }).priceInCents).to.equal(20 * 100);
expect(Product.build({ priceInCents: 30 * 100 }).price).to.equal(`$${30}`);
});
it('attaches getter and setter methods from options only if not defined in attribute', function () {
const Product = this.sequelize.define('ProductWithSettersAndGetters3', {
price1: {
type: DataTypes.INTEGER,
set(v) {
this.setDataValue('price1', v * 10);
},
},
price2: {
type: DataTypes.INTEGER,
get() {
return this.getDataValue('price2') * 10;
},
},
}, {
setterMethods: {
price1(v) {
this.setDataValue('price1', v * 100);
},
},
getterMethods: {
price2() {
return `$${this.getDataValue('price2')}`;
},
},
});
const p = Product.build({ price1: 1, price2: 2 });
expect(p.price1).to.equal(10);
expect(p.price2).to.equal(20);
});
describe('include', () => {
it('should support basic includes', function () {
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
});
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
});
const User = this.sequelize.define('User', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
});
Product.hasMany(Tag);
Product.belongsTo(User);
const product = Product.build({
id: 1,
title: 'Chair',
Tags: [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
],
User: {
id: 1,
first_name: 'Mick',
last_name: 'Hansen',
},
}, {
include: [
User,
Tag,
],
});
expect(product.Tags).to.be.ok;
expect(product.Tags.length).to.equal(2);
expect(product.Tags[0]).to.be.instanceof(Tag);
expect(product.User).to.be.ok;
expect(product.User).to.be.instanceof(User);
});
it('should support includes with aliases', function () {
const Product = this.sequelize.define('Product', {
title: DataTypes.STRING,
});
const Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
});
const User = this.sequelize.define('User', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
});
Product.hasMany(Tag, { as: 'categories' });
Product.belongsToMany(User, { as: 'followers', through: 'product_followers' });
User.belongsToMany(Product, { as: 'following', through: 'product_followers' });
const product = Product.build({
id: 1,
title: 'Chair',
categories: [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'Delta' },
],
followers: [
{
id: 1,
first_name: 'Mick',
last_name: 'Hansen',
},
{
id: 2,
first_name: 'Jan',
last_name: 'Meier',
},
],
}, {
include: [
{ model: User, as: 'followers' },
{ model: Tag, as: 'categories' },
],
});
expect(product.categories).to.be.ok;
expect(product.categories.length).to.equal(4);
expect(product.categories[0]).to.be.instanceof(Tag);
expect(product.followers).to.be.ok;
expect(product.followers.length).to.equal(2);
expect(product.followers[0]).to.be.instanceof(User);
});
});
});
describe('findOne', () => {
if (current.dialect.supports.transactions) {
it('supports the transaction option in the first parameter', async function () {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', {
username: DataTypes.STRING,
foo: DataTypes.STRING,
});
await User.sync({ force: true });
const t = await sequelize.transaction();
await User.create({ username: 'foo' }, { transaction: t });
const user = await User.findOne({ where: { username: 'foo' }, transaction: t });
expect(user).to.not.be.null;
await t.rollback();
});
}
it('should not fail if model is paranoid and where is an empty array', async function () {
const User = this.sequelize.define('User', { username: DataTypes.STRING }, { paranoid: true });
await User.sync({ force: true });
await User.create({ username: 'A fancy name' });
expect((await User.findOne({ where: [] })).username).to.equal('A fancy name');
});
it('should work if model is paranoid and only operator in where clause is a Symbol (#8406)', async function () {
const User = this.sequelize.define('User', { username: DataTypes.STRING }, { paranoid: true });
await User.sync({ force: true });
await User.create({ username: 'foo' });
expect(await User.findOne({
where: {
[Op.or]: [
{ username: 'bar' },
{ username: 'baz' },
],
},
})).to.not.be.ok;
});
});
describe('findOrBuild', () => {
if (current.dialect.supports.transactions) {
it('supports transactions', async function () {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: DataTypes.STRING, foo: DataTypes.STRING });
await User.sync({ force: true });
const t = await sequelize.transaction();
await User.create({ username: 'foo' }, { transaction: t });
const [user1] = await User.findOrBuild({
where: { username: 'foo' },
});
const [user2] = await User.findOrBuild({
where: { username: 'foo' },
transaction: t,
});
const [user3] = await User.findOrBuild({
where: { username: 'foo' },
defaults: { foo: 'asd' },
transaction: t,
});
expect(user1.isNewRecord).to.be.true;
expect(user2.isNewRecord).to.be.false;
expect(user3.isNewRecord).to.be.false;
await t.commit();
});
}
describe('returns an instance if it already exists', () => {
it('with a single find field', async function () {
const user = await this.User.create({ username: 'Username' });
const [_user, initialized] = await this.User.findOrBuild({
where: { username: user.username },
});
expect(_user.id).to.equal(user.id);
expect(_user.username).to.equal('Username');
expect(initialized).to.be.false;
});
it('with multiple find fields', async function () {
const user = await this.User.create({ username: 'Username', data: 'data' });
const [_user, initialized] = await this.User.findOrBuild({
where: {
username: user.username,
data: user.data,
},
});
expect(_user.id).to.equal(user.id);
expect(_user.username).to.equal('Username');
expect(_user.data).to.equal('data');
expect(initialized).to.be.false;
});
it('builds a new instance with default value.', async function () {
const [user, initialized] = await this.User.findOrBuild({
where: { username: 'Username' },
defaults: { data: 'ThisIsData' },
});
expect(user.id).to.be.null;
expect(user.username).to.equal('Username');
expect(user.data).to.equal('ThisIsData');
expect(initialized).to.be.true;
expect(user.isNewRecord).to.be.true;
});
});
});
describe('save', () => {
it('should map the correct fields when saving instance (#10589)', async function () {
const User = this.sequelize.define('User', {
id3: {
field: 'id',
type: DataTypes.INTEGER,
primaryKey: true,
},
id: {
field: 'id2',
type: DataTypes.INTEGER,
allowNull: false,
},
id2: {
field: 'id3',
type: DataTypes.INTEGER,
allowNull: false,
},
});
await this.sequelize.sync({ force: true });
await User.create({ id3: 94, id: 87, id2: 943 });
const user = await User.findByPk(94);
await user.set('id2', 8877);
await user.save({ id2: 8877 });
expect((await User.findByPk(94)).id2).to.equal(8877);
});
});
describe('update', () => {
it('throws an error if no where clause is given', async function () {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
try {
await User.update();
throw new Error('Update should throw an error if no where clause is given.');
} catch (error) {
expect(error).to.be.an.instanceof(Error);
expect(error.message).to.equal('Missing where attribute in the options parameter');
}
});
it('should map the correct fields when updating instance (#10589)', async function () {
const User = this.sequelize.define('User', {
id3: {
field: 'id',
type: DataTypes.INTEGER,
primaryKey: true,
},
id: {
field: 'id2',
type: DataTypes.INTEGER,
allowNull: false,
},
id2: {
field: 'id3',
type: DataTypes.INTEGER,
allowNull: false,
},
});
await this.sequelize.sync({ force: true });
await User.create({ id3: 94, id: 87, id2: 943 });
const user = await User.findByPk(94);