sequelize-typescript-generator 13.1.0 → 13.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +290 -20
- package/build/bin/cli.js +3 -3
- package/build/bin/utils.d.ts +13 -0
- package/build/bin/utils.js +25 -0
- package/build/builders/ModelBuilder.d.ts +4 -2
- package/build/builders/ModelBuilder.js +143 -19
- package/build/builders/NativeModelRenderer.d.ts +4 -3
- package/build/builders/NativeModelRenderer.js +31 -11
- package/build/builders/enumSupport.d.ts +104 -0
- package/build/builders/enumSupport.js +323 -0
- package/build/builders/generatedFile.d.ts +2 -1
- package/build/builders/generatedFile.js +7 -1
- package/build/builders/jsonSupport.d.ts +10 -3
- package/build/builders/jsonSupport.js +10 -3
- package/build/builders/nativeWiring.d.ts +2 -1
- package/build/builders/nativeWiring.js +9 -3
- package/build/builders/sharedTypesIndexExports.d.ts +11 -0
- package/build/builders/sharedTypesIndexExports.js +15 -0
- package/build/builders/typeOverrides.d.ts +30 -0
- package/build/builders/typeOverrides.js +93 -0
- package/build/builders/typeOverridesParser.d.ts +48 -0
- package/build/builders/typeOverridesParser.js +305 -0
- package/build/builders/unmappedTypes.d.ts +50 -0
- package/build/builders/unmappedTypes.js +62 -0
- package/build/builders/utils.d.ts +7 -0
- package/build/builders/utils.js +12 -0
- package/build/config/IConfig.d.ts +22 -0
- package/build/dialects/Dialect.d.ts +56 -3
- package/build/dialects/DialectMSSQL.d.ts +2 -2
- package/build/dialects/DialectMSSQL.js +1 -6
- package/build/dialects/DialectMariaDB.d.ts +2 -2
- package/build/dialects/DialectMariaDB.js +1 -6
- package/build/dialects/DialectMySQL.d.ts +2 -2
- package/build/dialects/DialectMySQL.js +1 -6
- package/build/dialects/DialectPostgres.d.ts +33 -2
- package/build/dialects/DialectPostgres.js +77 -10
- package/build/dialects/DialectSQLite.d.ts +2 -2
- package/build/dialects/DialectSQLite.js +1 -6
- package/build/dialects/dataTypes.d.ts +8 -0
- package/build/dialects/dataTypes.js +32 -4
- package/build/dialects/utils.d.ts +0 -6
- package/build/dialects/utils.js +0 -10
- package/build/index.d.ts +2 -2
- package/package.json +3 -3
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import * as ts from 'typescript';
|
|
3
|
+
import { isColumnDataTypeKey } from '../dialects/dataTypes.js';
|
|
4
|
+
/**
|
|
5
|
+
* Prefix of every type overrides validation error message.
|
|
6
|
+
*/
|
|
7
|
+
export const VALIDATION_ERROR_PREFIX = '[ValidationError]';
|
|
8
|
+
const TYPE_OVERRIDE_SECTIONS = ['types', 'columns'];
|
|
9
|
+
const TYPE_OVERRIDE_FIELDS = ['tsType', 'dataType'];
|
|
10
|
+
/**
|
|
11
|
+
* Allowed number of dot-separated key segments per section: `<type>` or
|
|
12
|
+
* `<schema>.<type>`; `<table>.<column>` or `<schema>.<table>.<column>`.
|
|
13
|
+
*/
|
|
14
|
+
const KEY_SEGMENT_RANGE_BY_SECTION = {
|
|
15
|
+
types: { min: 1, max: 2 },
|
|
16
|
+
columns: { min: 2, max: 3 },
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Namespaces accepted as a prefix of a data type identifier.
|
|
20
|
+
*/
|
|
21
|
+
const DATA_TYPE_PREFIXES = ['DataTypes', 'DataType'];
|
|
22
|
+
/**
|
|
23
|
+
* Name of the type alias the TypeScript type text is parsed into.
|
|
24
|
+
*/
|
|
25
|
+
const TS_TYPE_ALIAS_NAME = '__TypeOverride';
|
|
26
|
+
/**
|
|
27
|
+
* Build a type overrides validation error.
|
|
28
|
+
* @param {string} message
|
|
29
|
+
* @returns {Error}
|
|
30
|
+
*/
|
|
31
|
+
const validationError = (message) => new Error(`${VALIDATION_ERROR_PREFIX} Type overrides: ${message}`);
|
|
32
|
+
/**
|
|
33
|
+
* Label of a type override entry used in messages, e.g. `columns["users.status"]`.
|
|
34
|
+
* @param {TypeOverrideSection} section
|
|
35
|
+
* @param {string} key
|
|
36
|
+
* @returns {string}
|
|
37
|
+
*/
|
|
38
|
+
export const formatTypeOverrideLabel = (section, key) => `${section}[${JSON.stringify(key)}]`;
|
|
39
|
+
/**
|
|
40
|
+
* Type guard for a plain JSON object (not null, not an array).
|
|
41
|
+
* @param {unknown} value
|
|
42
|
+
* @returns {boolean}
|
|
43
|
+
*/
|
|
44
|
+
const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
45
|
+
/**
|
|
46
|
+
* Report the syntactic diagnostics of a source text.
|
|
47
|
+
* @param {string} text
|
|
48
|
+
* @returns {boolean}
|
|
49
|
+
*/
|
|
50
|
+
const hasSyntaxErrors = (text) => {
|
|
51
|
+
const { diagnostics } = ts.transpileModule(text, { reportDiagnostics: true });
|
|
52
|
+
return (diagnostics ?? []).some(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Parse a source text into its statements, or undefined when it has syntax errors.
|
|
56
|
+
* @param {string} text
|
|
57
|
+
* @returns {ts.NodeArray<ts.Statement> | undefined}
|
|
58
|
+
*/
|
|
59
|
+
const parseStatements = (text) => {
|
|
60
|
+
if (hasSyntaxErrors(text)) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
return ts.createSourceFile('typeOverride.ts', text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS).statements;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Detach a parsed node and all its descendants from their source text by giving
|
|
67
|
+
* them synthesized positions, so the printer renders them from the nodes alone in
|
|
68
|
+
* any source file.
|
|
69
|
+
* @param {T} node
|
|
70
|
+
* @returns {T}
|
|
71
|
+
*/
|
|
72
|
+
const synthesizeNode = (node) => {
|
|
73
|
+
ts.forEachChild(node, child => {
|
|
74
|
+
synthesizeNode(child);
|
|
75
|
+
});
|
|
76
|
+
return ts.setTextRange(node, { pos: -1, end: -1 });
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Parse the TypeScript type text of an override into a type node.
|
|
80
|
+
* @param {string} text
|
|
81
|
+
* @param {string} label
|
|
82
|
+
* @returns {ts.TypeNode}
|
|
83
|
+
*/
|
|
84
|
+
const parseTsType = (text, label) => {
|
|
85
|
+
const fail = () => validationError(`${label}.tsType is not a valid TypeScript type: ${JSON.stringify(text)}`);
|
|
86
|
+
if (text.trim() === '') {
|
|
87
|
+
throw fail();
|
|
88
|
+
}
|
|
89
|
+
const statements = parseStatements(`type ${TS_TYPE_ALIAS_NAME} = ${text};`);
|
|
90
|
+
if (!statements || statements.length !== 1) {
|
|
91
|
+
throw fail();
|
|
92
|
+
}
|
|
93
|
+
const [statement] = statements;
|
|
94
|
+
if (!ts.isTypeAliasDeclaration(statement)) {
|
|
95
|
+
throw fail();
|
|
96
|
+
}
|
|
97
|
+
return synthesizeNode(statement.type);
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Resolve the DataTypes key named by an identifier or a `DataTypes.`/`DataType.`
|
|
101
|
+
* property access, or undefined for any other expression.
|
|
102
|
+
* @param {ts.Expression} expression
|
|
103
|
+
* @returns {string | undefined}
|
|
104
|
+
*/
|
|
105
|
+
const resolveDataTypeName = (expression) => {
|
|
106
|
+
if (ts.isIdentifier(expression)) {
|
|
107
|
+
return expression.text;
|
|
108
|
+
}
|
|
109
|
+
if (ts.isPropertyAccessExpression(expression) &&
|
|
110
|
+
ts.isIdentifier(expression.expression) &&
|
|
111
|
+
DATA_TYPE_PREFIXES.includes(expression.expression.text) &&
|
|
112
|
+
ts.isIdentifier(expression.name)) {
|
|
113
|
+
return expression.name.text;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Convert an accepted data type expression into a format-neutral data type.
|
|
119
|
+
* @param {ts.Expression} expression
|
|
120
|
+
* @param {(reason: string) => Error} fail
|
|
121
|
+
* @returns {ISequelizeDataType}
|
|
122
|
+
*/
|
|
123
|
+
const convertDataTypeExpression = (expression, fail) => {
|
|
124
|
+
const callee = ts.isCallExpression(expression) ? expression.expression : expression;
|
|
125
|
+
const name = resolveDataTypeName(callee);
|
|
126
|
+
if (name === undefined) {
|
|
127
|
+
throw fail('only data type identifiers, calls, and string or number literals are allowed');
|
|
128
|
+
}
|
|
129
|
+
if (!isColumnDataTypeKey(name)) {
|
|
130
|
+
throw fail(`unknown data type ${JSON.stringify(name)}`);
|
|
131
|
+
}
|
|
132
|
+
if (!ts.isCallExpression(expression)) {
|
|
133
|
+
return { key: name, args: [] };
|
|
134
|
+
}
|
|
135
|
+
if (expression.typeArguments || expression.questionDotToken) {
|
|
136
|
+
throw fail('only data type identifiers, calls, and string or number literals are allowed');
|
|
137
|
+
}
|
|
138
|
+
const args = expression.arguments.map(argument => {
|
|
139
|
+
if (ts.isStringLiteral(argument)) {
|
|
140
|
+
return argument.text;
|
|
141
|
+
}
|
|
142
|
+
if (ts.isNumericLiteral(argument)) {
|
|
143
|
+
return Number(argument.text);
|
|
144
|
+
}
|
|
145
|
+
return convertDataTypeExpression(argument, fail);
|
|
146
|
+
});
|
|
147
|
+
return { key: name, args };
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Parse the Sequelize data type expression of an override.
|
|
151
|
+
* @param {string} text
|
|
152
|
+
* @param {string} label
|
|
153
|
+
* @returns {ISequelizeDataType}
|
|
154
|
+
*/
|
|
155
|
+
const parseDataType = (text, label) => {
|
|
156
|
+
const fail = (reason) => validationError(`${label}.dataType ${JSON.stringify(text)} is not a valid data type expression: ${reason}`);
|
|
157
|
+
const statements = parseStatements(text);
|
|
158
|
+
if (!statements) {
|
|
159
|
+
throw fail('it does not parse');
|
|
160
|
+
}
|
|
161
|
+
if (statements.length !== 1) {
|
|
162
|
+
throw fail('expected a single expression');
|
|
163
|
+
}
|
|
164
|
+
const [statement] = statements;
|
|
165
|
+
if (!ts.isExpressionStatement(statement)) {
|
|
166
|
+
throw fail('expected a single expression');
|
|
167
|
+
}
|
|
168
|
+
return convertDataTypeExpression(statement.expression, fail);
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Validate the key of an entry and return its lower-cased matching form.
|
|
172
|
+
* @param {TypeOverrideSection} section
|
|
173
|
+
* @param {string} key
|
|
174
|
+
* @returns {string}
|
|
175
|
+
*/
|
|
176
|
+
const normalizeKey = (section, key) => {
|
|
177
|
+
const segments = key.split('.');
|
|
178
|
+
const { min, max } = KEY_SEGMENT_RANGE_BY_SECTION[section];
|
|
179
|
+
const expected = section === 'types'
|
|
180
|
+
? '"<type>" or "<schema>.<type>"'
|
|
181
|
+
: '"<table>.<column>" or "<schema>.<table>.<column>"';
|
|
182
|
+
if (segments.length < min || segments.length > max || segments.some(segment => segment.trim() === '')) {
|
|
183
|
+
throw validationError(`${formatTypeOverrideLabel(section, key)} has a malformed key: expected ${expected}`);
|
|
184
|
+
}
|
|
185
|
+
return segments.join('.').toLowerCase();
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Validate one entry of a section.
|
|
189
|
+
* @param {TypeOverrideSection} section
|
|
190
|
+
* @param {string} key
|
|
191
|
+
* @param {unknown} entry
|
|
192
|
+
* @returns {IParsedTypeOverride}
|
|
193
|
+
*/
|
|
194
|
+
const parseEntry = (section, key, entry) => {
|
|
195
|
+
const label = formatTypeOverrideLabel(section, key);
|
|
196
|
+
if (!isPlainObject(entry)) {
|
|
197
|
+
throw validationError(`${label} must be an object`);
|
|
198
|
+
}
|
|
199
|
+
const unknownField = Object.keys(entry).find(field => !TYPE_OVERRIDE_FIELDS.some(knownField => knownField === field));
|
|
200
|
+
if (unknownField !== undefined) {
|
|
201
|
+
throw validationError(`${label} has an unknown field ${JSON.stringify(unknownField)}: expected tsType or dataType`);
|
|
202
|
+
}
|
|
203
|
+
const { tsType, dataType } = entry;
|
|
204
|
+
if (tsType === undefined && dataType === undefined) {
|
|
205
|
+
throw validationError(`${label} must set tsType, dataType or both`);
|
|
206
|
+
}
|
|
207
|
+
if (tsType !== undefined && typeof tsType !== 'string') {
|
|
208
|
+
throw validationError(`${label}.tsType must be a string`);
|
|
209
|
+
}
|
|
210
|
+
if (dataType !== undefined && typeof dataType !== 'string') {
|
|
211
|
+
throw validationError(`${label}.dataType must be a string`);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
section,
|
|
215
|
+
key,
|
|
216
|
+
...tsType !== undefined && { tsType: parseTsType(tsType, label) },
|
|
217
|
+
...dataType !== undefined && { dataType: parseDataType(dataType, label) },
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
/**
|
|
221
|
+
* Validate one section and index its entries by lower-cased key.
|
|
222
|
+
* @param {TypeOverrideSection} section
|
|
223
|
+
* @param {unknown} value
|
|
224
|
+
* @returns {Map<string, IParsedTypeOverride>}
|
|
225
|
+
*/
|
|
226
|
+
const parseSection = (section, value) => {
|
|
227
|
+
const entries = new Map();
|
|
228
|
+
if (value === undefined) {
|
|
229
|
+
return entries;
|
|
230
|
+
}
|
|
231
|
+
if (!isPlainObject(value)) {
|
|
232
|
+
throw validationError(`${section} must be an object`);
|
|
233
|
+
}
|
|
234
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
235
|
+
const normalizedKey = normalizeKey(section, key);
|
|
236
|
+
const existing = entries.get(normalizedKey);
|
|
237
|
+
if (existing) {
|
|
238
|
+
throw validationError(`${formatTypeOverrideLabel(section, key)} is a duplicate of ` +
|
|
239
|
+
`${formatTypeOverrideLabel(section, existing.key)}: keys match case-insensitively`);
|
|
240
|
+
}
|
|
241
|
+
entries.set(normalizedKey, parseEntry(section, key, entry));
|
|
242
|
+
}
|
|
243
|
+
return entries;
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Validate type overrides of unknown shape.
|
|
247
|
+
* @param {unknown} value
|
|
248
|
+
* @returns {IParsedTypeOverrides}
|
|
249
|
+
*/
|
|
250
|
+
export const parseTypeOverrides = (value) => {
|
|
251
|
+
if (!isPlainObject(value)) {
|
|
252
|
+
throw validationError('the root must be an object with optional "types" and "columns" sections');
|
|
253
|
+
}
|
|
254
|
+
const unknownSection = Object.keys(value).find(key => !TYPE_OVERRIDE_SECTIONS.some(section => section === key));
|
|
255
|
+
if (unknownSection !== undefined) {
|
|
256
|
+
throw validationError(`unknown section ${JSON.stringify(unknownSection)}: expected "types" or "columns"`);
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
types: parseSection('types', value.types),
|
|
260
|
+
columns: parseSection('columns', value.columns),
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Read and parse the JSON content of a type overrides file.
|
|
265
|
+
* @param {string} filePath
|
|
266
|
+
* @returns {Promise<unknown>}
|
|
267
|
+
*/
|
|
268
|
+
const readTypeOverridesFile = async (filePath) => {
|
|
269
|
+
let content;
|
|
270
|
+
try {
|
|
271
|
+
content = await fs.readFile(filePath, 'utf8');
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
throw new Error(`${VALIDATION_ERROR_PREFIX} Type overrides file '${filePath}' cannot be read`, { cause: err });
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
const parsed = JSON.parse(content);
|
|
278
|
+
return parsed;
|
|
279
|
+
}
|
|
280
|
+
catch (err) {
|
|
281
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
282
|
+
throw new Error(`${VALIDATION_ERROR_PREFIX} Type overrides file '${filePath}' is not valid JSON: ${reason}`, { cause: err });
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
/**
|
|
286
|
+
* Load and validate the type overrides configured in the metadata options, from
|
|
287
|
+
* either the type overrides file or the programmatic `typeOverrides`. Returns
|
|
288
|
+
* undefined when neither is set.
|
|
289
|
+
* @param {IConfigMetadata | undefined} metadata
|
|
290
|
+
* @returns {Promise<IParsedTypeOverrides | undefined>}
|
|
291
|
+
*/
|
|
292
|
+
export const loadTypeOverrides = async (metadata) => {
|
|
293
|
+
const filePath = metadata?.typeOverridesFile;
|
|
294
|
+
const typeOverrides = metadata?.typeOverrides;
|
|
295
|
+
if (filePath !== undefined && typeOverrides !== undefined) {
|
|
296
|
+
throw new Error(`${VALIDATION_ERROR_PREFIX} Set either typeOverridesFile or typeOverrides, not both`);
|
|
297
|
+
}
|
|
298
|
+
if (filePath !== undefined) {
|
|
299
|
+
return parseTypeOverrides(await readTypeOverridesFile(filePath));
|
|
300
|
+
}
|
|
301
|
+
if (typeOverrides !== undefined) {
|
|
302
|
+
return parseTypeOverrides(typeOverrides);
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Format } from '../config/format.js';
|
|
2
|
+
import type { Dialect, IColumnMetadata, ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
|
|
3
|
+
/**
|
|
4
|
+
* TypeScript type given to a column with an unmapped type, per output format.
|
|
5
|
+
*/
|
|
6
|
+
export declare const UNMAPPED_TS_TYPE_BY_FORMAT: {
|
|
7
|
+
native: string;
|
|
8
|
+
decorators: string;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* A column whose database type has no TypeScript type or no Sequelize data type
|
|
12
|
+
* mapping in the dialect, with the table it belongs to.
|
|
13
|
+
*/
|
|
14
|
+
export interface IUnmappedColumn {
|
|
15
|
+
table: ITableMetadata;
|
|
16
|
+
column: IColumnMetadata;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Report whether a column has an unmapped type: no type override matches it, it
|
|
20
|
+
* is neither a JSON column nor a database enum column, and the dialect maps its
|
|
21
|
+
* database type to no TypeScript type or to no Sequelize data type.
|
|
22
|
+
* @param {IColumnMetadata} column
|
|
23
|
+
* @param {Dialect} dialect
|
|
24
|
+
* @returns {boolean}
|
|
25
|
+
*/
|
|
26
|
+
export declare const isUnmappedColumn: (column: IColumnMetadata, dialect: Dialect) => boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Collect every column with an unmapped type, in table and column order.
|
|
29
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
30
|
+
* @param {Dialect} dialect
|
|
31
|
+
* @returns {IUnmappedColumn[]}
|
|
32
|
+
*/
|
|
33
|
+
export declare const findUnmappedColumns: (tablesMetadata: ITablesMetadata, dialect: Dialect) => IUnmappedColumn[];
|
|
34
|
+
/**
|
|
35
|
+
* Build the warning for a column with an unmapped type, naming the TypeScript
|
|
36
|
+
* type the column receives in the given format.
|
|
37
|
+
* @param {IUnmappedColumn} unmappedColumn
|
|
38
|
+
* @param {Dialect} dialect
|
|
39
|
+
* @param {Format} format
|
|
40
|
+
* @returns {string}
|
|
41
|
+
*/
|
|
42
|
+
export declare const buildUnmappedTypeWarning: (unmappedColumn: IUnmappedColumn, dialect: Dialect, format: Format) => string;
|
|
43
|
+
/**
|
|
44
|
+
* Warn once for every column with an unmapped type.
|
|
45
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
46
|
+
* @param {Dialect} dialect
|
|
47
|
+
* @param {Format} format
|
|
48
|
+
* @returns {void}
|
|
49
|
+
*/
|
|
50
|
+
export declare const warnUnmappedTypes: (tablesMetadata: ITablesMetadata, dialect: Dialect, format: Format) => void;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScript type given to a column with an unmapped type, per output format.
|
|
3
|
+
*/
|
|
4
|
+
export const UNMAPPED_TS_TYPE_BY_FORMAT = {
|
|
5
|
+
native: 'unknown',
|
|
6
|
+
decorators: 'any',
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Report whether a column has an unmapped type: no type override matches it, it
|
|
10
|
+
* is neither a JSON column nor a database enum column, and the dialect maps its
|
|
11
|
+
* database type to no TypeScript type or to no Sequelize data type.
|
|
12
|
+
* @param {IColumnMetadata} column
|
|
13
|
+
* @param {Dialect} dialect
|
|
14
|
+
* @returns {boolean}
|
|
15
|
+
*/
|
|
16
|
+
export const isUnmappedColumn = (column, dialect) => column.typeOverride === undefined &&
|
|
17
|
+
!column.isJson &&
|
|
18
|
+
column.enumType === undefined && (dialect.mapDbTypeToJs(column.type) === undefined || column.sequelizeType === undefined);
|
|
19
|
+
/**
|
|
20
|
+
* Collect every column with an unmapped type, in table and column order.
|
|
21
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
22
|
+
* @param {Dialect} dialect
|
|
23
|
+
* @returns {IUnmappedColumn[]}
|
|
24
|
+
*/
|
|
25
|
+
export const findUnmappedColumns = (tablesMetadata, dialect) => Object.values(tablesMetadata).flatMap(table => Object.values(table.columns)
|
|
26
|
+
.filter(column => isUnmappedColumn(column, dialect))
|
|
27
|
+
.map(column => ({ table, column })));
|
|
28
|
+
/**
|
|
29
|
+
* Qualified database name of a column: `schema.table.column`, or
|
|
30
|
+
* `table.column` when the table has no schema.
|
|
31
|
+
* @param {IUnmappedColumn} unmappedColumn
|
|
32
|
+
* @returns {string}
|
|
33
|
+
*/
|
|
34
|
+
const buildQualifiedColumnName = ({ table, column }) => [table.schema, table.originName, column.originName]
|
|
35
|
+
.filter(part => part !== undefined && part !== '')
|
|
36
|
+
.join('.');
|
|
37
|
+
/**
|
|
38
|
+
* Build the warning for a column with an unmapped type, naming the TypeScript
|
|
39
|
+
* type the column receives in the given format.
|
|
40
|
+
* @param {IUnmappedColumn} unmappedColumn
|
|
41
|
+
* @param {Dialect} dialect
|
|
42
|
+
* @param {Format} format
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export const buildUnmappedTypeWarning = (unmappedColumn, dialect, format) => {
|
|
46
|
+
const { type } = unmappedColumn.column;
|
|
47
|
+
const tsType = dialect.mapDbTypeToJs(type) ?? UNMAPPED_TS_TYPE_BY_FORMAT[format];
|
|
48
|
+
return `Unmapped type '${type}' for column ${buildQualifiedColumnName(unmappedColumn)}: ` +
|
|
49
|
+
`typed as '${tsType}'. Declare a type override with --type-overrides-file to set its type.`;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Warn once for every column with an unmapped type.
|
|
53
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
54
|
+
* @param {Dialect} dialect
|
|
55
|
+
* @param {Format} format
|
|
56
|
+
* @returns {void}
|
|
57
|
+
*/
|
|
58
|
+
export const warnUnmappedTypes = (tablesMetadata, dialect, format) => {
|
|
59
|
+
for (const unmappedColumn of findUnmappedColumns(tablesMetadata, dialect)) {
|
|
60
|
+
console.warn('[WARNING]', buildUnmappedTypeWarning(unmappedColumn, dialect, format));
|
|
61
|
+
}
|
|
62
|
+
};
|
|
@@ -111,6 +111,13 @@ export declare const buildDataTypeExpression: (dataType: ISequelizeDataType, nam
|
|
|
111
111
|
* @returns {ts.ExportDeclaration}
|
|
112
112
|
*/
|
|
113
113
|
export declare const generateIndexExport: (modelFileName: string) => ts.ExportDeclaration;
|
|
114
|
+
/**
|
|
115
|
+
* Generate the type-only re-export of a shared type file for the index file,
|
|
116
|
+
* e.g. `export type * from "./enums";`
|
|
117
|
+
* @param {string} fileBaseName
|
|
118
|
+
* @returns {ts.ExportDeclaration}
|
|
119
|
+
*/
|
|
120
|
+
export declare const generateTypeOnlyIndexExport: (fileBaseName: string) => ts.ExportDeclaration;
|
|
114
121
|
/**
|
|
115
122
|
* Generate object literal decorator
|
|
116
123
|
* @param {string} decoratorIdentifier
|
package/build/builders/utils.js
CHANGED
|
@@ -203,6 +203,15 @@ export const buildDataTypeExpression = (dataType, namespace) => {
|
|
|
203
203
|
export const generateIndexExport = (modelFileName) => {
|
|
204
204
|
return ts.factory.createExportDeclaration(undefined, false, undefined, ts.factory.createStringLiteral(`./${modelFileName}`));
|
|
205
205
|
};
|
|
206
|
+
/**
|
|
207
|
+
* Generate the type-only re-export of a shared type file for the index file,
|
|
208
|
+
* e.g. `export type * from "./enums";`
|
|
209
|
+
* @param {string} fileBaseName
|
|
210
|
+
* @returns {ts.ExportDeclaration}
|
|
211
|
+
*/
|
|
212
|
+
export const generateTypeOnlyIndexExport = (fileBaseName) => {
|
|
213
|
+
return ts.factory.createExportDeclaration(undefined, true, undefined, ts.factory.createStringLiteral(`./${fileBaseName}`));
|
|
214
|
+
};
|
|
206
215
|
/**
|
|
207
216
|
* Generate object literal decorator
|
|
208
217
|
* @param {string} decoratorIdentifier
|
|
@@ -212,6 +221,9 @@ export const generateIndexExport = (modelFileName) => {
|
|
|
212
221
|
export const generateObjectLiteralDecorator = (decoratorIdentifier, props) => {
|
|
213
222
|
const _createPropertyAssignment = (propName, propValue) => {
|
|
214
223
|
let expression;
|
|
224
|
+
if (isTsExpression(propValue)) {
|
|
225
|
+
return ts.factory.createPropertyAssignment(propName, propValue);
|
|
226
|
+
}
|
|
215
227
|
switch (typeof propValue) {
|
|
216
228
|
case 'number':
|
|
217
229
|
expression = ts.factory.createNumericLiteral(propValue);
|
|
@@ -12,6 +12,26 @@ export type TransformMap = {
|
|
|
12
12
|
};
|
|
13
13
|
export type TransformFn = (value: string, target: TransformTarget) => string;
|
|
14
14
|
export declare const TransformCases: Set<TransformCase>;
|
|
15
|
+
/**
|
|
16
|
+
* A type override entry: the TypeScript type, the Sequelize data type, or both.
|
|
17
|
+
* `tsType` is any TypeScript type expression, e.g. `{ x: number }` or
|
|
18
|
+
* `import('pkg').Type`; `dataType` is a Sequelize data type expression with an
|
|
19
|
+
* optional `DataTypes.`/`DataType.` prefix, e.g. `STRING(255)` or
|
|
20
|
+
* `ARRAY(ENUM('a', 'b'))`. A side left unset keeps the generated type.
|
|
21
|
+
*/
|
|
22
|
+
export interface ITypeOverride {
|
|
23
|
+
tsType?: string;
|
|
24
|
+
dataType?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Shape of the type overrides file. `types` keys are database type names, optionally
|
|
28
|
+
* schema-qualified (`<type>` or `<schema>.<type>`); `columns` keys are
|
|
29
|
+
* `<table>.<column>` or `<schema>.<table>.<column>`. Keys match case-insensitively.
|
|
30
|
+
*/
|
|
31
|
+
export interface ITypeOverrides {
|
|
32
|
+
types?: Record<string, ITypeOverride>;
|
|
33
|
+
columns?: Record<string, ITypeOverride>;
|
|
34
|
+
}
|
|
15
35
|
export interface IConfigMetadata {
|
|
16
36
|
tables?: string[];
|
|
17
37
|
skipTables?: string[];
|
|
@@ -21,6 +41,8 @@ export interface IConfigMetadata {
|
|
|
21
41
|
case?: TransformCase | TransformMap | TransformFn;
|
|
22
42
|
associationsFile?: string;
|
|
23
43
|
associations?: boolean;
|
|
44
|
+
typeOverridesFile?: string;
|
|
45
|
+
typeOverrides?: ITypeOverrides;
|
|
24
46
|
noViews?: boolean;
|
|
25
47
|
}
|
|
26
48
|
export interface IConfigOutput {
|
|
@@ -4,6 +4,7 @@ import { IConfig } from '../config/index.js';
|
|
|
4
4
|
import { IAssociationMetadata } from './AssociationsParser.js';
|
|
5
5
|
import type { ReferentialAction } from './foreignKeys.js';
|
|
6
6
|
import type { ISequelizeDataType } from './dataTypes.js';
|
|
7
|
+
import type { TypeNode } from 'typescript';
|
|
7
8
|
export interface ITablesMetadata {
|
|
8
9
|
[tableName: string]: ITableMetadata;
|
|
9
10
|
}
|
|
@@ -42,6 +43,48 @@ export interface IForeignKeyConstraintMetadata {
|
|
|
42
43
|
onUpdate: ReferentialAction;
|
|
43
44
|
isSourceColumnUnique: boolean;
|
|
44
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Type override applied to a column. Each side is set only when a matching type
|
|
48
|
+
* override entry sets it; an unset side keeps the type the generator derives.
|
|
49
|
+
*/
|
|
50
|
+
export interface IColumnTypeOverride {
|
|
51
|
+
/**
|
|
52
|
+
* TypeScript type replacing the generated one, before nullability wrapping.
|
|
53
|
+
*/
|
|
54
|
+
tsType?: TypeNode;
|
|
55
|
+
/**
|
|
56
|
+
* Sequelize data type emitted in place of `sequelizeType`/`dataType`, which
|
|
57
|
+
* keep the generated data type the TypeScript type is derived from.
|
|
58
|
+
*/
|
|
59
|
+
dataType?: ISequelizeDataType;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Database enum type a column is typed with: a Postgres user-defined enum, for a
|
|
63
|
+
* scalar column or an array column.
|
|
64
|
+
*/
|
|
65
|
+
export interface IColumnEnumType {
|
|
66
|
+
/**
|
|
67
|
+
* Schema the enum type is defined in, which may differ from the table schema.
|
|
68
|
+
*/
|
|
69
|
+
schema: string;
|
|
70
|
+
/**
|
|
71
|
+
* Database name of the enum type, e.g. `plan_tier`.
|
|
72
|
+
*/
|
|
73
|
+
name: string;
|
|
74
|
+
/**
|
|
75
|
+
* Enum labels in database sort order.
|
|
76
|
+
*/
|
|
77
|
+
labels: string[];
|
|
78
|
+
/**
|
|
79
|
+
* Set when the column holds an array of the enum.
|
|
80
|
+
*/
|
|
81
|
+
isArray: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Identifier of the shared enum type the column is typed with, assigned by
|
|
84
|
+
* the model builder once the shared type names of the run are resolved.
|
|
85
|
+
*/
|
|
86
|
+
sharedTypeName?: string;
|
|
87
|
+
}
|
|
45
88
|
export interface IColumnMetadata {
|
|
46
89
|
name: string;
|
|
47
90
|
originName: string;
|
|
@@ -57,6 +100,15 @@ export interface IColumnMetadata {
|
|
|
57
100
|
indices?: IIndexMetadata[];
|
|
58
101
|
comment?: string;
|
|
59
102
|
defaultValue?: any;
|
|
103
|
+
/**
|
|
104
|
+
* Set when the column is typed with a database enum type; drives the shared
|
|
105
|
+
* enum type the column is typed with.
|
|
106
|
+
*/
|
|
107
|
+
enumType?: IColumnEnumType;
|
|
108
|
+
/**
|
|
109
|
+
* Set when at least one type override entry matches the column.
|
|
110
|
+
*/
|
|
111
|
+
typeOverride?: IColumnTypeOverride;
|
|
60
112
|
}
|
|
61
113
|
export interface IIndexMetadata {
|
|
62
114
|
name: string;
|
|
@@ -96,11 +148,12 @@ export declare abstract class Dialect {
|
|
|
96
148
|
*/
|
|
97
149
|
abstract mapDbTypeToSequelize(dbType: string): AbstractDataTypeConstructor;
|
|
98
150
|
/**
|
|
99
|
-
* Map database data type to javascript data type
|
|
151
|
+
* Map database data type to javascript data type, or undefined when the
|
|
152
|
+
* dialect has no mapping for it (an unmapped type)
|
|
100
153
|
* @param {string} dbType
|
|
101
|
-
* @returns {string
|
|
154
|
+
* @returns {string | undefined}
|
|
102
155
|
*/
|
|
103
|
-
abstract mapDbTypeToJs(dbType: string): string;
|
|
156
|
+
abstract mapDbTypeToJs(dbType: string): string | undefined;
|
|
104
157
|
/**
|
|
105
158
|
* Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
|
|
106
159
|
* @param {string} v
|
|
@@ -17,9 +17,9 @@ export declare class DialectMSSQL extends Dialect {
|
|
|
17
17
|
/**
|
|
18
18
|
* Map database data type to javascript data type
|
|
19
19
|
* @param {string} dbType
|
|
20
|
-
* @returns {string
|
|
20
|
+
* @returns {string | undefined}
|
|
21
21
|
*/
|
|
22
|
-
mapDbTypeToJs(dbType: string): string;
|
|
22
|
+
mapDbTypeToJs(dbType: string): string | undefined;
|
|
23
23
|
/**
|
|
24
24
|
* Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
|
|
25
25
|
* @param {string} v
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { QueryTypes } from 'sequelize';
|
|
2
2
|
import { DataTypes } from 'sequelize';
|
|
3
3
|
import { Dialect } from './Dialect.js';
|
|
4
|
-
import { warnUnknownMappingForDataType } from './utils.js';
|
|
5
4
|
import { buildSequelizeDataType, renderDataTypeExpression, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
|
|
6
5
|
import { groupForeignKeyRows, mapForeignKeyQueryRow, } from './foreignKeys.js';
|
|
7
6
|
const jsDataTypesMap = {
|
|
@@ -85,7 +84,7 @@ export class DialectMSSQL extends Dialect {
|
|
|
85
84
|
/**
|
|
86
85
|
* Map database data type to javascript data type
|
|
87
86
|
* @param {string} dbType
|
|
88
|
-
* @returns {string
|
|
87
|
+
* @returns {string | undefined}
|
|
89
88
|
*/
|
|
90
89
|
mapDbTypeToJs(dbType) {
|
|
91
90
|
return jsDataTypesMap[dbType];
|
|
@@ -169,10 +168,6 @@ export class DialectMSSQL extends Dialect {
|
|
|
169
168
|
raw: true,
|
|
170
169
|
});
|
|
171
170
|
for (const column of columns) {
|
|
172
|
-
// Unknown data type
|
|
173
|
-
if (!this.mapDbTypeToSequelize(column.DATA_TYPE)) {
|
|
174
|
-
warnUnknownMappingForDataType(column.DATA_TYPE);
|
|
175
|
-
}
|
|
176
171
|
const sequelizeConstructor = this.mapDbTypeToSequelize(column.DATA_TYPE);
|
|
177
172
|
// Data type arguments (precision or length)
|
|
178
173
|
let dataTypeArgs = [];
|
|
@@ -17,9 +17,9 @@ export declare class DialectMariaDB extends Dialect {
|
|
|
17
17
|
/**
|
|
18
18
|
* Map database data type to javascript data type
|
|
19
19
|
* @param {string} dbType
|
|
20
|
-
* @returns {string
|
|
20
|
+
* @returns {string | undefined}
|
|
21
21
|
*/
|
|
22
|
-
mapDbTypeToJs(dbType: string): string;
|
|
22
|
+
mapDbTypeToJs(dbType: string): string | undefined;
|
|
23
23
|
/**
|
|
24
24
|
* Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
|
|
25
25
|
* @param {string} v
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { QueryTypes } from 'sequelize';
|
|
2
2
|
import { DataTypes } from 'sequelize';
|
|
3
3
|
import { Dialect } from './Dialect.js';
|
|
4
|
-
import { warnUnknownMappingForDataType } from './utils.js';
|
|
5
4
|
import { buildSequelizeDataType, renderDataTypeExpression, parseEnumValues, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
|
|
6
5
|
import { groupForeignKeyRows, buildInformationSchemaForeignKeysQuery, mapForeignKeyQueryRow, } from './foreignKeys.js';
|
|
7
6
|
import { extractJsonColumnsFromCheckConstraints, extractJsonColumnsFromCreateTable, getCreateTableStatement, } from './mariadbJson.js';
|
|
@@ -104,7 +103,7 @@ export class DialectMariaDB extends Dialect {
|
|
|
104
103
|
/**
|
|
105
104
|
* Map database data type to javascript data type
|
|
106
105
|
* @param {string} dbType
|
|
107
|
-
* @returns {string
|
|
106
|
+
* @returns {string | undefined}
|
|
108
107
|
*/
|
|
109
108
|
mapDbTypeToJs(dbType) {
|
|
110
109
|
return jsDataTypesMap[dbType];
|
|
@@ -183,10 +182,6 @@ export class DialectMariaDB extends Dialect {
|
|
|
183
182
|
raw: true,
|
|
184
183
|
});
|
|
185
184
|
for (const column of columns) {
|
|
186
|
-
// Unknown data type
|
|
187
|
-
if (!this.mapDbTypeToSequelize(column.DATA_TYPE)) {
|
|
188
|
-
warnUnknownMappingForDataType(column.DATA_TYPE);
|
|
189
|
-
}
|
|
190
185
|
const sequelizeConstructor = this.mapDbTypeToSequelize(column.DATA_TYPE);
|
|
191
186
|
// Data type arguments (precision, length or ENUM values)
|
|
192
187
|
let dataTypeArgs = [];
|
|
@@ -17,9 +17,9 @@ export declare class DialectMySQL extends Dialect {
|
|
|
17
17
|
/**
|
|
18
18
|
* Map database data type to javascript data type
|
|
19
19
|
* @param {string} dbType
|
|
20
|
-
* @returns {string}
|
|
20
|
+
* @returns {string | undefined}
|
|
21
21
|
*/
|
|
22
|
-
mapDbTypeToJs(dbType: string): string;
|
|
22
|
+
mapDbTypeToJs(dbType: string): string | undefined;
|
|
23
23
|
/**
|
|
24
24
|
* Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
|
|
25
25
|
* @param {string} v
|