model.test.js
91.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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
'use strict';
const chai = require('chai'),
Sequelize = require('../../index'),
expect = chai.expect,
Support = require('./support'),
DataTypes = require('../../lib/data-types'),
dialect = Support.getTestDialect(),
errors = require('../../lib/errors'),
sinon = require('sinon'),
_ = require('lodash'),
moment = require('moment'),
current = Support.sequelize,
Op = Sequelize.Op,
semver = require('semver'),
pMap = require('p-map');
describe(Support.getTestDialectTeaser('Model'), () => {
before(function() {
this.clock = sinon.useFakeTimers();
});
after(function() {
this.clock.restore();
});
beforeEach(async function() {
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: Sequelize.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: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
userscore: { type: Sequelize.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: Sequelize.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: Sequelize.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: Sequelize.INTEGER,
createdAt: {
type: Sequelize.DATE,
defaultValue: moment('2012-01-01').toDate()
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: moment('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(moment(user.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01');
expect(moment(user.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02');
for (const u of users) {
expect(moment(u.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01');
expect(moment(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: Sequelize.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: Sequelize.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: Sequelize.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: Sequelize.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(),
Task = this.sequelize.define('TaskBuild', {
title: {
type: Sequelize.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: Sequelize.INTEGER
}, {
paranoid: true,
underscored: true
});
await UserTable.sync({ force: true });
await UserTable.create({ aNumber: 30 });
expect(await UserTable.count()).to.equal(1);
});
it('allows multiple column unique keys to be defined', async function() {
const User = this.sequelize.define('UserWithUniqueUsername', {
username: { type: Sequelize.STRING, unique: 'user_and_email' },
email: { type: Sequelize.STRING, unique: 'user_and_email' },
aCol: { type: Sequelize.STRING, unique: 'a_and_b' },
bCol: { type: Sequelize.STRING, unique: 'a_and_b' }
});
await User.sync({ force: true, logging: _.after(2, _.once(sql => {
if (dialect === 'mssql') {
expect(sql).to.match(/CONSTRAINT\s*([`"[]?user_and_email[`"\]]?)?\s*UNIQUE\s*\([`"[]?username[`"\]]?, [`"[]?email[`"\]]?\)/);
expect(sql).to.match(/CONSTRAINT\s*([`"[]?a_and_b[`"\]]?)?\s*UNIQUE\s*\([`"[]?aCol[`"\]]?, [`"[]?bCol[`"\]]?\)/);
} else {
expect(sql).to.match(/UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/);
expect(sql).to.match(/UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/);
}
})) });
});
it('allows unique on column with field aliases', async function() {
const User = this.sequelize.define('UserWithUniqueFieldAlias', {
userName: { type: Sequelize.STRING, unique: 'user_name_unique', field: 'user_name' }
});
await User.sync({ force: true });
const indexes = await this.sequelize.queryInterface.showIndex(User.tableName);
let idxUnique;
if (dialect === 'sqlite') {
expect(indexes).to.have.length(1);
idxUnique = indexes[0];
expect(idxUnique.primary).to.equal(false);
expect(idxUnique.unique).to.equal(true);
expect(idxUnique.fields).to.deep.equal([{ attribute: 'user_name', length: undefined, order: undefined }]);
} else if (dialect === 'mysql') {
expect(indexes).to.have.length(2);
idxUnique = indexes[1];
expect(idxUnique.primary).to.equal(false);
expect(idxUnique.unique).to.equal(true);
expect(idxUnique.fields).to.deep.equal([{ attribute: 'user_name', length: undefined, order: 'ASC' }]);
expect(idxUnique.type).to.equal('BTREE');
} else if (dialect === 'postgres') {
expect(indexes).to.have.length(2);
idxUnique = indexes[1];
expect(idxUnique.primary).to.equal(false);
expect(idxUnique.unique).to.equal(true);
expect(idxUnique.fields).to.deep.equal([{ attribute: 'user_name', collate: undefined, order: undefined, length: undefined }]);
} else if (dialect === 'mssql') {
expect(indexes).to.have.length(2);
idxUnique = indexes[1];
expect(idxUnique.primary).to.equal(false);
expect(idxUnique.unique).to.equal(true);
expect(idxUnique.fields).to.deep.equal([{ attribute: 'user_name', collate: undefined, length: undefined, order: 'ASC' }]);
}
});
it('allows us to customize the error message for unique constraint', async function() {
const User = this.sequelize.define('UserWithUniqueUsername', {
username: { type: Sequelize.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' } },
email: { type: Sequelize.STRING, unique: 'user_and_email' }
});
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 (err) {
if (!(err instanceof Sequelize.UniqueConstraintError)) throw err;
expect(err.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: Sequelize.INTEGER },
email: { type: Sequelize.STRING }
}, {
indexes: [
{
name: 'user_and_email_index',
msg: 'User and email must be unique',
unique: true,
method: 'BTREE',
fields: ['user_id', { attribute: 'email', collate: dialect === '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: Sequelize.INTEGER, unique: { name: 'user_and_email_index', msg: 'User and email must be unique' } },
email: { type: Sequelize.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 (err) {
if (!(err instanceof Sequelize.UniqueConstraintError)) throw err;
expect(err.message).to.equal('User and email must be unique');
}
});
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: dialect === 'sqlite' ? 'RTRIM' : 'en_US',
order: 'DESC',
length: 5
}
]
}];
if (dialect !== 'mssql') {
indices.push({
type: 'FULLTEXT',
fields: ['fieldC'],
concurrently: true
});
indices.push({
type: 'FULLTEXT',
fields: ['fieldD']
});
}
const Model = this.sequelize.define('model', {
fieldA: Sequelize.STRING,
fieldB: Sequelize.INTEGER,
fieldC: Sequelize.STRING,
fieldD: Sequelize.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, idx1, idx2, idx3;
if (dialect === '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 }
]);
} else if (dialect === '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 }
]);
} else if (dialect === '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 }
]);
} else {
// 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, 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 (dialect !== 'mssql') {
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: Sequelize.STRING, defaultValue: 'a task!' },
foo: { type: Sequelize.INTEGER, defaultValue: 2 },
bar: { type: Sequelize.DATE },
foobar: { type: Sequelize.TEXT, defaultValue: 'asd' },
flag: { type: Sequelize.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: Sequelize.STRING, defaultValue: 'a task!' },
foo: { type: Sequelize.INTEGER, defaultValue: 2 },
bar: { type: Sequelize.DATE },
foobar: { type: Sequelize.TEXT, defaultValue: 'asd' },
flag: { type: Sequelize.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: Sequelize.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: Sequelize.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: Sequelize.INTEGER,
set(v) { this.setDataValue('price1', v * 10); }
},
price2: {
type: Sequelize.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: Sequelize.STRING
});
const Tag = this.sequelize.define('Tag', {
name: Sequelize.STRING
});
const User = this.sequelize.define('User', {
first_name: Sequelize.STRING,
last_name: Sequelize.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: Sequelize.STRING
});
const Tag = this.sequelize.define('Tag', {
name: Sequelize.STRING
});
const User = this.sequelize.define('User', {
first_name: Sequelize.STRING,
last_name: Sequelize.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: Sequelize.STRING,
foo: Sequelize.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: Sequelize.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: Sequelize.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: Sequelize.STRING, foo: Sequelize.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: Sequelize.INTEGER,
primaryKey: true
},
id: {
field: 'id2',
type: Sequelize.INTEGER,
allowNull: false
},
id2: {
field: 'id3',
type: Sequelize.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 (err) {
expect(err).to.be.an.instanceof(Error);
expect(err.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: Sequelize.INTEGER,
primaryKey: true
},
id: {
field: 'id2',
type: Sequelize.INTEGER,
allowNull: false
},
id2: {
field: 'id3',
type: Sequelize.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.update({ id2: 8877 });
expect((await User.findByPk(94)).id2).to.equal(8877);
});
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Sequelize.STRING });
await User.sync({ force: true });
await User.create({ username: 'foo' });
const t = await sequelize.transaction();
await User.update({ username: 'bar' }, {
where: { username: 'foo' },
transaction: t
});
const users1 = await User.findAll();
const users2 = await User.findAll({ transaction: t });
expect(users1[0].username).to.equal('foo');
expect(users2[0].username).to.equal('bar');
await t.rollback();
});
}
it('updates the attributes that we select only without updating createdAt', async function() {
const User = this.sequelize.define('User1', {
username: Sequelize.STRING,
secretValue: Sequelize.STRING
}, {
paranoid: true
});
let test = false;
await User.sync({ force: true });
const user = await User.create({ username: 'Peter', secretValue: '42' });
await user.update({ secretValue: '43' }, {
fields: ['secretValue'],
logging(sql) {
test = true;
if (dialect === 'mssql') {
expect(sql).to.not.contain('createdAt');
} else {
expect(sql).to.match(/UPDATE\s+[`"]+User1s[`"]+\s+SET\s+[`"]+secretValue[`"]=(\$1|\?),[`"]+updatedAt[`"]+=(\$2|\?)\s+WHERE [`"]+id[`"]+\s=\s(\$3|\?)/);
}
},
returning: ['*']
});
expect(test).to.be.true;
});
it('allows sql logging of updated statements', async function() {
const User = this.sequelize.define('User', {
name: Sequelize.STRING,
bio: Sequelize.TEXT
}, {
paranoid: true
});
let test = false;
await User.sync({ force: true });
const u = await User.create({ name: 'meg', bio: 'none' });
expect(u).to.exist;
await u.update({ name: 'brian' }, {
logging(sql) {
test = true;
expect(sql).to.exist;
expect(sql.toUpperCase()).to.include('UPDATE');
}
});
expect(test).to.be.true;
});
it('updates only values that match filter', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
await this.User.update({ username: 'Bill' }, { where: { secretValue: '42' } });
const users = await this.User.findAll({ order: ['id'] });
expect(users).to.have.lengthOf(3);
for (const user of users) {
if (user.secretValue === '42') {
expect(user.username).to.equal('Bill');
} else {
expect(user.username).to.equal('Bob');
}
}
});
it('throws an error if where has a key with undefined value', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
try {
await this.User.update({ username: 'Bill' }, {
where: {
secretValue: '42',
username: undefined
}
});
throw new Error('Update should throw an error if where has a key with undefined value');
} catch (err) {
expect(err).to.be.an.instanceof(Error);
expect(err.message).to.equal('WHERE parameter "username" has invalid "undefined" value');
}
});
it('updates only values that match the allowed fields', async function() {
const data = [{ username: 'Peter', secretValue: '42' }];
await this.User.bulkCreate(data);
await this.User.update({ username: 'Bill', secretValue: '43' }, { where: { secretValue: '42' }, fields: ['username'] });
const users = await this.User.findAll({ order: ['id'] });
expect(users).to.have.lengthOf(1);
expect(users[0].username).to.equal('Bill');
expect(users[0].secretValue).to.equal('42');
});
it('updates with casting', async function() {
await this.User.create({ username: 'John' });
await this.User.update({
username: this.sequelize.cast('1', dialect === 'mssql' ? 'nvarchar' : 'char')
}, {
where: { username: 'John' }
});
expect((await this.User.findOne()).username).to.equal('1');
});
it('updates with function and column value', async function() {
await this.User.create({ username: 'John' });
await this.User.update({
username: this.sequelize.fn('upper', this.sequelize.col('username'))
}, {
where: { username: 'John' }
});
expect((await this.User.findOne()).username).to.equal('JOHN');
});
it('does not update virtual attributes', async function() {
const User = this.sequelize.define('User', {
username: Sequelize.STRING,
virtual: Sequelize.VIRTUAL
});
await User.create({ username: 'jan' });
await User.update({
username: 'kurt',
virtual: 'test'
}, {
where: {
username: 'jan'
}
});
const user = await User.findOne();
expect(user.username).to.equal('kurt');
expect(user.virtual).to.not.equal('test');
});
it('doesn\'t update attributes that are altered by virtual setters when option is enabled', async function() {
const User = this.sequelize.define('UserWithVirtualSetters', {
username: Sequelize.STRING,
illness_name: Sequelize.STRING,
illness_pain: Sequelize.INTEGER,
illness: {
type: Sequelize.VIRTUAL,
set(value) {
this.set('illness_name', value.name);
this.set('illness_pain', value.pain);
}
}
});
await User.sync({ force: true });
await User.create({
username: 'Jan',
illness_name: 'Headache',
illness_pain: 5
});
await User.update({
illness: { pain: 10, name: 'Backache' }
}, {
where: {
username: 'Jan'
},
sideEffects: false
});
expect((await User.findOne()).illness_pain).to.be.equal(5);
});
it('updates attributes that are altered by virtual setters', async function() {
const User = this.sequelize.define('UserWithVirtualSetters', {
username: Sequelize.STRING,
illness_name: Sequelize.STRING,
illness_pain: Sequelize.INTEGER,
illness: {
type: Sequelize.VIRTUAL,
set(value) {
this.set('illness_name', value.name);
this.set('illness_pain', value.pain);
}
}
});
await User.sync({ force: true });
await User.create({
username: 'Jan',
illness_name: 'Headache',
illness_pain: 5
});
await User.update({
illness: { pain: 10, name: 'Backache' }
}, {
where: {
username: 'Jan'
}
});
expect((await User.findOne()).illness_pain).to.be.equal(10);
});
it('should properly set data when individualHooks are true', async function() {
this.User.beforeUpdate(instance => {
instance.set('intVal', 1);
});
const user = await this.User.create({ username: 'Peter' });
await this.User.update({ data: 'test' }, {
where: { id: user.id },
individualHooks: true
});
expect((await this.User.findByPk(user.id)).intVal).to.be.equal(1);
});
it('sets updatedAt to the current timestamp', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
let users = await this.User.findAll({ order: ['id'] });
this.updatedAt = users[0].updatedAt;
expect(this.updatedAt).to.be.ok;
expect(this.updatedAt).to.equalTime(users[2].updatedAt); // All users should have the same updatedAt
// Pass the time so we can actually see a change
this.clock.tick(1000);
await this.User.update({ username: 'Bill' }, { where: { secretValue: '42' } });
users = await this.User.findAll({ order: ['id'] });
expect(users[0].username).to.equal('Bill');
expect(users[1].username).to.equal('Bill');
expect(users[2].username).to.equal('Bob');
expect(users[0].updatedAt).to.be.afterTime(this.updatedAt);
expect(users[2].updatedAt).to.equalTime(this.updatedAt);
});
it('returns the number of affected rows', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
let [affectedRows] = await this.User.update({ username: 'Bill' }, { where: { secretValue: '42' } });
expect(affectedRows).to.equal(2);
[affectedRows] = await this.User.update({ username: 'Bill' }, { where: { secretValue: '44' } });
expect(affectedRows).to.equal(0);
});
it('does not update soft deleted records when model is paranoid', async function() {
const ParanoidUser = this.sequelize.define('ParanoidUser', {
username: DataTypes.STRING
}, { paranoid: true });
await this.sequelize.sync({ force: true });
await ParanoidUser.bulkCreate([
{ username: 'user1' },
{ username: 'user2' }
]);
await ParanoidUser.destroy({
where: { username: 'user1' }
});
await ParanoidUser.update({ username: 'foo' }, { where: {} });
const users = await ParanoidUser.findAll({
paranoid: false,
where: {
username: 'foo'
}
});
expect(users).to.have.lengthOf(1, 'should not update soft-deleted record');
});
it('updates soft deleted records when paranoid is overridden', async function() {
const ParanoidUser = this.sequelize.define('ParanoidUser', {
username: DataTypes.STRING
}, { paranoid: true });
await this.sequelize.sync({ force: true });
await ParanoidUser.bulkCreate([
{ username: 'user1' },
{ username: 'user2' }
]);
await ParanoidUser.destroy({ where: { username: 'user1' } });
await ParanoidUser.update({ username: 'foo' }, {
where: {},
paranoid: false
});
const users = await ParanoidUser.findAll({
paranoid: false,
where: {
username: 'foo'
}
});
expect(users).to.have.lengthOf(2);
});
it('calls update hook for soft deleted objects', async function() {
const hookSpy = sinon.spy();
const User = this.sequelize.define('User',
{ username: DataTypes.STRING },
{ paranoid: true, hooks: { beforeUpdate: hookSpy } }
);
await this.sequelize.sync({ force: true });
await User.bulkCreate([{ username: 'user1' }]);
await User.destroy({
where: {
username: 'user1'
}
});
await User.update({ username: 'updUser1' }, {
paranoid: false,
where: { username: 'user1' },
individualHooks: true
});
const user = await User.findOne({ where: { username: 'updUser1' }, paranoid: false });
expect(user).to.not.be.null;
expect(user.username).to.eq('updUser1');
expect(hookSpy).to.have.been.called;
});
if (dialect === 'postgres') {
it('returns the affected rows if `options.returning` is true', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
let [count, rows] = await this.User.update({ username: 'Bill' }, {
where: { secretValue: '42' },
returning: true
});
expect(count).to.equal(2);
expect(rows).to.have.length(2);
[count, rows] = await this.User.update({ username: 'Bill' }, {
where: { secretValue: '44' },
returning: true
});
expect(count).to.equal(0);
expect(rows).to.have.length(0);
});
}
if (dialect === 'mysql') {
it('supports limit clause', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Peter', secretValue: '42' },
{ username: 'Peter', secretValue: '42' }
];
await this.User.bulkCreate(data);
const [affectedRows] = await this.User.update({ secretValue: '43' }, {
where: { username: 'Peter' },
limit: 1
});
expect(affectedRows).to.equal(1);
});
}
});
describe('destroy', () => {
it('`truncate` method should clear the table', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
await User.bulkCreate([{ username: 'user1' }, { username: 'user2' }]);
await User.truncate();
expect(await User.findAll()).to.have.lengthOf(0);
});
it('`truncate` option should clear the table', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
await User.bulkCreate([{ username: 'user1' }, { username: 'user2' }]);
await User.destroy({ truncate: true });
expect(await User.findAll()).to.have.lengthOf(0);
});
it('`truncate` option returns a number', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
await User.bulkCreate([{ username: 'user1' }, { username: 'user2' }]);
const affectedRows = await User.destroy({ truncate: true });
expect(await User.findAll()).to.have.lengthOf(0);
expect(affectedRows).to.be.a('number');
});
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.destroy();
throw new Error('Destroy should throw an error if no where clause is given.');
} catch (err) {
expect(err).to.be.an.instanceof(Error);
expect(err.message).to.equal('Missing where or truncate attribute in the options parameter of model.destroy.');
}
});
it('deletes all instances when given an empty where object', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
await User.bulkCreate([{ username: 'user1' }, { username: 'user2' }]);
const affectedRows = await User.destroy({ where: {} });
expect(affectedRows).to.equal(2);
expect(await User.findAll()).to.have.lengthOf(0);
});
it('throws an error if where has a key with undefined value', async function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING });
await this.sequelize.sync({ force: true });
try {
await User.destroy({ where: { username: undefined } });
throw new Error('Destroy should throw an error if where has a key with undefined value');
} catch (err) {
expect(err).to.be.an.instanceof(Error);
expect(err.message).to.equal('WHERE parameter "username" has invalid "undefined" value');
}
});
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Sequelize.STRING });
await User.sync({ force: true });
await User.create({ username: 'foo' });
const t = await sequelize.transaction();
await User.destroy({
where: {},
transaction: t
});
const count1 = await User.count();
const count2 = await User.count({ transaction: t });
expect(count1).to.equal(1);
expect(count2).to.equal(0);
await t.rollback();
});
}
it('deletes values that match filter', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
await this.User.destroy({ where: { secretValue: '42' } });
const users = await this.User.findAll({ order: ['id'] });
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('Bob');
});
it('works without a primary key', async function() {
const Log = this.sequelize.define('Log', {
client_id: DataTypes.INTEGER,
content: DataTypes.TEXT,
timestamp: DataTypes.DATE
});
Log.removeAttribute('id');
await Log.sync({ force: true });
await Log.create({
client_id: 13,
content: 'Error!',
timestamp: new Date()
});
await Log.destroy({
where: {
client_id: 13
}
});
expect(await Log.findAll()).to.have.lengthOf(0);
});
it('supports .field', async function() {
const UserProject = this.sequelize.define('UserProject', {
userId: {
type: DataTypes.INTEGER,
field: 'user_id'
}
});
await UserProject.sync({ force: true });
await UserProject.create({ userId: 10 });
await UserProject.destroy({ where: { userId: 10 } });
expect(await UserProject.findAll()).to.have.lengthOf(0);
});
it('sets deletedAt to the current timestamp if paranoid is true', async function() {
const ParanoidUser = this.sequelize.define('ParanoidUser', {
username: Sequelize.STRING,
secretValue: Sequelize.STRING,
data: Sequelize.STRING,
intVal: { type: Sequelize.INTEGER, defaultValue: 1 }
}, { paranoid: true });
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await ParanoidUser.sync({ force: true });
await ParanoidUser.bulkCreate(data);
// since we save in UTC, let's format to UTC time
const date = moment().utc().format('YYYY-MM-DD h:mm');
await ParanoidUser.destroy({ where: { secretValue: '42' } });
let users = await ParanoidUser.findAll({ order: ['id'] });
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('Bob');
const queryGenerator = this.sequelize.queryInterface.queryGenerator;
const qi = queryGenerator.quoteIdentifier.bind(queryGenerator);
const query = `SELECT * FROM ${qi('ParanoidUsers')} WHERE ${qi('deletedAt')} IS NOT NULL ORDER BY ${qi('id')}`;
[users] = await this.sequelize.query(query);
expect(users[0].username).to.equal('Peter');
expect(users[1].username).to.equal('Paul');
const formatDate = val => moment(new Date(val)).utc().format('YYYY-MM-DD h:mm');
expect(formatDate(users[0].deletedAt)).to.equal(date);
expect(formatDate(users[1].deletedAt)).to.equal(date);
});
it('does not set deletedAt for previously destroyed instances if paranoid is true', async function() {
const User = this.sequelize.define('UserCol', {
secretValue: Sequelize.STRING,
username: Sequelize.STRING
}, { paranoid: true });
await User.sync({ force: true });
await User.bulkCreate([
{ username: 'Toni', secretValue: '42' },
{ username: 'Tobi', secretValue: '42' },
{ username: 'Max', secretValue: '42' }
]);
const user = await User.findByPk(1);
await user.destroy();
await user.reload({ paranoid: false });
const deletedAt = user.deletedAt;
await User.destroy({ where: { secretValue: '42' } });
await user.reload({ paranoid: false });
expect(user.deletedAt).to.eql(deletedAt);
});
describe("can't find records marked as deleted with paranoid being true", () => {
it('with the DAOFactory', async function() {
const User = this.sequelize.define('UserCol', {
username: Sequelize.STRING
}, { paranoid: true });
await User.sync({ force: true });
await User.bulkCreate([
{ username: 'Toni' },
{ username: 'Tobi' },
{ username: 'Max' }
]);
const user = await User.findByPk(1);
await user.destroy();
expect(await User.findByPk(1)).to.be.null;
expect(await User.count()).to.equal(2);
expect(await User.findAll()).to.have.length(2);
});
});
describe('can find paranoid records if paranoid is marked as false in query', () => {
it('with the DAOFactory', async function() {
const User = this.sequelize.define('UserCol', {
username: Sequelize.STRING
}, { paranoid: true });
await User.sync({ force: true });
await User.bulkCreate([
{ username: 'Toni' },
{ username: 'Tobi' },
{ username: 'Max' }
]);
const user = await User.findByPk(1);
await user.destroy();
expect(await User.findOne({ where: 1, paranoid: false })).to.exist;
expect(await User.findByPk(1)).to.be.null;
expect(await User.count()).to.equal(2);
expect(await User.count({ paranoid: false })).to.equal(3);
});
});
it('should include deleted associated records if include has paranoid marked as false', async function() {
const User = this.sequelize.define('User', {
username: Sequelize.STRING
}, { paranoid: true });
const Pet = this.sequelize.define('Pet', {
name: Sequelize.STRING,
UserId: Sequelize.INTEGER
}, { paranoid: true });
User.hasMany(Pet);
Pet.belongsTo(User);
await User.sync({ force: true });
await Pet.sync({ force: true });
const userId = (await User.create({ username: 'Joe' })).id;
await Pet.bulkCreate([
{ name: 'Fido', UserId: userId },
{ name: 'Fifi', UserId: userId }
]);
const pet = await Pet.findByPk(1);
await pet.destroy();
const user = await User.findOne({
where: { id: userId },
include: Pet
});
const userWithDeletedPets = await User.findOne({
where: { id: userId },
include: { model: Pet, paranoid: false }
});
expect(user).to.exist;
expect(user.Pets).to.have.length(1);
expect(userWithDeletedPets).to.exist;
expect(userWithDeletedPets.Pets).to.have.length(2);
});
it('should delete a paranoid record if I set force to true', async function() {
const User = this.sequelize.define('paranoiduser', {
username: Sequelize.STRING
}, { paranoid: true });
await User.sync({ force: true });
await User.bulkCreate([
{ username: 'Bob' },
{ username: 'Tobi' },
{ username: 'Max' },
{ username: 'Tony' }
]);
const user = await User.findOne({ where: { username: 'Bob' } });
await user.destroy({ force: true });
expect(await User.findOne({ where: { username: 'Bob' } })).to.be.null;
const tobi = await User.findOne({ where: { username: 'Tobi' } });
await tobi.destroy();
let result = await this.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tobi\'', { plain: true });
expect(result.username).to.equal('Tobi');
await User.destroy({ where: { username: 'Tony' } });
result = await this.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tony\'', { plain: true });
expect(result.username).to.equal('Tony');
await User.destroy({ where: { username: ['Tony', 'Max'] }, force: true });
const [users] = await this.sequelize.query('SELECT * FROM paranoidusers', { raw: true });
expect(users).to.have.length(1);
expect(users[0].username).to.equal('Tobi');
});
it('returns the number of affected rows', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
await this.User.bulkCreate(data);
let affectedRows = await this.User.destroy({ where: { secretValue: '42' } });
expect(affectedRows).to.equal(2);
affectedRows = await this.User.destroy({ where: { secretValue: '44' } });
expect(affectedRows).to.equal(0);
});
it('supports table schema/prefix', async function() {
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }
];
const prefixUser = this.User.schema('prefix');
await Support.dropTestSchemas(this.sequelize);
await this.sequelize.queryInterface.createSchema('prefix');
await prefixUser.sync({ force: true });
await prefixUser.bulkCreate(data);
await prefixUser.destroy({ where: { secretValue: '42' } });
const users = await prefixUser.findAll({ order: ['id'] });
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('Bob');
await this.sequelize.queryInterface.dropSchema('prefix');
});
it('should work if model is paranoid and only operator in where clause is a Symbol', async function() {
const User = this.sequelize.define('User', {
username: Sequelize.STRING
}, { paranoid: true });
await User.sync({ force: true });
await User.bulkCreate([{ username: 'foo' }, { username: 'bar' }]);
await User.destroy({
where: {
[Op.or]: [
{ username: 'bar' },
{ username: 'baz' }
]
}
});
const users = await User.findAll();
expect(users).to.have.length(1);
expect(users[0].username).to.equal('foo');
});
});
describe('restore', () => {
it('rejects with an error if the model is not paranoid', async function() {
await expect(this.User.restore({ where: { secretValue: '42' } })).to.be.rejectedWith(Error, 'Model is not paranoid');
});
it('restores a previously deleted model', async function() {
const ParanoidUser = this.sequelize.define('ParanoidUser', {
username: Sequelize.STRING,
secretValue: Sequelize.STRING,
data: Sequelize.STRING,
intVal: { type: Sequelize.INTEGER, defaultValue: 1 }
}, {
paranoid: true
});
const data = [
{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }
];
await ParanoidUser.sync({ force: true });
await ParanoidUser.bulkCreate(data);
await ParanoidUser.destroy({ where: { secretValue: '42' } });
await ParanoidUser.restore({ where: { secretValue: '42' } });
const user = await ParanoidUser.findOne({ where: { secretValue: '42' } });
expect(user).to.be.ok;
expect(user.username).to.equal('Peter');
});
});
describe('equals', () => {
it('correctly determines equality of objects', async function() {
const user = await this.User.create({ username: 'hallo', data: 'welt' });
expect(user.equals(user)).to.be.ok;
});
// sqlite can't handle multiple primary keys
if (dialect !== 'sqlite') {
it('correctly determines equality with multiple primary keys', async function() {
const userKeys = this.sequelize.define('userkeys', {
foo: { type: Sequelize.STRING, primaryKey: true },
bar: { type: Sequelize.STRING, primaryKey: true },
name: Sequelize.STRING,
bio: Sequelize.TEXT
});
await userKeys.sync({ force: true });
const user = await userKeys.create({ foo: '1', bar: '2', name: 'hallo', bio: 'welt' });
expect(user.equals(user)).to.be.ok;
});
}
});
// sqlite can't handle multiple primary keys
if (dialect !== 'sqlite') {
describe('equalsOneOf', () => {
beforeEach(async function() {
this.userKey = this.sequelize.define('userKeys', {
foo: { type: Sequelize.STRING, primaryKey: true },
bar: { type: Sequelize.STRING, primaryKey: true },
name: Sequelize.STRING,
bio: Sequelize.TEXT
});
await this.userKey.sync({ force: true });
});
it('determines equality if one is matching', async function() {
const u = await this.userKey.create({ foo: '1', bar: '2', name: 'hallo', bio: 'welt' });
expect(u.equalsOneOf([u, { a: 1 }])).to.be.ok;
});
it("doesn't determine equality if none is matching", async function() {
const u = await this.userKey.create({ foo: '1', bar: '2', name: 'hallo', bio: 'welt' });
expect(u.equalsOneOf([{ b: 2 }, { a: 1 }])).to.not.be.ok;
});
});
}
describe('count', () => {
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Sequelize.STRING });
await User.sync({ force: true });
const t = await sequelize.transaction();
await User.create({ username: 'foo' }, { transaction: t });
const count1 = await User.count();
const count2 = await User.count({ transaction: t });
expect(count1).to.equal(0);
expect(count2).to.equal(1);
await t.rollback();
});
}
it('counts all created objects', async function() {
await this.User.bulkCreate([{ username: 'user1' }, { username: 'user2' }]);
expect(await this.User.count()).to.equal(2);
});
it('returns multiple rows when using group', async function() {
await this.User.bulkCreate([
{ username: 'user1', data: 'A' },
{ username: 'user2', data: 'A' },
{ username: 'user3', data: 'B' }
]);
const count = await this.User.count({
attributes: ['data'],
group: ['data']
});
expect(count).to.have.lengthOf(2);
});
if (dialect !== 'mssql') {
describe('aggregate', () => {
it('allows grouping by aliased attribute', async function() {
await this.User.aggregate('id', 'count', {
attributes: [['id', 'id2']],
group: ['id2'],
logging: true
});
});
});
}
describe('options sent to aggregate', () => {
let options, aggregateSpy;
beforeEach(function() {
options = { where: { username: 'user1' } };
aggregateSpy = sinon.spy(this.User, 'aggregate');
});
afterEach(() => {
expect(aggregateSpy).to.have.been.calledWith(
sinon.match.any, sinon.match.any,
sinon.match.object.and(sinon.match.has('where', { username: 'user1' }))
);
aggregateSpy.restore();
});
it('modifies option "limit" by setting it to null', async function() {
options.limit = 5;
await this.User.count(options);
expect(aggregateSpy).to.have.been.calledWith(
sinon.match.any, sinon.match.any,
sinon.match.object.and(sinon.match.has('limit', null))
);
});
it('modifies option "offset" by setting it to null', async function() {
options.offset = 10;
await this.User.count(options);
expect(aggregateSpy).to.have.been.calledWith(
sinon.match.any, sinon.match.any,
sinon.match.object.and(sinon.match.has('offset', null))
);
});
it('modifies option "order" by setting it to null', async function() {
options.order = 'username';
await this.User.count(options);
expect(aggregateSpy).to.have.been.calledWith(
sinon.match.any, sinon.match.any,
sinon.match.object.and(sinon.match.has('order', null))
);
});
});
it('allows sql logging', async function() {
let test = false;
await this.User.count({
logging(sql) {
test = true;
expect(sql).to.exist;
expect(sql.toUpperCase()).to.include('SELECT');
}
});
expect(test).to.be.true;
});
it('filters object', async function() {
await this.User.create({ username: 'user1' });
await this.User.create({ username: 'foo' });
const count = await this.User.count({ where: { username: { [Op.like]: '%us%' } } });
expect(count).to.equal(1);
});
it('supports distinct option', async function() {
const Post = this.sequelize.define('Post', {});
const PostComment = this.sequelize.define('PostComment', {});
Post.hasMany(PostComment);
await Post.sync({ force: true });
await PostComment.sync({ force: true });
const post = await Post.create({});
await PostComment.bulkCreate([{ PostId: post.id }, { PostId: post.id }]);
const count1 = await Post.count({ distinct: false, include: { model: PostComment, required: false } });
const count2 = await Post.count({ distinct: true, include: { model: PostComment, required: false } });
expect(count1).to.equal(2);
expect(count2).to.equal(1);
});
});
for (const methodName of ['min', 'max']) {
describe(methodName, () => {
beforeEach(async function() {
this.UserWithAge = this.sequelize.define('UserWithAge', {
age: Sequelize.INTEGER,
order: Sequelize.INTEGER
});
this.UserWithDec = this.sequelize.define('UserWithDec', {
value: Sequelize.DECIMAL(10, 3)
});
await this.UserWithAge.sync({ force: true });
await this.UserWithDec.sync({ force: true });
});
if (current.dialect.supports.transactions) {
it('supports transactions', async function() {
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { age: Sequelize.INTEGER });
await User.sync({ force: true });
const t = await sequelize.transaction();
await User.bulkCreate([{ age: 2 }, { age: 5 }, { age: 3 }], { transaction: t });
const val1 = await User[methodName]('age');
const val2 = await User[methodName]('age', { transaction: t });
expect(val1).to.be.not.ok;
expect(val2).to.equal(methodName === 'min' ? 2 : 5);
await t.rollback();
});
}
it('returns the correct value', async function() {
await this.UserWithAge.bulkCreate([{ age: 3 }, { age: 2 }]);
expect(await this.UserWithAge[methodName]('age')).to.equal(methodName === 'min' ? 2 : 3);
});
it('allows sql logging', async function() {
let test = false;
await this.UserWithAge[methodName]('age', {
logging(sql) {
test = true;
expect(sql).to.exist;
expect(sql.toUpperCase()).to.include('SELECT');
}
});
expect(test).to.be.true;
});
it('should allow decimals', async function() {
await this.UserWithDec.bulkCreate([{ value: 5.5 }, { value: 3.5 }]);
expect(await this.UserWithDec[methodName]('value')).to.equal(methodName === 'min' ? 3.5 : 5.5);
});
it('should allow strings', async function() {
await this.User.bulkCreate([{ username: 'bbb' }, { username: 'yyy' }]);
expect(await this.User[methodName]('username')).to.equal(methodName === 'min' ? 'bbb' : 'yyy');
});
it('should allow dates', async function() {
const date1 = new Date(2000, 1, 1);
const date2 = new Date(1990, 1, 1);
await this.User.bulkCreate([{ theDate: date1 }, { theDate: date2 }]);
expect(await this.User[methodName]('theDate')).to.equalDate(methodName === 'min' ? date2 : date1);
});
it('should work with fields named as an SQL reserved keyword', async function() {
await this.UserWithAge.bulkCreate([
{ age: 2, order: 3 },
{ age: 3, order: 5 }
]);
expect(await this.UserWithAge[methodName]('order')).to.equal(methodName === 'min' ? 3 : 5);
});
});
}
describe('sum', () => {
beforeEach(async function() {
this.UserWithAge = this.sequelize.define('UserWithAge', {
age: Sequelize.INTEGER,
order: Sequelize.INTEGER,
gender: Sequelize.ENUM('male', 'female')
});
this.UserWithDec = this.sequelize.define('UserWithDec', {
value: Sequelize.DECIMAL(10, 3)
});
this.UserWithFields = this.sequelize.define('UserWithFields', {
age: {
type: Sequelize.INTEGER,
field: 'user_age'
},
order: Sequelize.INTEGER,
gender: {
type: Sequelize.ENUM('male', 'female'),
field: 'male_female'
}
});
await Promise.all([
this.UserWithAge.sync({ force: true }),
this.UserWithDec.sync({ force: true }),
this.UserWithFields.sync({ force: true })
]);
});
it('should work in the simplest case', async function() {
await this.UserWithAge.bulkCreate([{ age: 2 }, { age: 3 }]);
expect(await this.UserWithAge.sum('age')).to.equal(5);
});
it('should work with fields named as an SQL reserved keyword', async function() {
await this.UserWithAge.bulkCreate([{ age: 2, order: 3 }, { age: 3, order: 5 }]);
expect(await this.UserWithAge.sum('order')).to.equal(8);
});
it('should allow decimals in sum', async function() {
await this.UserWithDec.bulkCreate([{ value: 3.5 }, { value: 5.25 }]);
expect(await this.UserWithDec.sum('value')).to.equal(8.75);
});
it('should accept a where clause', async function() {
const options = { where: { gender: 'male' } };
await this.UserWithAge.bulkCreate([
{ age: 2, gender: 'male' },
{ age: 3, gender: 'female' }
]);
expect(await this.UserWithAge.sum('age', options)).to.equal(2);
});
it('should accept a where clause with custom fields', async function() {
const options = { where: { gender: 'male' } };
await this.UserWithFields.bulkCreate([
{ age: 2, gender: 'male' },
{ age: 3, gender: 'female' }
]);
expect(await this.UserWithFields.sum('age', options)).to.equal(2);
});
it('allows sql logging', async function() {
let test = false;
await this.UserWithAge.sum('age', {
logging(sql) {
test = true;
expect(sql).to.exist;
expect(sql.toUpperCase()).to.include('SELECT');
}
});
expect(test).to.true;
});
});
describe('schematic support', () => {
beforeEach(async function() {
this.UserPublic = this.sequelize.define('UserPublic', {
age: Sequelize.INTEGER
});
this.UserSpecial = this.sequelize.define('UserSpecial', {
age: Sequelize.INTEGER
});
await Support.dropTestSchemas(this.sequelize);
await this.sequelize.createSchema('schema_test');
await this.sequelize.createSchema('special');
this.UserSpecialSync = await this.UserSpecial.schema('special').sync({ force: true });
});
afterEach(async function() {
try {
await this.sequelize.dropSchema('schema_test');
} finally {
await this.sequelize.dropSchema('special');
await this.sequelize.dropSchema('prefix');
}
});
it('should be able to drop with schemas', async function() {
await this.UserSpecial.drop();
});
it('should be able to list schemas', async function() {
const schemas = await this.sequelize.showAllSchemas();
expect(schemas).to.be.instanceof(Array);
const expectedLengths = {
mssql: 2,
postgres: 2,
mariadb: 3,
mysql: 1,
sqlite: 1
};
expect(schemas).to.have.length(expectedLengths[dialect]);
});
if (['mysql', 'sqlite'].includes(dialect)) {
it('should take schemaDelimiter into account if applicable', async function() {
let test = 0;
const UserSpecialUnderscore = this.sequelize.define('UserSpecialUnderscore', {
age: Sequelize.INTEGER
}, { schema: 'hello', schemaDelimiter: '_' });
const UserSpecialDblUnderscore = this.sequelize.define('UserSpecialDblUnderscore', {
age: Sequelize.INTEGER
});
const User = await UserSpecialUnderscore.sync({ force: true });
const DblUser = await UserSpecialDblUnderscore.schema('hello', '__').sync({ force: true });
await DblUser.create({ age: 3 }, {
logging(sql) {
test++;
expect(sql).to.exist;
expect(sql).to.include('INSERT INTO `hello__UserSpecialDblUnderscores`');
}
});
await User.create({ age: 3 }, {
logging(sql) {
test++;
expect(sql).to.exist;
expect(sql).to.include('INSERT INTO `hello_UserSpecialUnderscores`');
}
});
expect(test).to.equal(2);
});
}
it('should describeTable using the default schema settings', async function() {
const UserPublic = this.sequelize.define('Public', {
username: Sequelize.STRING
});
let test = 0;
await UserPublic.sync({ force: true });
await UserPublic.schema('special').sync({ force: true });
let table = await this.sequelize.queryInterface.describeTable('Publics', {
logging(sql) {
if (dialect === 'sqlite' && sql.includes('TABLE_INFO')) {
test++;
expect(sql).to.not.contain('special');
}
else if (['mysql', 'mssql', 'mariadb'].includes(dialect)) {
test++;
expect(sql).to.not.contain('special');
}
}
});
if (dialect === 'postgres') {
test++;
expect(table.id.defaultValue).to.not.contain('special');
}
table = await this.sequelize.queryInterface.describeTable('Publics', {
schema: 'special',
logging(sql) {
if (dialect === 'sqlite' && sql.includes('TABLE_INFO')) {
test++;
expect(sql).to.contain('special');
}
else if (['mysql', 'mssql', 'mariadb'].includes(dialect)) {
test++;
expect(sql).to.contain('special');
}
}
});
if (dialect === 'postgres') {
test++;
expect(table.id.defaultValue).to.contain('special');
}
expect(test).to.equal(2);
});
it('should be able to reference a table with a schema set', async function() {
const UserPub = this.sequelize.define('UserPub', {
username: Sequelize.STRING
}, { schema: 'prefix' });
const ItemPub = this.sequelize.define('ItemPub', {
name: Sequelize.STRING
}, { schema: 'prefix' });
UserPub.hasMany(ItemPub, { foreignKeyConstraint: true });
if (['postgres', 'mssql', 'mariadb'].includes(dialect)) {
await Support.dropTestSchemas(this.sequelize);
await this.sequelize.queryInterface.createSchema('prefix');
}
let test = false;
await UserPub.sync({ force: true });
await ItemPub.sync({
force: true,
logging: _.after(2, _.once(sql => {
test = true;
if (dialect === 'postgres') {
expect(sql).to.match(/REFERENCES\s+"prefix"\."UserPubs" \("id"\)/);
} else if (dialect === 'mssql') {
expect(sql).to.match(/REFERENCES\s+\[prefix\]\.\[UserPubs\] \(\[id\]\)/);
} else if (dialect === 'mariadb') {
expect(sql).to.match(/REFERENCES\s+`prefix`\.`UserPubs` \(`id`\)/);
} else {
expect(sql).to.match(/REFERENCES\s+`prefix\.UserPubs` \(`id`\)/);
}
}))
});
expect(test).to.be.true;
});
it('should be able to create and update records under any valid schematic', async function() {
let logged = 0;
const UserPublicSync = await this.UserPublic.sync({ force: true });
await UserPublicSync.create({ age: 3 }, {
logging: UserPublic => {
logged++;
if (dialect === 'postgres') {
expect(this.UserSpecialSync.getTableName().toString()).to.equal('"special"."UserSpecials"');
expect(UserPublic).to.include('INSERT INTO "UserPublics"');
} else if (dialect === 'sqlite') {
expect(this.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`');
expect(UserPublic).to.include('INSERT INTO `UserPublics`');
} else if (dialect === 'mssql') {
expect(this.UserSpecialSync.getTableName().toString()).to.equal('[special].[UserSpecials]');
expect(UserPublic).to.include('INSERT INTO [UserPublics]');
} else if (dialect === 'mariadb') {
expect(this.UserSpecialSync.getTableName().toString()).to.equal('`special`.`UserSpecials`');
expect(UserPublic.indexOf('INSERT INTO `UserPublics`')).to.be.above(-1);
} else {
expect(this.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`');
expect(UserPublic).to.include('INSERT INTO `UserPublics`');
}
}
});
const UserSpecial = await this.UserSpecialSync.schema('special').create({ age: 3 }, {
logging(UserSpecial) {
logged++;
if (dialect === 'postgres') {
expect(UserSpecial).to.include('INSERT INTO "special"."UserSpecials"');
} else if (dialect === 'sqlite') {
expect(UserSpecial).to.include('INSERT INTO `special.UserSpecials`');
} else if (dialect === 'mssql') {
expect(UserSpecial).to.include('INSERT INTO [special].[UserSpecials]');
} else if (dialect === 'mariadb') {
expect(UserSpecial).to.include('INSERT INTO `special`.`UserSpecials`');
} else {
expect(UserSpecial).to.include('INSERT INTO `special.UserSpecials`');
}
}
});
await UserSpecial.update({ age: 5 }, {
logging(user) {
logged++;
if (dialect === 'postgres') {
expect(user).to.include('UPDATE "special"."UserSpecials"');
} else if (dialect === 'mssql') {
expect(user).to.include('UPDATE [special].[UserSpecials]');
} else if (dialect === 'mariadb') {
expect(user).to.include('UPDATE `special`.`UserSpecials`');
} else {
expect(user).to.include('UPDATE `special.UserSpecials`');
}
}
});
expect(logged).to.equal(3);
});
});
describe('references', () => {
beforeEach(async function() {
this.Author = this.sequelize.define('author', { firstName: Sequelize.STRING });
await this.sequelize.getQueryInterface().dropTable('posts', { force: true });
await this.sequelize.getQueryInterface().dropTable('authors', { force: true });
await this.Author.sync();
});
it('uses an existing dao factory and references the author table', async function() {
const authorIdColumn = { type: Sequelize.INTEGER, references: { model: this.Author, key: 'id' } };
const Post = this.sequelize.define('post', {
title: Sequelize.STRING,
authorId: authorIdColumn
});
this.Author.hasMany(Post);
Post.belongsTo(this.Author);
// The posts table gets dropped in the before filter.
await Post.sync({ logging: _.once(sql => {
if (dialect === 'postgres') {
expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/);
} else if (dialect === 'mysql' || dialect === 'mariadb') {
expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/);
} else if (dialect === 'mssql') {
expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/);
} else if (dialect === 'sqlite') {
expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/);
} else {
throw new Error('Undefined dialect!');
}
}) });
});
it('uses a table name as a string and references the author table', async function() {
const authorIdColumn = { type: Sequelize.INTEGER, references: { model: 'authors', key: 'id' } };
const Post = this.sequelize.define('post', { title: Sequelize.STRING, authorId: authorIdColumn });
this.Author.hasMany(Post);
Post.belongsTo(this.Author);
// The posts table gets dropped in the before filter.
await Post.sync({ logging: _.once(sql => {
if (dialect === 'postgres') {
expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/);
} else if (dialect === 'mysql' || dialect === 'mariadb') {
expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/);
} else if (dialect === 'sqlite') {
expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/);
} else if (dialect === 'mssql') {
expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/);
} else {
throw new Error('Undefined dialect!');
}
}) });
});
it('emits an error event as the referenced table name is invalid', async function() {
const authorIdColumn = { type: Sequelize.INTEGER, references: { model: '4uth0r5', key: 'id' } };
const Post = this.sequelize.define('post', { title: Sequelize.STRING, authorId: authorIdColumn });
this.Author.hasMany(Post);
Post.belongsTo(this.Author);
try {
// The posts table gets dropped in the before filter.
await Post.sync();
if (dialect === 'sqlite') {
// sorry ... but sqlite is too stupid to understand whats going on ...
expect(1).to.equal(1);
} else {
// the parser should not end up here ...
expect(2).to.equal(1);
}
} catch (err) {
if (dialect === 'mysql') {
// MySQL 5.7 or above doesn't support POINT EMPTY
if (semver.gte(current.options.databaseVersion, '5.6.0')) {
expect(err.message).to.match(/Cannot add foreign key constraint/);
} else {
expect(err.message).to.match(/Can't create table/);
}
} else if (dialect === 'sqlite') {
// the parser should not end up here ... see above
expect(1).to.equal(2);
} else if (dialect === 'mariadb') {
expect(err.message).to.match(/Foreign key constraint is incorrectly formed/);
} else if (dialect === 'postgres') {
expect(err.message).to.match(/relation "4uth0r5" does not exist/);
} else if (dialect === 'mssql') {
expect(err.message).to.match(/Could not create constraint/);
} else {
throw new Error('Undefined dialect!');
}
}
});
it('works with comments', async function() {
// Test for a case where the comment was being moved to the end of the table when there was also a reference on the column, see #1521
const Member = this.sequelize.define('Member', {});
const idColumn = {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: false,
comment: 'asdf'
};
idColumn.references = { model: Member, key: 'id' };
this.sequelize.define('Profile', { id: idColumn });
await this.sequelize.sync({ force: true });
});
});
describe('blob', () => {
beforeEach(async function() {
this.BlobUser = this.sequelize.define('blobUser', {
data: Sequelize.BLOB
});
await this.BlobUser.sync({ force: true });
});
describe('buffers', () => {
it('should be able to take a buffer as parameter to a BLOB field', async function() {
const user = await this.BlobUser.create({
data: Buffer.from('Sequelize')
});
expect(user).to.be.ok;
});
it('should return a buffer when fetching a blob', async function() {
const user = await this.BlobUser.create({
data: Buffer.from('Sequelize')
});
const user0 = await this.BlobUser.findByPk(user.id);
expect(user0.data).to.be.an.instanceOf(Buffer);
expect(user0.data.toString()).to.have.string('Sequelize');
});
it('should work when the database returns null', async function() {
const user = await this.BlobUser.create({
// create a null column
});
const user0 = await this.BlobUser.findByPk(user.id);
expect(user0.data).to.be.null;
});
});
if (dialect !== 'mssql') {
// NOTE: someone remember to inform me about the intent of these tests. Are
// you saying that data passed in as a string is automatically converted
// to binary? i.e. "Sequelize" is CAST as binary, OR that actual binary
// data is passed in, in string form? Very unclear, and very different.
describe('strings', () => {
it('should be able to take a string as parameter to a BLOB field', async function() {
const user = await this.BlobUser.create({
data: 'Sequelize'
});
expect(user).to.be.ok;
});
it('should return a buffer when fetching a BLOB, even when the BLOB was inserted as a string', async function() {
const user = await this.BlobUser.create({
data: 'Sequelize'
});
const user0 = await this.BlobUser.findByPk(user.id);
expect(user0.data).to.be.an.instanceOf(Buffer);
expect(user0.data.toString()).to.have.string('Sequelize');
});
});
}
});
describe('paranoid is true and where is an array', () => {
beforeEach(async function() {
this.User = this.sequelize.define('User', { username: DataTypes.STRING }, { paranoid: true });
this.Project = this.sequelize.define('Project', { title: DataTypes.STRING }, { paranoid: true });
this.Project.belongsToMany(this.User, { through: 'project_user' });
this.User.belongsToMany(this.Project, { through: 'project_user' });
await this.sequelize.sync({ force: true });
await this.User.bulkCreate([{
username: 'leia'
}, {
username: 'luke'
}, {
username: 'vader'
}]);
await this.Project.bulkCreate([{
title: 'republic'
}, {
title: 'empire'
}]);
const users = await this.User.findAll();
const projects = await this.Project.findAll();
const leia = users[0],
luke = users[1],
vader = users[2],
republic = projects[0],
empire = projects[1];
await leia.setProjects([republic]);
await luke.setProjects([republic]);
await vader.setProjects([empire]);
await leia.destroy();
});
it('should not fail when array contains Sequelize.or / and', async function() {
const res = await this.User.findAll({
where: [
this.sequelize.or({ username: 'vader' }, { username: 'luke' }),
this.sequelize.and({ id: [1, 2, 3] })
]
});
expect(res).to.have.length(2);
});
it('should fail when array contains strings', async function() {
await expect(this.User.findAll({
where: ['this is a mistake', ['dont do it!']]
})).to.eventually.be.rejectedWith(Error, 'Support for literal replacements in the `where` object has been removed.');
});
it('should not fail with an include', async function() {
const users = await this.User.findAll({
where: this.sequelize.literal(`${this.sequelize.queryInterface.queryGenerator.quoteIdentifiers('Projects.title')} = ${this.sequelize.queryInterface.queryGenerator.escape('republic')}`),
include: [
{ model: this.Project }
]
});
expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('luke');
});
it('should not overwrite a specified deletedAt by setting paranoid: false', async function() {
let tableName = '';
if (this.User.name) {
tableName = `${this.sequelize.queryInterface.queryGenerator.quoteIdentifier(this.User.name)}.`;
}
const users = await this.User.findAll({
paranoid: false,
where: this.sequelize.literal(`${tableName + this.sequelize.queryInterface.queryGenerator.quoteIdentifier('deletedAt')} IS NOT NULL `),
include: [
{ model: this.Project }
]
});
expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('leia');
});
it('should not overwrite a specified deletedAt (complex query) by setting paranoid: false', async function() {
const res = await this.User.findAll({
paranoid: false,
where: [
this.sequelize.or({ username: 'leia' }, { username: 'luke' }),
this.sequelize.and(
{ id: [1, 2, 3] },
this.sequelize.or({ deletedAt: null }, { deletedAt: { [Op.gt]: new Date(0) } })
)
]
});
expect(res).to.have.length(2);
});
});
if (dialect !== 'sqlite' && current.dialect.supports.transactions) {
it('supports multiple async transactions', async function() {
this.timeout(90000);
const sequelize = await Support.prepareTransactionTest(this.sequelize);
const User = sequelize.define('User', { username: Sequelize.STRING });
const testAsync = async function() {
const t0 = await sequelize.transaction();
await User.create({
username: 'foo'
}, {
transaction: t0
});
const users0 = await User.findAll({
where: {
username: 'foo'
}
});
expect(users0).to.have.length(0);
const users = await User.findAll({
where: {
username: 'foo'
},
transaction: t0
});
expect(users).to.have.length(1);
const t = t0;
return t.rollback();
};
await User.sync({ force: true });
const tasks = [];
for (let i = 0; i < 1000; i++) {
tasks.push(testAsync);
}
await pMap(tasks, entry => {
return entry();
}, {
// Needs to be one less than ??? else the non transaction query won't ever get a connection
concurrency: (sequelize.config.pool && sequelize.config.pool.max || 5) - 1
});
});
}
describe('Unique', () => {
it('should set unique when unique is true', async function() {
const uniqueTrue = this.sequelize.define('uniqueTrue', {
str: { type: Sequelize.STRING, unique: true }
});
await uniqueTrue.sync({ force: true, logging: _.after(2, _.once(s => {
expect(s).to.match(/UNIQUE/);
})) });
});
it('should not set unique when unique is false', async function() {
const uniqueFalse = this.sequelize.define('uniqueFalse', {
str: { type: Sequelize.STRING, unique: false }
});
await uniqueFalse.sync({ force: true, logging: _.after(2, _.once(s => {
expect(s).not.to.match(/UNIQUE/);
})) });
});
it('should not set unique when unique is unset', async function() {
const uniqueUnset = this.sequelize.define('uniqueUnset', {
str: { type: Sequelize.STRING }
});
await uniqueUnset.sync({ force: true, logging: _.after(2, _.once(s => {
expect(s).not.to.match(/UNIQUE/);
})) });
});
});
it('should be possible to use a key named UUID as foreign key', async function() {
this.sequelize.define('project', {
UserId: {
type: Sequelize.STRING,
references: {
model: 'Users',
key: 'UUID'
}
}
});
this.sequelize.define('Users', {
UUID: {
type: Sequelize.STRING,
primaryKey: true,
unique: true,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
}
});
await this.sequelize.sync({ force: true });
});
describe('bulkCreate', () => {
it('errors - should return array of errors if validate and individualHooks are true', async function() {
const data = [{ username: null },
{ username: null },
{ username: null }];
const user = this.sequelize.define('User', {
username: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
}
});
await this.sequelize.sync({ force: true });
expect(user.bulkCreate(data, {
validate: true,
individualHooks: true
})).to.be.rejectedWith(errors.AggregateError);
});
it('should not use setter when renaming fields in dataValues', async function() {
const user = this.sequelize.define('User', {
username: {
type: Sequelize.STRING,
allowNull: false,
field: 'data',
get() {
const val = this.getDataValue('username');
return val.substring(0, val.length - 1);
},
set(val) {
if (val.includes('!')) {
throw new Error('val should not include a "!"');
}
this.setDataValue('username', `${val}!`);
}
}
});
const data = [{ username: 'jon' }];
await this.sequelize.sync({ force: true });
await user.bulkCreate(data);
const users1 = await user.findAll();
expect(users1[0].username).to.equal('jon');
});
});
});