model.d.ts
85.3 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
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
import { IndexHints } from '..';
import { Association, BelongsTo, BelongsToMany, BelongsToManyOptions, BelongsToOptions, HasMany, HasManyOptions, HasOne, HasOneOptions } from './associations/index';
import { DataType } from './data-types';
import { Deferrable } from './deferrable';
import { HookReturn, Hooks, ModelHooks } from './hooks';
import { ValidationOptions } from './instance-validator';
import { QueryOptions, IndexesOptions } from './query-interface';
import { Sequelize, SyncOptions } from './sequelize';
import { Transaction, LOCK } from './transaction';
import { Col, Fn, Literal, Where } from './utils';
import Op = require('./operators');
export interface Logging {
/**
* A function that gets executed while running the query to log the sql.
*/
logging?: boolean | ((sql: string, timing?: number) => void);
/**
* Pass query execution time in milliseconds as second argument to logging function (options.logging).
*/
benchmark?: boolean;
}
export interface Poolable {
/**
* Force the query to use the write pool, regardless of the query type.
*
* @default false
*/
useMaster?: boolean;
}
export interface Transactionable {
/**
* Transaction to run query under
*/
transaction?: Transaction;
}
export interface SearchPathable {
/**
* An optional parameter to specify the schema search_path (Postgres only)
*/
searchPath?: string;
}
export interface Filterable<TAttributes = any> {
/**
* Attribute has to be matched for rows to be selected for the given action.
*/
where?: WhereOptions<TAttributes>;
}
export interface Projectable {
/**
* A list of the attributes that you want to select. To rename an attribute, you can pass an array, with
* two elements - the first is the name of the attribute in the DB (or some kind of expression such as
* `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to
* have in the returned instance
*/
attributes?: FindAttributeOptions;
}
export interface Paranoid {
/**
* If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
* be returned. Only applies if `options.paranoid` is true for the model.
*/
paranoid?: boolean;
}
export type GroupOption = string | Fn | Col | (string | Fn | Col)[];
/**
* Options to pass to Model on drop
*/
export interface DropOptions extends Logging {
/**
* Also drop all objects depending on this table, such as views. Only works in postgres
*/
cascade?: boolean;
}
/**
* Schema Options provided for applying a schema to a model
*/
export interface SchemaOptions extends Logging {
/**
* The character(s) that separates the schema name from the table name
*/
schemaDelimiter?: string;
}
/**
* Scope Options for Model.scope
*/
export interface ScopeOptions {
/**
* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
* To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function,
* pass an object, with a `method` property. The value can either be a string, if the method does not take
* any arguments, or an array, where the first element is the name of the method, and consecutive elements
* are arguments to that method. Pass null to remove all scopes, including the default.
*/
method: string | [string, ...unknown[]];
}
/**
* The type accepted by every `where` option
*/
export type WhereOptions<TAttributes = any> =
| WhereAttributeHash<TAttributes>
| AndOperator<TAttributes>
| OrOperator<TAttributes>
| Literal
| Fn
| Where;
/**
* Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
*
* _PG only_
*/
export interface AnyOperator {
[Op.any]: (string | number)[];
}
/** Undocumented? */
export interface AllOperator {
[Op.all]: (string | number | Date | Literal)[];
}
export type Rangable = [number, number] | [Date, Date] | Literal;
/**
* Operators that can be used in WhereOptions
*
* See https://sequelize.org/master/en/v3/docs/querying/#operators
*/
export interface WhereOperators {
/**
* Example: `[Op.any]: [2,3]` becomes `ANY ARRAY[2, 3]::INTEGER`
*
* _PG only_
*/
[Op.any]?: (string | number | Literal)[] | Literal;
/** Example: `[Op.gte]: 6,` becomes `>= 6` */
[Op.gte]?: number | string | Date | Literal;
/** Example: `[Op.lt]: 10,` becomes `< 10` */
[Op.lt]?: number | string | Date | Literal;
/** Example: `[Op.lte]: 10,` becomes `<= 10` */
[Op.lte]?: number | string | Date | Literal;
/** Example: `[Op.ne]: 20,` becomes `!= 20` */
[Op.ne]?: null | string | number | Literal | WhereOperators;
/** Example: `[Op.not]: true,` becomes `IS NOT TRUE` */
[Op.not]?: null | boolean | string | number | Literal | WhereOperators;
/** Example: `[Op.between]: [6, 10],` becomes `BETWEEN 6 AND 10` */
[Op.between]?: Rangable;
/** Example: `[Op.in]: [1, 2],` becomes `IN [1, 2]` */
[Op.in]?: (string | number | Literal)[] | Literal;
/** Example: `[Op.notIn]: [1, 2],` becomes `NOT IN [1, 2]` */
[Op.notIn]?: (string | number | Literal)[] | Literal;
/**
* Examples:
* - `[Op.like]: '%hat',` becomes `LIKE '%hat'`
* - `[Op.like]: { [Op.any]: ['cat', 'hat']}` becomes `LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.like]?: string | Literal | AnyOperator | AllOperator;
/**
* Examples:
* - `[Op.notLike]: '%hat'` becomes `NOT LIKE '%hat'`
* - `[Op.notLike]: { [Op.any]: ['cat', 'hat']}` becomes `NOT LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.notLike]?: string | Literal | AnyOperator | AllOperator;
/**
* case insensitive PG only
*
* Examples:
* - `[Op.iLike]: '%hat'` becomes `ILIKE '%hat'`
* - `[Op.iLike]: { [Op.any]: ['cat', 'hat']}` becomes `ILIKE ANY ARRAY['cat', 'hat']`
*/
[Op.iLike]?: string | Literal | AnyOperator | AllOperator;
/**
* PG array overlap operator
*
* Example: `[Op.overlap]: [1, 2]` becomes `&& [1, 2]`
*/
[Op.overlap]?: Rangable;
/**
* PG array contains operator
*
* Example: `[Op.contains]: [1, 2]` becomes `@> [1, 2]`
*/
[Op.contains]?: (string | number)[] | Rangable;
/**
* PG array contained by operator
*
* Example: `[Op.contained]: [1, 2]` becomes `<@ [1, 2]`
*/
[Op.contained]?: (string | number)[] | Rangable;
/** Example: `[Op.gt]: 6,` becomes `> 6` */
[Op.gt]?: number | string | Date | Literal;
/**
* PG only
*
* Examples:
* - `[Op.notILike]: '%hat'` becomes `NOT ILIKE '%hat'`
* - `[Op.notLike]: ['cat', 'hat']` becomes `LIKE ANY ARRAY['cat', 'hat']`
*/
[Op.notILike]?: string | Literal | AnyOperator | AllOperator;
/** Example: `[Op.notBetween]: [11, 15],` becomes `NOT BETWEEN 11 AND 15` */
[Op.notBetween]?: Rangable;
/**
* Strings starts with value.
*/
[Op.startsWith]?: string;
/**
* String ends with value.
*/
[Op.endsWith]?: string;
/**
* String contains value.
*/
[Op.substring]?: string;
/**
* MySQL/PG only
*
* Matches regular expression, case sensitive
*
* Example: `[Op.regexp]: '^[h|a|t]'` becomes `REGEXP/~ '^[h|a|t]'`
*/
[Op.regexp]?: string;
/**
* MySQL/PG only
*
* Does not match regular expression, case sensitive
*
* Example: `[Op.notRegexp]: '^[h|a|t]'` becomes `NOT REGEXP/!~ '^[h|a|t]'`
*/
[Op.notRegexp]?: string;
/**
* PG only
*
* Matches regular expression, case insensitive
*
* Example: `[Op.iRegexp]: '^[h|a|t]'` becomes `~* '^[h|a|t]'`
*/
[Op.iRegexp]?: string;
/**
* PG only
*
* Does not match regular expression, case insensitive
*
* Example: `[Op.notIRegexp]: '^[h|a|t]'` becomes `!~* '^[h|a|t]'`
*/
[Op.notIRegexp]?: string;
/**
* PG only
*
* Forces the operator to be strictly left eg. `<< [a, b)`
*/
[Op.strictLeft]?: Rangable;
/**
* PG only
*
* Forces the operator to be strictly right eg. `>> [a, b)`
*/
[Op.strictRight]?: Rangable;
/**
* PG only
*
* Forces the operator to not extend the left eg. `&> [1, 2)`
*/
[Op.noExtendLeft]?: Rangable;
/**
* PG only
*
* Forces the operator to not extend the left eg. `&< [1, 2)`
*/
[Op.noExtendRight]?: Rangable;
}
/** Example: `[Op.or]: [{a: 5}, {a: 6}]` becomes `(a = 5 OR a = 6)` */
export interface OrOperator<TAttributes = any> {
[Op.or]: WhereOptions<TAttributes> | WhereOptions<TAttributes>[] | WhereValue<TAttributes> | WhereValue<TAttributes>[];
}
/** Example: `[Op.and]: {a: 5}` becomes `AND (a = 5)` */
export interface AndOperator<TAttributes = any> {
[Op.and]: WhereOptions<TAttributes> | WhereOptions<TAttributes>[] | WhereValue<TAttributes> | WhereValue<TAttributes>[];
}
/**
* Where Geometry Options
*/
export interface WhereGeometryOptions {
type: string;
coordinates: (number[] | number)[];
}
/**
* Used for the right hand side of WhereAttributeHash.
* WhereAttributeHash is in there for JSON columns.
*/
export type WhereValue<TAttributes = any> =
| string // literal value
| number // literal value
| boolean // literal value
| Date // literal value
| Buffer // literal value
| null
| WhereOperators
| WhereAttributeHash<any> // for JSON columns
| Col // reference another column
| Fn
| OrOperator<TAttributes>
| AndOperator<TAttributes>
| WhereGeometryOptions
| (string | number | Buffer | WhereAttributeHash<TAttributes>)[]; // implicit [Op.or]
/**
* A hash of attributes to describe your search.
*/
export type WhereAttributeHash<TAttributes = any> = {
/**
* Possible key values:
* - A simple attribute name
* - A nested key for JSON columns
*
* {
* "meta.audio.length": {
* [Op.gt]: 20
* }
* }
*/
[field in keyof TAttributes]?: WhereValue<TAttributes> | WhereOptions<TAttributes>;
}
/**
* Through options for Include Options
*/
export interface IncludeThroughOptions extends Filterable<any>, Projectable {
/**
* The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
* `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
*/
as?: string;
}
/**
* Options for eager-loading associated models, also allowing for all associations to be loaded at once
*/
export type Includeable = typeof Model | Association | IncludeOptions | { all: true, nested?: true } | string;
/**
* Complex include options
*/
export interface IncludeOptions extends Filterable<any>, Projectable, Paranoid {
/**
* Mark the include as duplicating, will prevent a subquery from being used.
*/
duplicating?: boolean;
/**
* The model you want to eagerly load
*/
model?: typeof Model;
/**
* The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` /
* `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
*/
as?: string;
/**
* The association you want to eagerly load. (This can be used instead of providing a model/as pair)
*/
association?: Association | string;
/**
* Custom `on` clause, overrides default.
*/
on?: WhereOptions<any>;
/**
* Note that this converts the eager load to an inner join,
* unless you explicitly set `required: false`
*/
where?: WhereOptions<any>;
/**
* If true, converts to an inner join, which means that the parent model will only be loaded if it has any
* matching children. True if `include.where` is set, false otherwise.
*/
required?: boolean;
/**
* If true, converts to a right join if dialect support it. Ignored if `include.required` is true.
*/
right?: boolean;
/**
* Limit include. Only available when setting `separate` to true.
*/
limit?: number;
/**
* Run include in separate queries.
*/
separate?: boolean;
/**
* Through Options
*/
through?: IncludeThroughOptions;
/**
* Load further nested related models
*/
include?: Includeable[];
/**
* Order include. Only available when setting `separate` to true.
*/
order?: Order;
/**
* Use sub queries. This should only be used if you know for sure the query does not result in a cartesian product.
*/
subQuery?: boolean;
}
type OrderItemAssociation = Association | ModelStatic<Model> | { model: ModelStatic<Model>; as: string } | string
type OrderItemColumn = string | Col | Fn | Literal
export type OrderItem =
| string
| Fn
| Col
| Literal
| [OrderItemColumn, string]
| [OrderItemAssociation, OrderItemColumn]
| [OrderItemAssociation, OrderItemColumn, string]
| [OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
| [OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
| [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
| [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
| [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn]
| [OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]
export type Order = string | Fn | Col | Literal | OrderItem[];
/**
* Please note if this is used the aliased property will not be available on the model instance
* as a property but only via `instance.get('alias')`.
*/
export type ProjectionAlias = [string | Literal | Fn, string];
export type FindAttributeOptions =
| (string | ProjectionAlias)[]
| {
exclude: string[];
include?: (string | ProjectionAlias)[];
}
| {
exclude?: string[];
include: (string | ProjectionAlias)[];
};
export interface IndexHint {
type: IndexHints;
values: string[];
}
export interface IndexHintable {
/**
* MySQL only.
*/
indexHints?: IndexHint[];
}
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
/**
* Options that are passed to any model creating a SELECT query
*
* A hash of options to describe the scope of the search
*/
export interface FindOptions<TAttributes = any>
extends QueryOptions, Filterable<TAttributes>, Projectable, Paranoid, IndexHintable
{
/**
* A list of associations to eagerly load using a left join (a single association is also supported). Supported is either
* `{ include: Model1 }`, `{ include: [ Model1, Model2, ...]}`, `{ include: [{ model: Model1, as: 'Alias' }]}` or
* `{ include: [{ all: true }]}`.
* If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in
* the as attribute when eager loading Y).
*/
include?: Includeable | Includeable[];
/**
* Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide
* several columns / functions to order by. Each element can be further wrapped in a two-element array. The
* first element is the column / function to order by, the second is the direction. For example:
* `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
*/
order?: Order;
/**
* GROUP BY in sql
*/
group?: GroupOption;
/**
* Limit the results
*/
limit?: number;
/**
* Skip the results;
*/
offset?: number;
/**
* Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE.
* Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model
* locks with joins. See [transaction.LOCK for an example](transaction#lock)
*/
lock?:
| LOCK
| { level: LOCK; of: ModelStatic<Model> }
| boolean;
/**
* Skip locked rows. Only supported in Postgres.
*/
skipLocked?: boolean;
/**
* Return raw result. See sequelize.query for more information.
*/
raw?: boolean;
/**
* Select group rows after groups and aggregates are computed.
*/
having?: WhereOptions<any>;
/**
* Use sub queries (internal)
*/
subQuery?: boolean;
}
export interface NonNullFindOptions<TAttributes = any> extends FindOptions<TAttributes> {
/**
* Throw if nothing was found.
*/
rejectOnEmpty: boolean | Error;
}
/**
* Options for Model.count method
*/
export interface CountOptions<TAttributes = any>
extends Logging, Transactionable, Filterable<TAttributes>, Projectable, Paranoid, Poolable
{
/**
* Include options. See `find` for details
*/
include?: Includeable | Includeable[];
/**
* Apply COUNT(DISTINCT(col))
*/
distinct?: boolean;
/**
* GROUP BY in sql
* Used in conjunction with `attributes`.
* @see Projectable
*/
group?: GroupOption;
/**
* The column to aggregate on.
*/
col?: string;
}
/**
* Options for Model.count when GROUP BY is used
*/
export interface CountWithOptions<TAttributes = any> extends CountOptions<TAttributes> {
/**
* GROUP BY in sql
* Used in conjunction with `attributes`.
* @see Projectable
*/
group: GroupOption;
}
export interface FindAndCountOptions<TAttributes = any> extends CountOptions<TAttributes>, FindOptions<TAttributes> { }
/**
* Options for Model.build method
*/
export interface BuildOptions {
/**
* If set to true, values will ignore field and virtual setters.
*/
raw?: boolean;
/**
* Is this record new
*/
isNewRecord?: boolean;
/**
* An array of include options. A single option is also supported - Used to build prefetched/included model instances. See `set`
*
* TODO: See set
*/
include?: Includeable | Includeable[];
}
export interface Silent {
/**
* If true, the updatedAt timestamp will not be updated.
*
* @default false
*/
silent?: boolean;
}
/**
* Options for Model.create method
*/
export interface CreateOptions<TAttributes = any> extends BuildOptions, Logging, Silent, Transactionable, Hookable {
/**
* If set, only columns matching those in fields will be saved
*/
fields?: (keyof TAttributes)[];
/**
* On Duplicate
*/
onDuplicate?: string;
/**
* If false, validations won't be run.
*
* @default true
*/
validate?: boolean;
}
export interface Hookable {
/**
* If `false` the applicable hooks will not be called.
* The default value depends on the context.
*/
hooks?: boolean
}
/**
* Options for Model.findOrCreate method
*/
export interface FindOrCreateOptions<TAttributes = any, TCreationAttributes = TAttributes>
extends FindOptions<TAttributes>
{
/**
* The fields to insert / update. Defaults to all fields
*/
fields?: (keyof TAttributes)[];
/**
* Default values to use if building a new instance
*/
defaults?: TCreationAttributes;
}
/**
* Options for Model.upsert method
*/
export interface UpsertOptions<TAttributes = any> extends Logging, Transactionable, SearchPathable, Hookable {
/**
* The fields to insert / update. Defaults to all fields
*/
fields?: (keyof TAttributes)[];
/**
* Return the affected rows (only for postgres)
*/
returning?: boolean;
/**
* Run validations before the row is inserted
*/
validate?: boolean;
}
/**
* Options for Model.bulkCreate method
*/
export interface BulkCreateOptions<TAttributes = any> extends Logging, Transactionable, Hookable {
/**
* Fields to insert (defaults to all fields)
*/
fields?: (keyof TAttributes)[];
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row
* fails validation
*/
validate?: boolean;
/**
* Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if
* options.hooks is true.
*/
individualHooks?: boolean;
/**
* Ignore duplicate values for primary keys? (not supported by postgres)
*
* @default false
*/
ignoreDuplicates?: boolean;
/**
* Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL,
* MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5). By default, all fields are updated.
*/
updateOnDuplicate?: (keyof TAttributes)[];
/**
* Include options. See `find` for details
*/
include?: Includeable | Includeable[];
/**
* Return all columns or only the specified columns for the affected rows (only for postgres)
*/
returning?: boolean | (keyof TAttributes)[];
}
/**
* The options passed to Model.destroy in addition to truncate
*/
export interface TruncateOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {
/**
* Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the
* named table, or to any tables added to the group due to CASCADE.
*
* @default false;
*/
cascade?: boolean;
/**
* If set to true, destroy will SELECT all records matching the where parameter and will execute before /
* after destroy hooks on each row
*/
individualHooks?: boolean;
/**
* How many rows to delete
*/
limit?: number;
/**
* Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
*/
force?: boolean;
/**
* Only used in conjunction with `truncate`.
* Automatically restart sequences owned by columns of the truncated table
*/
restartIdentity?: boolean;
}
/**
* Options used for Model.destroy
*/
export interface DestroyOptions<TAttributes = any> extends TruncateOptions<TAttributes> {
/**
* If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is
* truncated the where and limit options are ignored
*/
truncate?: boolean;
}
/**
* Options for Model.restore
*/
export interface RestoreOptions<TAttributes = any> extends Logging, Transactionable, Filterable<TAttributes>, Hookable {
/**
* If set to true, restore will find all records within the where parameter and will execute before / after
* bulkRestore hooks on each row
*/
individualHooks?: boolean;
/**
* How many rows to undelete
*/
limit?: number;
}
/**
* Options used for Model.update
*/
export interface UpdateOptions<TAttributes = any> extends Logging, Transactionable, Paranoid, Hookable {
/**
* Options to describe the scope of the search.
*/
where: WhereOptions<TAttributes>;
/**
* Fields to update (defaults to all fields)
*/
fields?: (keyof TAttributes)[];
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row
* fails validation.
*
* @default true
*/
validate?: boolean;
/**
* Whether or not to update the side effects of any virtual setters.
*
* @default true
*/
sideEffects?: boolean;
/**
* Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs.
* A select is needed, because the row data needs to be passed to the hooks
*
* @default false
*/
individualHooks?: boolean;
/**
* Return the affected rows (only for postgres)
*/
returning?: boolean;
/**
* How many rows to update (only for mysql and mariadb)
*/
limit?: number;
/**
* If true, the updatedAt timestamp will not be updated.
*/
silent?: boolean;
}
/**
* Options used for Model.aggregate
*/
export interface AggregateOptions<T extends DataType | unknown, TAttributes = any>
extends QueryOptions, Filterable<TAttributes>, Paranoid
{
/**
* The type of the result. If `field` is a field in this Model, the default will be the type of that field,
* otherwise defaults to float.
*/
dataType?: string | T;
/**
* Applies DISTINCT to the field being aggregated over
*/
distinct?: boolean;
}
// instance
/**
* Options used for Instance.increment method
*/
export interface IncrementDecrementOptions<TAttributes = any>
extends Logging, Transactionable, Silent, SearchPathable, Filterable<TAttributes> { }
/**
* Options used for Instance.increment method
*/
export interface IncrementDecrementOptionsWithBy<TAttributes = any> extends IncrementDecrementOptions<TAttributes> {
/**
* The number to increment by
*
* @default 1
*/
by?: number;
}
/**
* Options used for Instance.restore method
*/
export interface InstanceRestoreOptions extends Logging, Transactionable { }
/**
* Options used for Instance.destroy method
*/
export interface InstanceDestroyOptions extends Logging, Transactionable {
/**
* If set to true, paranoid models will actually be deleted
*/
force?: boolean;
}
/**
* Options used for Instance.update method
*/
export interface InstanceUpdateOptions<TAttributes = any> extends
SaveOptions<TAttributes>, SetOptions, Filterable<TAttributes> { }
/**
* Options used for Instance.set method
*/
export interface SetOptions {
/**
* If set to true, field and virtual setters will be ignored
*/
raw?: boolean;
/**
* Clear all previously set data values
*/
reset?: boolean;
}
/**
* Options used for Instance.save method
*/
export interface SaveOptions<TAttributes = any> extends Logging, Transactionable, Silent, Hookable {
/**
* An optional array of strings, representing database columns. If fields is provided, only those columns
* will be validated and saved.
*/
fields?: (keyof TAttributes)[];
/**
* If false, validations won't be run.
*
* @default true
*/
validate?: boolean;
}
/**
* Model validations, allow you to specify format/content/inheritance validations for each attribute of the
* model.
*
* Validations are automatically run on create, update and save. You can also call validate() to manually
* validate an instance.
*
* The validations are implemented by validator.js.
*/
export interface ModelValidateOptions {
/**
* is: ["^[a-z]+$",'i'] // will only allow letters
* is: /^[a-z]+[Op./i] // same as the previous example using real RegExp
*/
is?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
/**
* not: ["[a-z]",'i'] // will not allow letters
*/
not?: string | (string | RegExp)[] | RegExp | { msg: string; args: string | (string | RegExp)[] | RegExp };
/**
* checks for email format (foo@bar.com)
*/
isEmail?: boolean | { msg: string };
/**
* checks for url format (http://foo.com)
*/
isUrl?: boolean | { msg: string };
/**
* checks for IPv4 (129.89.23.1) or IPv6 format
*/
isIP?: boolean | { msg: string };
/**
* checks for IPv4 (129.89.23.1)
*/
isIPv4?: boolean | { msg: string };
/**
* checks for IPv6 format
*/
isIPv6?: boolean | { msg: string };
/**
* will only allow letters
*/
isAlpha?: boolean | { msg: string };
/**
* will only allow alphanumeric characters, so "_abc" will fail
*/
isAlphanumeric?: boolean | { msg: string };
/**
* will only allow numbers
*/
isNumeric?: boolean | { msg: string };
/**
* checks for valid integers
*/
isInt?: boolean | { msg: string };
/**
* checks for valid floating point numbers
*/
isFloat?: boolean | { msg: string };
/**
* checks for any numbers
*/
isDecimal?: boolean | { msg: string };
/**
* checks for lowercase
*/
isLowercase?: boolean | { msg: string };
/**
* checks for uppercase
*/
isUppercase?: boolean | { msg: string };
/**
* won't allow null
*/
notNull?: boolean | { msg: string };
/**
* only allows null
*/
isNull?: boolean | { msg: string };
/**
* don't allow empty strings
*/
notEmpty?: boolean | { msg: string };
/**
* only allow a specific value
*/
equals?: string | { msg: string };
/**
* force specific substrings
*/
contains?: string | { msg: string };
/**
* check the value is not one of these
*/
notIn?: string[][] | { msg: string; args: string[][] };
/**
* check the value is one of these
*/
isIn?: string[][] | { msg: string; args: string[][] };
/**
* don't allow specific substrings
*/
notContains?: string[] | string | { msg: string; args: string[] | string };
/**
* only allow values with length between 2 and 10
*/
len?: [number, number] | { msg: string; args: [number, number] };
/**
* only allow uuids
*/
isUUID?: number | { msg: string; args: number };
/**
* only allow date strings
*/
isDate?: boolean | { msg: string; args: boolean };
/**
* only allow date strings after a specific date
*/
isAfter?: string | { msg: string; args: string };
/**
* only allow date strings before a specific date
*/
isBefore?: string | { msg: string; args: string };
/**
* only allow values
*/
max?: number | { msg: string; args: [number] };
/**
* only allow values >= 23
*/
min?: number | { msg: string; args: [number] };
/**
* only allow arrays
*/
isArray?: boolean | { msg: string; args: boolean };
/**
* check for valid credit card numbers
*/
isCreditCard?: boolean | { msg: string; args: boolean };
/**
* custom validations are also possible
*
* Implementation notes :
*
* We can't enforce any other method to be a function, so :
*
* ```typescript
* [name: string] : ( value : unknown ) => boolean;
* ```
*
* doesn't work in combination with the properties above
*
* @see https://github.com/Microsoft/TypeScript/issues/1889
*/
[name: string]: unknown;
}
/**
* Interface for indexes property in InitOptions
*/
export type ModelIndexesOptions = IndexesOptions
/**
* Interface for name property in InitOptions
*/
export interface ModelNameOptions {
/**
* Singular model name
*/
singular?: string;
/**
* Plural model name
*/
plural?: string;
}
/**
* Interface for getterMethods in InitOptions
*/
export interface ModelGetterOptions<M extends Model = Model> {
[name: string]: (this: M) => unknown;
}
/**
* Interface for setterMethods in InitOptions
*/
export interface ModelSetterOptions<M extends Model = Model> {
[name: string]: (this: M, val: any) => void;
}
/**
* Interface for Define Scope Options
*/
export interface ModelScopeOptions<TAttributes = any> {
/**
* Name of the scope and it's query
*/
[scopeName: string]: FindOptions<TAttributes> | ((...args: any[]) => FindOptions<TAttributes>);
}
/**
* General column options
*/
export interface ColumnOptions {
/**
* If false, the column will have a NOT NULL constraint, and a not null validation will be run before an
* instance is saved.
* @default true
*/
allowNull?: boolean;
/**
* If set, sequelize will map the attribute name to a different name in the database
*/
field?: string;
/**
* A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
*/
defaultValue?: unknown;
}
/**
* References options for the column's attributes
*/
export interface ModelAttributeColumnReferencesOptions {
/**
* If this column references another table, provide it here as a Model, or a string
*/
model?: string | typeof Model;
/**
* The column of the foreign table that this column references
*/
key?: string;
/**
* When to check for the foreign key constraing
*
* PostgreSQL only
*/
deferrable?: Deferrable;
}
/**
* Column options for the model schema attributes
*/
export interface ModelAttributeColumnOptions<M extends Model = Model> extends ColumnOptions {
/**
* A string or a data type
*/
type: DataType;
/**
* If true, the column will get a unique constraint. If a string is provided, the column will be part of a
* composite unique index. If multiple columns have the same string, they will be part of the same unique
* index
*/
unique?: boolean | string | { name: string; msg: string };
/**
* Primary key flag
*/
primaryKey?: boolean;
/**
* Is this field an auto increment field
*/
autoIncrement?: boolean;
/**
* If this field is a Postgres auto increment field, use Postgres `GENERATED BY DEFAULT AS IDENTITY` instead of `SERIAL`. Postgres 10+ only.
*/
autoIncrementIdentity?: boolean;
/**
* Comment for the database
*/
comment?: string;
/**
* An object with reference configurations or the column name as string
*/
references?: string | ModelAttributeColumnReferencesOptions;
/**
* What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION
*/
onUpdate?: string;
/**
* What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION
*/
onDelete?: string;
/**
* An object of validations to execute for this column every time the model is saved. Can be either the
* name of a validation provided by validator.js, a validation function provided by extending validator.js
* (see the
* `DAOValidator` property for more details), or a custom validation function. Custom validation functions
* are called with the value of the field, and can possibly take a second callback argument, to signal that
* they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it
* it is async, the callback should be called with the error text.
*/
validate?: ModelValidateOptions;
/**
* Usage in object notation
*
* ```js
* class MyModel extends Model {}
* MyModel.init({
* states: {
* type: Sequelize.ENUM,
* values: ['active', 'pending', 'deleted']
* }
* }, { sequelize })
* ```
*/
values?: string[];
/**
* Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying
* values.
*/
get?(this: M): unknown;
/**
* Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the
* underlying values.
*/
set?(this: M, val: unknown): void;
}
/**
* Interface for Attributes provided for a column
*/
export type ModelAttributes<M extends Model = Model, TCreationAttributes = any> = {
/**
* The description of a database column
*/
[name in keyof TCreationAttributes]: DataType | ModelAttributeColumnOptions<M>;
}
/**
* Possible types for primary keys
*/
export type Identifier = number | string | Buffer;
/**
* Options for model definition
*/
export interface ModelOptions<M extends Model = Model> {
/**
* Define the default search scope to use for this model. Scopes have the same form as the options passed to
* find / findAll.
*/
defaultScope?: FindOptions<M['_attributes']>;
/**
* More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about
* how scopes are defined, and what you can do with them
*/
scopes?: ModelScopeOptions<M['_attributes']>;
/**
* Don't persits null values. This means that all columns with null values will not be saved.
*/
omitNull?: boolean;
/**
* Adds createdAt and updatedAt timestamps to the model. Default true.
*/
timestamps?: boolean;
/**
* Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
* timestamps=true to work. Default false.
*/
paranoid?: boolean;
/**
* Converts all camelCased columns to underscored if true. Default false.
*/
underscored?: boolean;
/**
* Indicates if the model's table has a trigger associated with it. Default false.
*/
hasTrigger?: boolean;
/**
* If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name.
* Otherwise, the dao name will be pluralized. Default false.
*/
freezeTableName?: boolean;
/**
* An object with two attributes, `singular` and `plural`, which are used when this model is associated to
* others.
*/
name?: ModelNameOptions;
/**
* Set name of the model. By default its same as Class name.
*/
modelName?: string;
/**
* Indexes for the provided database table
*/
indexes?: ModelIndexesOptions[];
/**
* Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
createdAt?: string | boolean;
/**
* Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
deletedAt?: string | boolean;
/**
* Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps
* must be true. Not affected by underscored setting.
*/
updatedAt?: string | boolean;
/**
* @default pluralized model name, unless freezeTableName is true, in which case it uses model name
* verbatim
*/
tableName?: string;
schema?: string;
/**
* You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
*/
engine?: string;
charset?: string;
/**
* Finaly you can specify a comment for the table in MySQL and PG
*/
comment?: string;
collate?: string;
/**
* Set the initial AUTO_INCREMENT value for the table in MySQL.
*/
initialAutoIncrement?: string;
/**
* An object of hook function that are called before and after certain lifecycle events.
* See Hooks for more information about hook
* functions and their signatures. Each property can either be a function, or an array of functions.
*/
hooks?: Partial<ModelHooks<M, M['_attributes']>>;
/**
* An object of model wide validations. Validations have access to all model values via `this`. If the
* validator function takes an argument, it is asumed to be async, and is called with a callback that
* accepts an optional error.
*/
validate?: ModelValidateOptions;
/**
* Allows defining additional setters that will be available on model instances.
*/
setterMethods?: ModelSetterOptions<M>;
/**
* Allows defining additional getters that will be available on model instances.
*/
getterMethods?: ModelGetterOptions<M>;
/**
* Enable optimistic locking.
* When enabled, sequelize will add a version count attribute to the model and throw an
* OptimisticLockingError error when stale instances are saved.
* - If string: Uses the named attribute.
* - If boolean: Uses `version`.
* @default false
*/
version?: boolean | string;
}
/**
* Options passed to [[Model.init]]
*/
export interface InitOptions<M extends Model = Model> extends ModelOptions<M> {
/**
* The sequelize connection. Required ATM.
*/
sequelize: Sequelize;
}
/**
* AddScope Options for Model.addScope
*/
export interface AddScopeOptions {
/**
* If a scope of the same name already exists, should it be overwritten?
*/
override: boolean;
}
export abstract class Model<TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes>
extends Hooks<Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes>
{
/**
* A dummy variable that doesn't exist on the real object. This exists so
* Typescript can infer the type of the attributes in static functions. Don't
* try to access this!
*
* Before using these, I'd tried typing out the functions without them, but
* Typescript fails to infer `TAttributes` in signatures like the below.
*
* ```ts
* public static findOne<M extends Model<TAttributes>, TAttributes>(
* this: { new(): M },
* options: NonNullFindOptions<TAttributes>
* ): Promise<M>;
* ```
*/
_attributes: TModelAttributes;
/**
* A similar dummy variable that doesn't exist on the real object. Do not
* try to access this in real code.
*/
_creationAttributes: TCreationAttributes;
/** The name of the database table */
public static readonly tableName: string;
/**
* The name of the primary key attribute
*/
public static readonly primaryKeyAttribute: string;
/**
* The name of the primary key attributes
*/
public static readonly primaryKeyAttributes: string[];
/**
* An object hash from alias to association object
*/
public static readonly associations: {
[key: string]: Association;
};
/**
* The options that the model was initialized with
*/
public static readonly options: InitOptions;
/**
* The attributes of the model
*/
public static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions };
/**
* Reference to the sequelize instance the model was initialized with
*/
public static readonly sequelize?: Sequelize;
/**
* Initialize a model, representing a table in the DB, with attributes and options.
*
* The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
*
* ```js
* Project.init({
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ['[a-z]','i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* }, {sequelize})
*
* sequelize.models.modelName // The model will now be available in models under the class name
* ```
*
* As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
*
* For a list of possible data types, see https://sequelize.org/master/en/latest/docs/models-definition/#data-types
*
* For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
*
* For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
*
* For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
*
* @param attributes
* An object, where each attribute is a column of the table. Each column can be either a DataType, a
* string or a type-description object, with the properties described below:
* @param options These options are merged with the default define options provided to the Sequelize constructor
* @return Return the initialized model
*/
public static init<M extends Model>(
this: ModelStatic<M>,
attributes: ModelAttributes<M, M['_attributes']>, options: InitOptions<M>
): Model;
/**
* Remove attribute from model definition
*
* @param attribute
*/
public static removeAttribute(attribute: string): void;
/**
* Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the
* model instance (this)
*/
public static sync<M extends Model>(options?: SyncOptions): Promise<M>;
/**
* Drop the table represented by this Model
*
* @param options
*/
public static drop(options?: DropOptions): Promise<void>;
/**
* Apply a schema to this model. For postgres, this will actually place the schema in front of the table
* name
* - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and
* sqlite - `'schema.tablename'`.
*
* @param schema The name of the schema
* @param options
*/
public static schema<M extends Model>(
this: ModelStatic<M>,
schema: string,
options?: SchemaOptions
): { new(): M } & typeof Model;
/**
* Get the tablename of the model, taking schema into account. The method will return The name as a string
* if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties.
*
* @param options The hash of options from any query. You can use one model to access tables with matching
* schemas by overriding `getTableName` and using custom key/values to alter the name of the table.
* (eg.
* subscribers_1, subscribers_2)
*/
public static getTableName(): string | {
tableName: string;
schema: string;
delimiter: string;
};
/**
* Apply a scope created in `define` to the model. First let's look at how to create scopes:
* ```js
* class MyModel extends Model {}
* MyModel.init(attributes, {
* defaultScope: {
* where: {
* username: 'dan'
* },
* limit: 12
* },
* scopes: {
* isALie: {
* where: {
* stuff: 'cake'
* }
* },
* complexFunction(email, accessLevel) {
* return {
* where: {
* email: {
* [Op.like]: email
* },
* accesss_level {
* [Op.gte]: accessLevel
* }
* }
* }
* }
* },
* sequelize,
* })
* ```
* Now, since you defined a default scope, every time you do Model.find, the default scope is appended to
* your query. Here's a couple of examples:
* ```js
* Model.findAll() // WHERE username = 'dan'
* Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
* ```
*
* To invoke scope functions you can do:
* ```js
* Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
* // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
* ```
*
* @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned
* model will clear the previous scope.
*/
public static scope<M extends Model>(
this: ModelStatic<M>,
options?: string | ScopeOptions | (string | ScopeOptions)[] | WhereAttributeHash<M>
): ModelCtor<M>;
/**
* Add a new scope to the model
*
* This is especially useful for adding scopes with includes, when the model you want to
* include is not available at the time this model is defined. By default this will throw an
* error if a scope with that name already exists. Pass `override: true` in the options
* object to silence this error.
*/
public static addScope<M extends Model>(
this: ModelStatic<M>,
name: string,
scope: FindOptions<M['_attributes']>,
options?: AddScopeOptions
): void;
public static addScope<M extends Model>(
this: ModelStatic<M>,
name: string,
scope: (...args: any[]) => FindOptions<M['_attributes']>,
options?: AddScopeOptions
): void;
/**
* Search for multiple instances.
*
* __Simple search using AND and =__
* ```js
* Model.findAll({
* where: {
* attr1: 42,
* attr2: 'cake'
* }
* })
* ```
* ```sql
* WHERE attr1 = 42 AND attr2 = 'cake'
* ```
*
* __Using greater than, less than etc.__
* ```js
*
* Model.findAll({
* where: {
* attr1: {
* gt: 50
* },
* attr2: {
* lte: 45
* },
* attr3: {
* in: [1,2,3]
* },
* attr4: {
* ne: 5
* }
* }
* })
* ```
* ```sql
* WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
* ```
* Possible options are: `[Op.ne], [Op.in], [Op.not], [Op.notIn], [Op.gte], [Op.gt], [Op.lte], [Op.lt], [Op.like], [Op.ilike]/[Op.iLike], [Op.notLike],
* [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
*
* __Queries using OR__
* ```js
* Model.findAll({
* where: Sequelize.and(
* { name: 'a project' },
* Sequelize.or(
* { id: [1,2,3] },
* { id: { gt: 10 } }
* )
* )
* })
* ```
* ```sql
* WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
* ```
*
* The success listener is called with an array of instances if the query succeeds.
*
* @see {Sequelize#query}
*/
public static findAll<M extends Model>(
this: ModelStatic<M>,
options?: FindOptions<M['_attributes']>): Promise<M[]>;
/**
* Search for a single instance by its primary key. This applies LIMIT 1, so the listener will
* always be called with a single instance.
*/
public static findByPk<M extends Model>(
this: ModelStatic<M>,
identifier: Identifier,
options: Omit<NonNullFindOptions<M['_attributes']>, 'where'>
): Promise<M>;
public static findByPk<M extends Model>(
this: ModelStatic<M>,
identifier?: Identifier,
options?: Omit<FindOptions<M['_attributes']>, 'where'>
): Promise<M | null>;
/**
* Search for a single instance. Returns the first instance found, or null if none can be found.
*/
public static findOne<M extends Model>(
this: ModelStatic<M>,
options: NonNullFindOptions<M['_attributes']>
): Promise<M>;
public static findOne<M extends Model>(
this: ModelStatic<M>,
options?: FindOptions<M['_attributes']>
): Promise<M | null>;
/**
* Run an aggregation method on the specified field
*
* @param field The field to aggregate over. Can be a field name or *
* @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param options Query options. See sequelize.query for full options
* @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in
* which case the complete data result is returned.
*/
public static aggregate<T, M extends Model>(
this: ModelStatic<M>,
field: keyof M['_attributes'] | '*',
aggregateFunction: string,
options?: AggregateOptions<T, M['_attributes']>
): Promise<T>;
/**
* Count number of records if group by is used
*/
public static count<M extends Model>(
this: ModelStatic<M>,
options: CountWithOptions<M['_attributes']>
): Promise<{ [key: string]: number }>;
/**
* Count the number of records matching the provided where clause.
*
* If you provide an `include` option, the number of matching associations will be counted instead.
*/
public static count<M extends Model>(
this: ModelStatic<M>,
options?: CountOptions<M['_attributes']>
): Promise<number>;
/**
* Find all the rows matching your query, within a specified offset / limit, and get the total number of
* rows matching your query. This is very usefull for paging
*
* ```js
* Model.findAndCountAll({
* where: ...,
* limit: 12,
* offset: 12
* }).then(result => {
* ...
* })
* ```
* In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return
* the
* total number of rows that matched your query.
*
* When you add includes, only those which are required (either because they have a where clause, or
* because
* `required` is explicitly set to true on the include) will be added to the count part.
*
* Suppose you want to find all users who have a profile attached:
* ```js
* User.findAndCountAll({
* include: [
* { model: Profile, required: true}
* ],
* limit: 3
* });
* ```
* Because the include for `Profile` has `required` set it will result in an inner join, and only the users
* who have a profile will be counted. If we remove `required` from the include, both users with and
* without
* profiles will be counted
*/
public static findAndCountAll<M extends Model>(
this: ModelStatic<M>,
options?: FindAndCountOptions<M['_attributes']>
): Promise<{ rows: M[]; count: number }>;
/**
* Find the maximum value of field
*/
public static max<T extends DataType | unknown, M extends Model>(
this: ModelStatic<M>,
field: keyof M['_attributes'],
options?: AggregateOptions<T, M['_attributes']>
): Promise<T>;
/**
* Find the minimum value of field
*/
public static min<T extends DataType | unknown, M extends Model>(
this: ModelStatic<M>,
field: keyof M['_attributes'],
options?: AggregateOptions<T, M['_attributes']>
): Promise<T>;
/**
* Find the sum of field
*/
public static sum<T extends DataType | unknown, M extends Model>(
this: ModelStatic<M>,
field: keyof M['_attributes'],
options?: AggregateOptions<T, M['_attributes']>
): Promise<number>;
/**
* Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
*/
public static build<M extends Model>(
this: ModelStatic<M>,
record?: M['_creationAttributes'],
options?: BuildOptions
): M;
/**
* Undocumented bulkBuild
*/
public static bulkBuild<M extends Model>(
this: ModelStatic<M>,
records: (M['_creationAttributes'])[],
options?: BuildOptions
): M[];
/**
* Builds a new model instance and calls save on it.
*/
public static create<M extends Model>(
this: ModelStatic<M>,
values?: M['_creationAttributes'],
options?: CreateOptions<M['_attributes']>
): Promise<M>;
public static create<M extends Model>(
this: ModelStatic<M>,
values: M['_creationAttributes'],
options: CreateOptions<M['_attributes']> & { returning: false }
): Promise<void>;
/**
* Find a row that matches the query, or build (but don't save) the row if none is found.
* The successfull result of the promise will be (instance, initialized) - Make sure to use `.then(([...]))`
*/
public static findOrBuild<M extends Model>(
this: ModelStatic<M>,
options: FindOrCreateOptions<M['_attributes'], M['_creationAttributes']>
): Promise<[M, boolean]>;
/**
* Find a row that matches the query, or build and save the row if none is found
* The successful result of the promise will be (instance, created) - Make sure to use `.then(([...]))`
*
* If no transaction is passed in the `options` object, a new transaction will be created internally, to
* prevent the race condition where a matching row is created by another connection after the find but
* before the insert call. However, it is not always possible to handle this case in SQLite, specifically
* if one transaction inserts and another tries to select before the first one has comitted. In this case,
* an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint
* will be created instead, and any unique constraint violation will be handled internally.
*/
public static findOrCreate<M extends Model>(
this: ModelStatic<M>,
options: FindOrCreateOptions<M['_attributes'], M['_creationAttributes']>
): Promise<[M, boolean]>;
/**
* A more performant findOrCreate that will not work under a transaction (at least not in postgres)
* Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
*/
public static findCreateFind<M extends Model>(
this: ModelStatic<M>,
options: FindOrCreateOptions<M['_attributes'], M['_creationAttributes']>
): Promise<[M, boolean]>;
/**
* Insert or update a single row. An update will be executed if a row which matches the supplied values on
* either the primary key or a unique key is found. Note that the unique index must be defined in your
* sequelize model and not just in the table. Otherwise you may experience a unique constraint violation,
* because sequelize fails to identify the row that should be updated.
*
* **Implementation details:**
*
* * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
* * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN
* unique_constraint UPDATE
* * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed
* regardless
* of whether the row already existed or not
*
* **Note** that SQLite returns null for created, no matter if the row was created or updated. This is
* because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know
* whether the row was inserted or not.
*/
public static upsert<M extends Model>(
this: ModelStatic<M>,
values: M['_creationAttributes'],
options?: UpsertOptions<M['_attributes']>
): Promise<[M, boolean | null]>;
/**
* Create and insert multiple instances in bulk.
*
* The success handler is passed an array of instances, but please notice that these may not completely
* represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to
* obtain
* back automatically generated IDs and other default values in a way that can be mapped to multiple
* records. To obtain Instances for the newly created values, you will need to query for them again.
*
* @param records List of objects (key/value pairs) to create instances from
*/
public static bulkCreate<M extends Model>(
this: ModelStatic<M>,
records: (M['_creationAttributes'])[],
options?: BulkCreateOptions<M['_attributes']>
): Promise<M[]>;
/**
* Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
*/
public static truncate<M extends Model>(
this: ModelStatic<M>,
options?: TruncateOptions<M['_attributes']>
): Promise<void>;
/**
* Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
*
* @return Promise<number> The number of destroyed rows
*/
public static destroy<M extends Model>(
this: ModelStatic<M>,
options?: DestroyOptions<M['_attributes']>
): Promise<number>;
/**
* Restore multiple instances if `paranoid` is enabled.
*/
public static restore<M extends Model>(
this: ModelStatic<M>,
options?: RestoreOptions<M['_attributes']>
): Promise<void>;
/**
* Update multiple instances that match the where options. The promise returns an array with one or two
* elements. The first element is always the number of affected rows, while the second element is the actual
* affected rows (only supported in postgres and mssql with `options.returning` true.)
*/
public static update<M extends Model>(
this: ModelStatic<M>,
values: Partial<M['_attributes']>,
options: UpdateOptions<M['_attributes']>
): Promise<[number, M[]]>;
/**
* Increments a single field.
*/
public static increment<M extends Model>(
this: ModelStatic<M>,
field: keyof M['_attributes'],
options: IncrementDecrementOptionsWithBy<M['_attributes']>
): Promise<M>;
/**
* Increments multiple fields by the same value.
*/
public static increment<M extends Model>(
this: ModelStatic<M>,
fields: (keyof M['_attributes'])[],
options: IncrementDecrementOptionsWithBy<M['_attributes']>
): Promise<M>;
/**
* Increments multiple fields by different values.
*/
public static increment<M extends Model>(
this: ModelStatic<M>,
fields: { [key in keyof M['_attributes']]?: number },
options: IncrementDecrementOptions<M['_attributes']>
): Promise<M>;
/**
* Run a describe query on the table. The result will be return to the listener as a hash of attributes and
* their types.
*/
public static describe(): Promise<object>;
/**
* Unscope the model
*/
public static unscoped<M extends typeof Model>(this: M): M;
/**
* A hook that is run before validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeValidate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
public static beforeValidate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
/**
* A hook that is run after validation
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterValidate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
public static afterValidate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: ValidationOptions) => HookReturn
): void;
/**
* A hook that is run before creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static beforeCreate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: CreateOptions<M['_attributes']>) => HookReturn
): void;
public static beforeCreate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: CreateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after creating a single instance
*
* @param name
* @param fn A callback function that is called with attributes, options
*/
public static afterCreate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: CreateOptions<M['_attributes']>) => HookReturn
): void;
public static afterCreate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: CreateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeDestroy<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
public static beforeDestroy<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
/**
* A hook that is run after destroying a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterDestroy<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
public static afterDestroy<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
): void;
/**
* A hook that is run before updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeUpdate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
public static beforeUpdate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after updating a single instance
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterUpdate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
public static afterUpdate<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate`
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static beforeSave<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: UpdateOptions<M['_attributes']> | SaveOptions<M['_attributes']>) => HookReturn
): void;
public static beforeSave<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: UpdateOptions<M['_attributes']> | SaveOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
*
* @param name
* @param fn A callback function that is called with instance, options
*/
public static afterSave<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instance: M, options: UpdateOptions<M['_attributes']> | SaveOptions<M['_attributes']>) => HookReturn
): void;
public static afterSave<M extends Model>(
this: ModelStatic<M>,
fn: (instance: M, options: UpdateOptions<M['_attributes']> | SaveOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static beforeBulkCreate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instances: M[], options: BulkCreateOptions<M['_attributes']>) => HookReturn
): void;
public static beforeBulkCreate<M extends Model>(
this: ModelStatic<M>,
fn: (instances: M[], options: BulkCreateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after creating instances in bulk
*
* @param name
* @param fn A callback function that is called with instances, options
*/
public static afterBulkCreate<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instances: M[], options: BulkCreateOptions<M['_attributes']>) => HookReturn
): void;
public static afterBulkCreate<M extends Model>(
this: ModelStatic<M>,
fn: (instances: M[], options: BulkCreateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkDestroy<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: BulkCreateOptions<M['_attributes']>) => HookReturn): void;
public static beforeBulkDestroy<M extends Model>(
this: ModelStatic<M>,
fn: (options: BulkCreateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after destroying instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkDestroy<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: DestroyOptions<M['_attributes']>) => HookReturn
): void;
public static afterBulkDestroy<M extends Model>(
this: ModelStatic<M>,
fn: (options: DestroyOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeBulkUpdate<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
public static beforeBulkUpdate<M extends Model>(
this: ModelStatic<M>,
fn: (options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run after updating instances in bulk
*
* @param name
* @param fn A callback function that is called with options
*/
public static afterBulkUpdate<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
public static afterBulkUpdate<M extends Model>(
this: ModelStatic<M>,
fn: (options: UpdateOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before a find (select) query
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFind<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: FindOptions<M['_attributes']>) => HookReturn
): void;
public static beforeFind<M extends Model>(
this: ModelStatic<M>,
fn: (options: FindOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before a count query
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeCount<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: CountOptions<M['_attributes']>) => HookReturn
): void;
public static beforeCount<M extends Model>(
this: ModelStatic<M>,
fn: (options: CountOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterExpandIncludeAll<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: FindOptions<M['_attributes']>) => HookReturn
): void;
public static beforeFindAfterExpandIncludeAll<M extends Model>(
this: ModelStatic<M>,
fn: (options: FindOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before a find (select) query, after all option parsing is complete
*
* @param name
* @param fn A callback function that is called with options
*/
public static beforeFindAfterOptions<M extends Model>(
this: ModelStatic<M>,
name: string, fn: (options: FindOptions<M['_attributes']>) => HookReturn
): void;
public static beforeFindAfterOptions<M extends Model>(
this: ModelStatic<M>,
fn: (options: FindOptions<M['_attributes']>) => void
): HookReturn;
/**
* A hook that is run after a find (select) query
*
* @param name
* @param fn A callback function that is called with instance(s), options
*/
public static afterFind<M extends Model>(
this: ModelStatic<M>,
name: string,
fn: (instancesOrInstance: M[] | M | null, options: FindOptions<M['_attributes']>) => HookReturn
): void;
public static afterFind<M extends Model>(
this: ModelStatic<M>,
fn: (instancesOrInstance: M[] | M | null, options: FindOptions<M['_attributes']>) => HookReturn
): void;
/**
* A hook that is run before sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after sequelize.sync call
* @param fn A callback function that is called with options passed to sequelize.sync
*/
public static afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterBulkSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run before Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static beforeSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* A hook that is run after Model.sync call
* @param fn A callback function that is called with options passed to Model.sync
*/
public static afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void;
public static afterSync(fn: (options: SyncOptions) => HookReturn): void;
/**
* Creates an association between this (the source) and the provided target. The foreign key is added
* on the target.
*
* Example: `User.hasOne(Profile)`. This will add userId to the profile table.
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static hasOne<M extends Model, T extends Model>(
this: ModelStatic<M>, target: ModelStatic<T>, options?: HasOneOptions
): HasOne<M, T>;
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the
* source.
*
* Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static belongsTo<M extends Model, T extends Model>(
this: ModelStatic<M>, target: ModelStatic<T>, options?: BelongsToOptions
): BelongsTo<M, T>;
/**
* Create an association that is either 1:m or n:m.
*
* ```js
* // Create a 1:m association between user and project
* User.hasMany(Project)
* ```
* ```js
* // Create a n:m association between user and project
* User.hasMany(Project)
* Project.hasMany(User)
* ```
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be
* overridden by providing either a string or a Model as `through` in the options. If you use a through
* model with custom attributes, these attributes can be set when adding / setting new associations in two
* ways. Consider users and projects from before with a join table that stores whether the project has been
* started yet:
* ```js
* class UserProjects extends Model {}
* UserProjects.init({
* started: Sequelize.BOOLEAN
* }, { sequelize })
* User.hasMany(Project, { through: UserProjects })
* Project.hasMany(User, { through: UserProjects })
* ```
* ```js
* jan.addProject(homework, { started: false }) // The homework project is not started yet
* jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
* started
* ```
*
* If you want to set several target instances, but with different attributes you have to set the
* attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.userprojects {
* started: true
* }
* user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
* ```
*
* Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model.
* ```js
* user.getProjects().then(projects => {
* const p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* ```
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static hasMany<M extends Model, T extends Model>(
this: ModelStatic<M>, target: ModelStatic<T>, options?: HasManyOptions
): HasMany<M, T>;
/**
* Create an N:M association with a join table
*
* ```js
* User.belongsToMany(Project)
* Project.belongsToMany(User)
* ```
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be
* overridden by providing either a string or a Model as `through` in the options.
*
* If you use a through model with custom attributes, these attributes can be set when adding / setting new
* associations in two ways. Consider users and projects from before with a join table that stores whether
* the project has been started yet:
* ```js
* class UserProjects extends Model {}
* UserProjects.init({
* started: Sequelize.BOOLEAN
* }, { sequelize });
* User.belongsToMany(Project, { through: UserProjects })
* Project.belongsToMany(User, { through: UserProjects })
* ```
* ```js
* jan.addProject(homework, { started: false }) // The homework project is not started yet
* jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started
* ```
*
* If you want to set several target instances, but with different attributes you have to set the
* attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.userprojects {
* started: true
* }
* user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.
* ```
*
* Similarily, when fetching through a join table with custom attributes, these attributes will be
* available as an object with the name of the through model.
* ```js
* user.getProjects().then(projects => {
* const p1 = projects[0]
* p1.userprojects.started // Is this project started yet?
* })
* ```
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*
*/
public static belongsToMany<M extends Model, T extends Model>(
this: ModelStatic<M>, target: ModelStatic<T>, options: BelongsToManyOptions
): BelongsToMany<M, T>;
/**
* Returns true if this instance has not yet been persisted to the database
*/
public isNewRecord: boolean;
/**
* A reference to the sequelize instance
*/
public sequelize: Sequelize;
/**
* Builds a new model instance.
* @param values an object of key value pairs
*/
constructor(values?: TCreationAttributes, options?: BuildOptions);
/**
* Get an object representing the query for this instance, use with `options.where`
*/
public where(): object;
/**
* Get the value of the underlying data value
*/
public getDataValue<K extends keyof TModelAttributes>(key: K): TModelAttributes[K];
/**
* Update the underlying data value
*/
public setDataValue<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K]): void;
/**
* If no key is given, returns all values of the instance, also invoking virtual getters.
*
* If key is given and a field or virtual getter is present for the key it will call that getter - else it
* will return the value for key.
*
* @param options.plain If set to true, included instances will be returned as plain objects
*/
public get(options?: { plain?: boolean; clone?: boolean }): TModelAttributes;
public get<K extends keyof this>(key: K, options?: { plain?: boolean; clone?: boolean }): this[K];
public get(key: string, options?: { plain?: boolean; clone?: boolean }): unknown;
/**
* Set is used to update values on the instance (the sequelize representation of the instance that is,
* remember that nothing will be persisted before you actually call `save`). In its most basic form `set`
* will update a value stored in the underlying `dataValues` object. However, if a custom setter function
* is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw:
* true` in the options object.
*
* If set is called with an object, it will loop over the object, and call set recursively for each key,
* value pair. If you set raw to true, the underlying dataValues will either be set directly to the object
* passed, or used to extend dataValues, if dataValues already contain values.
*
* When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the
* association while also making sure that the proper include options have been set (from .build() or
* .findOne())
*
* If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
* entire object as changed.
*
* @param options.raw If set to true, field and virtual setters will be ignored
* @param options.reset Clear all previously set data values
*/
public set<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K], options?: SetOptions): this;
public set(keys: Partial<TModelAttributes>, options?: SetOptions): this;
public setAttributes<K extends keyof TModelAttributes>(key: K, value: TModelAttributes[K], options?: SetOptions): this;
public setAttributes(keys: Partial<TModelAttributes>, options?: SetOptions): this;
/**
* If changed is called with a string it will return a boolean indicating whether the value of that key in
* `dataValues` is different from the value in `_previousDataValues`.
*
* If changed is called without an argument, it will return an array of keys that have changed.
*
* If changed is called with two arguments, it will set the property to `dirty`.
*
* If changed is called without an argument and no keys have changed, it will return `false`.
*/
public changed<K extends keyof this>(key: K): boolean;
public changed<K extends keyof this>(key: K, dirty: boolean): void;
public changed(): false | string[];
/**
* Returns the previous value for key from `_previousDataValues`.
*/
public previous<K extends keyof this>(key: K): this[K];
/**
* Validates this instance, and if the validation passes, persists it to the database.
*
* Returns a Promise that resolves to the saved instance (or rejects with a `Sequelize.ValidationError`, which will have a property for each of the fields for which the validation failed, with the error message for that field).
*
* This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
*
* This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling `save()` will simply ignore the change that happened on the child.
*/
public save(options?: SaveOptions<TModelAttributes>): Promise<this>;
/**
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return
* the same object. This is different from doing a `find(Instance.id)`, because that would create and
* return a new instance. With this method, all references to the Instance are updated with the new data
* and no new objects are created.
*/
public reload(options?: FindOptions<TModelAttributes>): Promise<this>;
/**
* Validate the attribute of this instance according to validation rules set in the model definition.
*
* Emits null if and only if validation successful; otherwise an Error instance containing
* { field name : [error msgs] } entries.
*
* @param options.skip An array of strings. All properties that are in this array will not be validated
*/
public validate(options?: ValidationOptions): Promise<void>;
/**
* This is the same as calling `set` and then calling `save`.
*/
public update<K extends keyof this>(key: K, value: this[K], options?: InstanceUpdateOptions<TModelAttributes>): Promise<this>;
public update(keys: object, options?: InstanceUpdateOptions<TModelAttributes>): Promise<this>;
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
* either be completely deleted, or have its deletedAt timestamp set to the current time.
*/
public destroy(options?: InstanceDestroyOptions): Promise<void>;
/**
* Restore the row corresponding to this instance. Only available for paranoid models.
*/
public restore(options?: InstanceRestoreOptions): Promise<void>;
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use
* the values currently stored on the Instance. The increment is done using a
* ```sql
* SET column = column + X
* ```
* query. To get the correct value after an increment into the Instance you should do a reload.
*
* ```js
* instance.increment('number') // increment number by 1
* instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
* instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is incremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is incremented by the value given.
*/
public increment<K extends keyof TModelAttributes>(
fields: K | K[] | Partial<TModelAttributes>,
options?: IncrementDecrementOptionsWithBy<TModelAttributes>
): Promise<this>;
/**
* Decrement the value of one or more columns. This is done in the database, which means it does not use
* the values currently stored on the Instance. The decrement is done using a
* ```sql
* SET column = column - X
* ```
* query. To get the correct value after an decrement into the Instance you should do a reload.
*
* ```js
* instance.decrement('number') // decrement number by 1
* instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
* instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own
* // value
* ```
*
* @param fields If a string is provided, that column is decremented by the value of `by` given in options.
* If an array is provided, the same is true for each column.
* If and object is provided, each column is decremented by the value given
*/
public decrement<K extends keyof TModelAttributes>(
fields: K | K[] | Partial<TModelAttributes>,
options?: IncrementDecrementOptionsWithBy<TModelAttributes>
): Promise<this>;
/**
* Check whether all values of this and `other` Instance are the same
*/
public equals(other: this): boolean;
/**
* Check if this is eqaul to one of `others` by calling equals
*/
public equalsOneOf(others: this[]): boolean;
/**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all
* values gotten from the DB, and apply all custom getters.
*/
public toJSON(): object;
/**
* Helper method to determine if a instance is "soft deleted". This is
* particularly useful if the implementer renamed the deletedAt attribute to
* something different. This method requires paranoid to be enabled.
*
* Throws an error if paranoid is not enabled.
*/
public isSoftDeleted(): boolean;
}
export type ModelType = typeof Model;
// Do not switch the order of `typeof Model` and `{ new(): M }`. For
// instances created by `sequelize.define` to typecheck well, `typeof Model`
// must come first for unknown reasons.
export type ModelCtor<M extends Model> = typeof Model & { new(): M };
export type ModelDefined<S, T> = ModelCtor<Model<S, T>>;
export type ModelStatic<M extends Model> = { new(): M };
export default Model;