-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathdata-types.ts
More file actions
2867 lines (2439 loc) · 78.1 KB
/
Copy pathdata-types.ts
File metadata and controls
2867 lines (2439 loc) · 78.1 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
import {
EMPTY_ARRAY,
isPlainObject,
isString,
parseBigInt,
parseSafeInteger,
} from '@sequelize/utils';
import dayjs from 'dayjs';
import isEqual from 'lodash/isEqual';
import isObject from 'lodash/isObject';
import { Blob } from 'node:buffer';
import util from 'node:util';
import type { Class } from 'type-fest';
import { ValidationErrorItem } from '../errors';
import type { GeoJson, GeoJsonType } from '../geo-json.js';
import { assertIsGeoJson } from '../geo-json.js';
import type { ModelStatic, Rangable, RangePart } from '../model.js';
import type { Sequelize } from '../sequelize.js';
import { makeBufferFromTypedArray } from '../utils/buffer.js';
import { isValidTimeZone } from '../utils/dayjs.js';
import { doNotUseRealDataType } from '../utils/deprecations.js';
import { joinSQLFragments } from '../utils/join-sql-fragments';
import { validator as Validator } from '../utils/validator-extras';
import {
attributeTypeToSql,
dataTypeClassOrInstanceToInstance,
isDataType,
isDataTypeClass,
throwUnsupportedDataType,
} from './data-types-utils.js';
import type { AbstractDialect } from './dialect.js';
import type { TableNameWithSchema } from './query-interface.js';
// TODO: try merging "validate" & "sanitize" by making sanitize coerces the type, and if it cannot, throw a ValidationError.
// right now, they share a lot of the same logic.
// legacy support
let Moment: any;
try {
Moment = require('moment');
} catch {
/* ignore */
}
function isMoment(value: any): boolean {
return Moment?.isMoment(value) ?? false;
}
// If T is a constructor, returns the type of what `new T()` would return,
// otherwise, returns T
export type Constructed<T> = T extends abstract new () => infer Instance ? Instance : T;
export type AcceptableTypeOf<T extends DataType> =
Constructed<T> extends AbstractDataType<infer Acceptable> ? Acceptable : never;
export type DataTypeInstance = AbstractDataType<any>;
export type DataTypeClass = Class<AbstractDataType<any>>;
export type DataTypeClassOrInstance = DataTypeInstance | DataTypeClass;
export type DataType = string | DataTypeClassOrInstance;
export type NormalizedDataType = string | DataTypeInstance;
export interface BindParamOptions {
bindParam(value: unknown): string;
}
export type DataTypeUseContext =
| { model: ModelStatic; attributeName: string; sequelize: Sequelize }
| { tableName: TableNameWithSchema; columnName: string; sequelize: Sequelize };
/**
* A symbol that can be used as the key for a static property on a DataType class to uniquely identify it.
*/
export const DataTypeIdentifier = Symbol('DataTypeIdentifier');
/**
* @category DataTypes
*/
export abstract class AbstractDataType<
/** The type of value we'll accept - ie for a column of this type, we'll accept this value as user input. */
AcceptedType,
> {
/**
* This property is designed to uniquely identify the DataType.
* Do not change this value in implementation-specific dialects, or they will not be mapped to their parent DataType properly!
*
* @hidden
*/
declare static readonly [DataTypeIdentifier]: string;
static getDataTypeId(): string {
return this[DataTypeIdentifier];
}
getDataTypeId(): string {
// @ts-expect-error -- untyped constructor
return this.constructor.getDataTypeId();
}
/**
* Where this DataType is being used.
*/
usageContext: DataTypeUseContext | undefined;
#dialect: AbstractDialect | undefined;
protected _getDialect(): AbstractDialect {
if (!this.#dialect) {
throw new Error('toDialectDataType has not yet been called on this DataType');
}
return this.#dialect;
}
// TODO: Remove in v8
/**
* @hidden
*/
static get escape() {
throw new Error(
'The "escape" static property has been removed. Each DataType is responsible for escaping its value correctly.',
);
}
// TODO: Remove in v8
/**
* @hidden
*/
static get types() {
throw new Error('The "types" static property has been removed. Use getDataTypeDialectMeta.');
}
// TODO: Remove in v8
/**
* @hidden
*/
static get key() {
throw new Error('The "key" static property has been removed.');
}
// TODO: Remove in v8
/**
* @hidden
*/
get types() {
throw new Error('The "types" instance property has been removed.');
}
// TODO: Remove in v8
/**
* @hidden
*/
get key() {
throw new Error('The "key" instance property has been removed.');
}
// TODO: move to utils?
protected _construct<Constructor extends abstract new () => AbstractDataType<any>>(
...args: ConstructorParameters<Constructor>
): this {
const constructor = this.constructor as new (
..._args: ConstructorParameters<Constructor>
) => this;
return new constructor(...args);
}
areValuesEqual(value: AcceptedType, originalValue: AcceptedType): boolean {
return isEqual(value, originalValue);
}
/**
* Whether this DataType wishes to handle NULL values itself.
* This is almost exclusively used by {@link JSON} and {@link JSONB} which serialize `null` as the JSON string `'null'`.
*/
acceptsNull(): boolean {
return false;
}
/**
* Called when a value is retrieved from the Database, and its DataType is specified.
* Used to normalize values from the database.
*
* Note: It is also possible to do an initial parsing of a Database value using {@link AbstractDialect#registerDataTypeParser}.
* That normalization uses the type ID from the database instead of a Sequelize Data Type to determine which parser to use,
* and is called before this method.
*
* @param value The value to parse.
*/
parseDatabaseValue(value: unknown): unknown {
return value as AcceptedType;
}
/**
* Used to normalize a value when {@link Model#set} is called.
* That is, when a user sets a value on a Model instance.
*
* @param value
*/
sanitize(value: unknown): unknown {
return value;
}
/**
* Checks whether the JS value is compatible with (or can be converted to) the SQL data type.
* Throws if that is not the case.
*
* @param value
*/
validate(value: any): asserts value is AcceptedType {}
/**
* Escapes a value for the purposes of inlining it in a SQL query.
* The resulting value will be inlined as-is with no further escaping.
*
* @param value The value to escape.
*/
escape(value: AcceptedType): string {
const asBindValue = this.toBindableValue(value);
if (!isString(asBindValue)) {
throw new Error(
`${this.constructor.name}#stringify has been overridden to return a non-string value, so ${this.constructor.name}#escape must be implemented to handle that value correctly.`,
);
}
return this._getDialect().escapeString(asBindValue);
}
/**
* This method is called when {@link AbstractQueryGenerator} needs to add a bind parameter to a query it is building.
* This method allows for customizing both the SQL to add to the query, and convert the bind parameter value to a DB-compatible value.
*
* If you only need to prepare the bind param value, implement {@link toBindableValue} instead.
*
* This method must return the SQL to add to the query. You can obtain a bind parameter ID by calling {@link BindParamOptions#bindParam}
* with the value associated to that bind parameter.
*
* An example of a data type that requires customizing the SQL is the {@link GEOMETRY} data type.
*
* @param value The value to bind.
* @param options Options.
*/
getBindParamSql(value: AcceptedType, options: BindParamOptions): string {
// TODO: rename "options.bindParam" to "options.collectBindParam"
return options.bindParam(this.toBindableValue(value));
}
/**
* Converts a JS value to a value compatible with the connector library for this Data Type.
* Unlike {@link escape}, this value does not need to be escaped. It is passed separately to the database, which
* will handle escaping.
*
* @param value The value to convert.
*/
toBindableValue(value: AcceptedType): unknown {
return String(value);
}
toString(): string {
try {
return this.toSql();
} catch {
// best effort introspection (dialect may not be available)
return this.constructor.toString();
}
}
static toString() {
return this.name;
}
/**
* Returns a SQL declaration of this data type.
* e.g. 'VARCHAR(255)', 'TEXT', etc…
*/
abstract toSql(): string;
/**
* Override this method to emit an error or a warning if the Data Type, as it is configured, is not compatible
* with the current dialect.
*
* @param dialect The dialect using this data type.
*/
protected _checkOptionSupport(dialect: AbstractDialect) {
// use "dialect.supports" to determine base support for this DataType.
assertDataTypeSupported(dialect, this);
}
belongsToDialect(dialect: AbstractDialect): boolean {
return this.#dialect === dialect;
}
/**
* Returns this DataType, using its dialect-specific subclass.
*
* @param dialect
*/
toDialectDataType(dialect: AbstractDialect): this {
// This DataType has already been converted to a dialect-specific DataType.
if (this.#dialect === dialect) {
return this;
}
const DataTypeClass = this.constructor as Class<AbstractDataType<any>>;
// get dialect-specific implementation
const subClass = dialect.getDataTypeForDialect(DataTypeClass);
const replacement: this =
!subClass || subClass === DataTypeClass
? // optimisation: re-use instance if it doesn't belong to any dialect yet.
this.#dialect == null
? this
: this.clone()
: // there is a convention that all DataTypes must accept a single "options" parameter as one of their signatures, but it's impossible to enforce in typing
// @ts-expect-error -- see ^
(new subClass(this.options) as this);
replacement.#dialect = dialect;
replacement._checkOptionSupport(dialect);
if (this.usageContext) {
replacement.attachUsageContext(this.usageContext);
}
return replacement;
}
/**
* Returns a copy of this DataType, without usage context.
* Designed to re-use a DataType on another Model.
*/
clone(): this {
// there is a convention that all DataTypes must accept a single "options" parameter as one of their signatures, but it's impossible to enforce in typing
// @ts-expect-error -- see ^
return this._construct(this.options);
}
withUsageContext(usageContext: DataTypeUseContext): this {
const out = this.clone().attachUsageContext(usageContext);
if (this.#dialect) {
out.#dialect = this.#dialect;
}
return out;
}
/**
* @param usageContext
* @private
*/
attachUsageContext(usageContext: DataTypeUseContext): this {
if (this.usageContext && !isEqual(this.usageContext, usageContext)) {
throw new Error(
`This DataType is already attached to ${printContext(this.usageContext)}, and therefore cannot be attached to ${printContext(usageContext)}.`,
);
}
this.usageContext = Object.freeze(usageContext);
return this;
}
}
function printContext(usageContext: DataTypeUseContext): string {
if ('model' in usageContext) {
return `attribute ${usageContext.model.name}#${usageContext.attributeName}`;
}
return `column "${usageContext.tableName}"."${usageContext.columnName}"`;
}
export interface StringTypeOptions {
/**
* @default 255
*/
length?: number | undefined;
/**
* @default false
*/
binary?: boolean;
}
/**
* Represents a variable length string type.
*
* __Fallback policy:__
* - If the 'length' option is not supported by the dialect, a CHECK constraint will be added to ensure
* the value remains within the specified length.
* - If the 'binary' option is not supported by the dialect, a suitable binary type will be used instead.
* If none is available, an error will be raised instead.
*
* @example
* ```ts
* DataTypes.STRING(255)
* ```
*
* @category DataTypes
*/
export class STRING extends AbstractDataType<string | Buffer> {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'STRING';
readonly options: StringTypeOptions;
constructor(length: number, binary?: boolean);
constructor(options?: StringTypeOptions);
// we have to define the constructor overloads using tuples due to a TypeScript limitation
// https://github.com/microsoft/TypeScript/issues/29732, to play nice with classToInvokable.
/** @hidden */
constructor(
...args:
| []
| [length: number]
| [length: number, binary: boolean]
| [options: StringTypeOptions]
);
constructor(lengthOrOptions?: number | StringTypeOptions, binary?: boolean) {
super();
if (isObject(lengthOrOptions)) {
this.options = {
length: lengthOrOptions.length,
binary: lengthOrOptions.binary ?? false,
};
} else {
this.options = {
length: lengthOrOptions,
binary: binary ?? false,
};
}
}
protected _checkOptionSupport(dialect: AbstractDialect) {
if (!dialect.supports.dataTypes.COLLATE_BINARY && this.options.binary) {
throwUnsupportedDataType(dialect, 'STRING.BINARY');
}
}
toSql(): string {
// TODO: STRING should use an unlimited length type by default - https://github.com/sequelize/sequelize/issues/14259
return joinSQLFragments([
`VARCHAR(${this.options.length ?? 255})`,
this.options.binary ? 'BINARY' : '',
]);
}
validate(value: any): asserts value is string | Buffer {
if (typeof value === 'string') {
return;
}
if (!this.options.binary) {
ValidationErrorItem.throwDataTypeValidationError(
`${util.inspect(value)} is not a valid string. Only the string type is accepted for non-binary strings.`,
);
}
rejectBlobs(value);
if (Buffer.isBuffer(value)) {
return;
}
if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
return;
}
ValidationErrorItem.throwDataTypeValidationError(
`${util.inspect(value)} is not a valid binary value: Only strings, Buffer, Uint8Array and ArrayBuffer are supported.`,
);
}
get BINARY() {
return this._construct<typeof STRING>({
...this.options,
binary: true,
});
}
static get BINARY() {
return new this({ binary: true });
}
escape(value: string | Buffer): string {
if (Buffer.isBuffer(value)) {
return this._getDialect().escapeBuffer(value);
}
return this._getDialect().escapeString(value);
}
toBindableValue(value: string | Buffer): unknown {
return this.sanitize(value);
}
}
/**
* Represents a fixed length string type.
*
* __Fallback policy:__
* - If this DataType is not supported, an error will be raised.
*
* @example
* ```ts
* DataTypes.CHAR(1000)
* ```
*
* @category DataTypes
*/
export class CHAR extends STRING {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'CHAR';
protected _checkOptionSupport(dialect: AbstractDialect) {
if (!dialect.supports.dataTypes.CHAR) {
throwUnsupportedDataType(dialect, 'CHAR');
}
if (!dialect.supports.dataTypes.COLLATE_BINARY && this.options.binary) {
throwUnsupportedDataType(dialect, 'CHAR.BINARY');
}
}
toSql() {
return joinSQLFragments([
`CHAR(${this.options.length ?? 255})`,
this.options.binary ? 'BINARY' : '',
]);
}
}
const validTextLengths = ['tiny', 'medium', 'long'];
export type TextLength = 'tiny' | 'medium' | 'long';
export interface TextOptions {
length?: TextLength | undefined;
}
/**
* Represents an unlimited length string type.
*
* @example
* ```ts
* DataTypes.TEXT('tiny') // TINYTEXT
* ```
*
* @category DataTypes
*/
export class TEXT extends AbstractDataType<string> {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'TEXT';
readonly options: TextOptions;
/**
* @param lengthOrOptions could be tiny, medium, long.
*/
constructor(lengthOrOptions?: TextLength | TextOptions) {
super();
const length = (
typeof lengthOrOptions === 'object' ? lengthOrOptions.length : lengthOrOptions
)?.toLowerCase();
if (length != null && !validTextLengths.includes(length)) {
throw new TypeError(
`If specified, the "length" option must be one of: ${validTextLengths.join(', ')}`,
);
}
this.options = {
length: length as TextLength,
};
}
toSql(): string {
switch (this.options.length) {
case 'tiny':
return 'TINYTEXT';
case 'medium':
return 'MEDIUMTEXT';
case 'long':
return 'LONGTEXT';
default:
return 'TEXT';
}
}
validate(value: any): asserts value is string {
if (typeof value !== 'string') {
ValidationErrorItem.throwDataTypeValidationError(
util.format('%s is not a valid string', value),
);
}
}
}
/**
* An unlimited length case-insensitive text column.
* Original case is preserved but acts case-insensitive when comparing values (such as when finding or unique constraints).
* Only available in Postgres and SQLite.
*
* __Fallback policy:__
* - If this DataType is not supported, and no case-insensitive text alternative exists, an error will be raised.
*
* @example
* ```ts
* DataTypes.CITEXT
* ```
*
* @category DataTypes
*/
export class CITEXT extends AbstractDataType<string> {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'CITEXT';
toSql(): string {
return 'CITEXT';
}
protected _checkOptionSupport(dialect: AbstractDialect) {
if (!dialect.supports.dataTypes.CITEXT) {
throwUnsupportedDataType(dialect, 'case-insensitive text (CITEXT)');
}
}
validate(value: any): asserts value is string {
if (typeof value !== 'string') {
ValidationErrorItem.throwDataTypeValidationError(
util.format('%s is not a valid string', value),
);
}
}
}
export interface NumberOptions {
/**
* Pad the value with zeros to the specified length.
*
* Currently useless for types that are returned as JS BigInts or JS Numbers.
*/
// TODO: When a number is 0-filled, return it as a string instead of number or bigint
zerofill?: boolean | undefined;
/**
* Is unsigned?
*/
unsigned?: boolean | undefined;
}
export interface IntegerOptions extends NumberOptions {
/**
* In MariaDB: When specified, and {@link zerofill} is set, the returned value will be padded with zeros to the specified length.
* In MySQL: This option is ignored.
* This option is supported in no other dialect.
* Currently useless for types that are returned as JS BigInts or JS Numbers.
*/
length?: number;
}
export interface DecimalNumberOptions extends NumberOptions {
/**
* Total number of digits.
*
* {@link DecimalNumberOptions#scale} must be specified if precision is specified.
*/
precision?: number | undefined;
/**
* Count of decimal digits in the fractional part.
*
* {@link DecimalNumberOptions#precision} must be specified if scale is specified.
*/
scale?: number | undefined;
}
type AcceptedNumber = number | bigint | boolean | string | null;
/**
* Base number type which is used to build other types
*/
export class BaseNumberDataType<
Options extends NumberOptions = NumberOptions,
> extends AbstractDataType<AcceptedNumber> {
readonly options: Options;
constructor(options?: Options) {
super();
// @ts-expect-error -- "options" is always optional, but we can't tell TypeScript that all properties of the object must be optional
this.options = { ...options };
}
protected getNumberSqlTypeName(): string {
throw new Error(`getNumberSqlTypeName has not been implemented in ${this.constructor.name}`);
}
toSql(): string {
let result: string = this.getNumberSqlTypeName();
if (this.options.unsigned && this._supportsNativeUnsigned(this._getDialect())) {
result += ' UNSIGNED';
}
if (this.options.zerofill) {
result += ' ZEROFILL';
}
return result;
}
protected _supportsNativeUnsigned(_dialect: AbstractDialect) {
return false;
}
validate(value: any): asserts value is number {
if (typeof value === 'number' && Number.isInteger(value) && !Number.isSafeInteger(value)) {
ValidationErrorItem.throwDataTypeValidationError(
util.format(
`${this.constructor.name} received an integer % that is not a safely represented using the JavaScript number type. Use a JavaScript bigint or a string instead.`,
value,
),
);
}
if (!Validator.isFloat(String(value))) {
ValidationErrorItem.throwDataTypeValidationError(
`${util.inspect(value)} is not a valid ${this.toString().toLowerCase()}`,
);
}
}
escape(value: AcceptedNumber): string {
return String(this.toBindableValue(value));
}
toBindableValue(num: AcceptedNumber): string | number {
// This should be unnecessary but since this directly returns the passed string its worth the added validation.
this.validate(num);
if (Number.isNaN(num)) {
return 'NaN';
}
if (num === Number.NEGATIVE_INFINITY || num === Number.POSITIVE_INFINITY) {
const sign = num < 0 ? '-' : '';
return `${sign}Infinity`;
}
return num;
}
getBindParamSql(value: AcceptedNumber, options: BindParamOptions): string {
return options.bindParam(value);
}
get UNSIGNED(): this {
return this._construct<typeof BaseNumberDataType>({ ...this.options, unsigned: true });
}
get ZEROFILL(): this {
return this._construct<typeof BaseNumberDataType>({ ...this.options, zerofill: true });
}
static get UNSIGNED() {
return new this({ unsigned: true });
}
static get ZEROFILL() {
return new this({ zerofill: true });
}
}
export class BaseIntegerDataType extends BaseNumberDataType<IntegerOptions> {
constructor(optionsOrLength?: number | Readonly<IntegerOptions>) {
if (typeof optionsOrLength === 'number') {
super({ length: optionsOrLength });
} else {
super(optionsOrLength ?? {});
}
}
validate(value: unknown) {
super.validate(value);
if (typeof value === 'number' && !Number.isInteger(value)) {
ValidationErrorItem.throwDataTypeValidationError(
`${util.inspect(value)} is not a valid ${this.toString().toLowerCase()}`,
);
}
if (!Validator.isInt(String(value))) {
ValidationErrorItem.throwDataTypeValidationError(
`${util.inspect(value)} is not a valid ${this.toString().toLowerCase()}`,
);
}
}
sanitize(value: unknown): unknown {
if (typeof value === 'string' || typeof value === 'bigint') {
const out = parseSafeInteger(value);
// let validate sort this validation instead
if (out === null) {
return value;
}
return out;
}
return value;
}
parseDatabaseValue(value: unknown): unknown {
return this.sanitize(value);
}
protected _checkOptionSupport(dialect: AbstractDialect) {
super._checkOptionSupport(dialect);
if (this.options.zerofill && !dialect.supports.dataTypes.INTS.zerofill) {
throwUnsupportedDataType(dialect, `${this.getDataTypeId()}.ZEROFILL`);
}
}
protected _supportsNativeUnsigned(_dialect: AbstractDialect): boolean {
return _dialect.supports.dataTypes.INTS.unsigned;
}
toSql(): string {
let result: string = this.getNumberSqlTypeName();
if (this.options.length != null) {
result += `(${this.options.length})`;
}
if (this.options.unsigned && this._supportsNativeUnsigned(this._getDialect())) {
result += ' UNSIGNED';
}
if (this.options.zerofill) {
result += ' ZEROFILL';
}
return result;
}
}
/**
* An 8-bit integer.
*
* __Fallback policy:__
* - If this type or its unsigned option is unsupported by the dialect, it will be replaced by a SMALLINT or greater,
* with a CHECK constraint to ensure the value is withing the bounds of an 8-bit integer.
* - If the zerofill option is unsupported by the dialect, an error will be raised.
* - If the length option is unsupported by the dialect, it will be discarded.
*
* @example
* ```ts
* DataTypes.TINYINT
* ```
*
* @category DataTypes
*/
export class TINYINT extends BaseIntegerDataType {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'TINYINT';
protected getNumberSqlTypeName(): string {
return 'TINYINT';
}
}
/**
* A 16-bit integer.
*
* __Fallback policy:__
* - If this type or its unsigned option is unsupported by the dialect, it will be replaced by a MEDIUMINT or greater,
* with a CHECK constraint to ensure the value is withing the bounds of an 16-bit integer.
* - If the zerofill option is unsupported by the dialect, an error will be raised.
* - If the length option is unsupported by the dialect, it will be discarded.
*
* @example
* ```ts
* DataTypes.SMALLINT
* ```
*
* @category DataTypes
*/
export class SMALLINT extends BaseIntegerDataType {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'SMALLINT';
protected getNumberSqlTypeName(): string {
return 'SMALLINT';
}
}
/**
* A 24-bit integer.
*
* __Fallback policy:__
* - If this type or its unsigned option is unsupported by the dialect, it will be replaced by a INTEGER (32 bits) or greater,
* with a CHECK constraint to ensure the value is withing the bounds of an 32-bit integer.
* - If the zerofill option is unsupported by the dialect, an error will be raised.
* - If the length option is unsupported by the dialect, it will be discarded.
*
* @example
* ```ts
* DataTypes.MEDIUMINT
* ```
*
* @category DataTypes
*/
export class MEDIUMINT extends BaseIntegerDataType {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'MEDIUMINT';
protected getNumberSqlTypeName(): string {
return 'MEDIUMINT';
}
}
/**
* A 32-bit integer.
*
* __Fallback policy:__
* - When this type or its unsigned option is unsupported by the dialect, it will be replaced by a BIGINT,
* with a CHECK constraint to ensure the value is withing the bounds of an 32-bit integer.
* - If the zerofill option is unsupported by the dialect, an error will be raised.
* - If the length option is unsupported by the dialect, it will be discarded.
*
* @example
* ```ts
* DataTypes.INTEGER
* ```
*
* @category DataTypes
*/
export class INTEGER extends BaseIntegerDataType {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'INTEGER';
protected getNumberSqlTypeName(): string {
return 'INTEGER';
}
}
/**
* A 64-bit integer.
*
* __Fallback policy:__
* - If this type or its unsigned option is unsupported by the dialect, an error will be raised.
* - If the zerofill option is unsupported by the dialect, an error will be raised.
* - If the length option is unsupported by the dialect, it will be discarded.
*
* @example
* ```ts
* DataTypes.BIGINT
* ```
*
* @category DataTypes
*/
export class BIGINT extends BaseIntegerDataType {
/** @hidden */
static readonly [DataTypeIdentifier]: string = 'BIGINT';
protected getNumberSqlTypeName(): string {
return 'BIGINT';
}
protected _checkOptionSupport(dialect: AbstractDialect) {
super._checkOptionSupport(dialect);
if (!dialect.supports.dataTypes.BIGINT) {
throwUnsupportedDataType(dialect, 'BIGINT');
}
if (this.options.unsigned && !this._supportsNativeUnsigned(dialect)) {
throwUnsupportedDataType(dialect, `${this.getDataTypeId()}.UNSIGNED`);
}
}
sanitize(value: AcceptedNumber): AcceptedNumber {
if (typeof value === 'bigint') {
return value;
}
if (typeof value !== 'string' && typeof value !== 'number') {
// let validate() handle this instead
return value;
}
// TODO: Breaking Change: Return a BigInt by default - https://github.com/sequelize/sequelize/issues/14296
return String(parseBigInt(value));
}
}