sequelize-typescript-generator 13.0.1 → 13.2.0
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 +274 -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 +2 -1
- package/build/builders/ModelBuilder.js +155 -15
- package/build/builders/NativeModelRenderer.d.ts +4 -3
- package/build/builders/NativeModelRenderer.js +41 -13
- 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 +12 -1
- package/build/builders/jsonSupport.d.ts +69 -0
- package/build/builders/jsonSupport.js +89 -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 +20 -2
- package/build/builders/utils.js +42 -5
- package/build/config/IConfig.d.ts +22 -0
- package/build/dialects/Dialect.d.ts +57 -3
- package/build/dialects/DialectMSSQL.d.ts +2 -2
- package/build/dialects/DialectMSSQL.js +1 -6
- package/build/dialects/DialectMariaDB.d.ts +13 -2
- package/build/dialects/DialectMariaDB.js +46 -6
- package/build/dialects/DialectMySQL.d.ts +2 -2
- package/build/dialects/DialectMySQL.js +2 -6
- package/build/dialects/DialectPostgres.d.ts +36 -3
- package/build/dialects/DialectPostgres.js +111 -13
- package/build/dialects/DialectSQLite.d.ts +2 -2
- package/build/dialects/DialectSQLite.js +1 -6
- package/build/dialects/dataTypes.d.ts +26 -4
- package/build/dialects/dataTypes.js +50 -5
- package/build/dialects/mariadbJson.d.ts +39 -0
- package/build/dialects/mariadbJson.js +52 -0
- 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,48 @@
|
|
|
1
|
+
import * as ts from 'typescript';
|
|
2
|
+
import type { IConfigMetadata, ITypeOverrides } from '../config/IConfig.js';
|
|
3
|
+
import type { ISequelizeDataType } from '../dialects/dataTypes.js';
|
|
4
|
+
/**
|
|
5
|
+
* Prefix of every type overrides validation error message.
|
|
6
|
+
*/
|
|
7
|
+
export declare const VALIDATION_ERROR_PREFIX = "[ValidationError]";
|
|
8
|
+
/**
|
|
9
|
+
* Section of the type overrides file an entry belongs to.
|
|
10
|
+
*/
|
|
11
|
+
export type TypeOverrideSection = keyof ITypeOverrides;
|
|
12
|
+
/**
|
|
13
|
+
* A validated type override entry.
|
|
14
|
+
*/
|
|
15
|
+
export interface IParsedTypeOverride {
|
|
16
|
+
section: TypeOverrideSection;
|
|
17
|
+
key: string;
|
|
18
|
+
tsType?: ts.TypeNode;
|
|
19
|
+
dataType?: ISequelizeDataType;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validated type overrides, indexed by section and by lower-cased key.
|
|
23
|
+
*/
|
|
24
|
+
export interface IParsedTypeOverrides {
|
|
25
|
+
types: ReadonlyMap<string, IParsedTypeOverride>;
|
|
26
|
+
columns: ReadonlyMap<string, IParsedTypeOverride>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Label of a type override entry used in messages, e.g. `columns["users.status"]`.
|
|
30
|
+
* @param {TypeOverrideSection} section
|
|
31
|
+
* @param {string} key
|
|
32
|
+
* @returns {string}
|
|
33
|
+
*/
|
|
34
|
+
export declare const formatTypeOverrideLabel: (section: TypeOverrideSection, key: string) => string;
|
|
35
|
+
/**
|
|
36
|
+
* Validate type overrides of unknown shape.
|
|
37
|
+
* @param {unknown} value
|
|
38
|
+
* @returns {IParsedTypeOverrides}
|
|
39
|
+
*/
|
|
40
|
+
export declare const parseTypeOverrides: (value: unknown) => IParsedTypeOverrides;
|
|
41
|
+
/**
|
|
42
|
+
* Load and validate the type overrides configured in the metadata options, from
|
|
43
|
+
* either the type overrides file or the programmatic `typeOverrides`. Returns
|
|
44
|
+
* undefined when neither is set.
|
|
45
|
+
* @param {IConfigMetadata | undefined} metadata
|
|
46
|
+
* @returns {Promise<IParsedTypeOverrides | undefined>}
|
|
47
|
+
*/
|
|
48
|
+
export declare const loadTypeOverrides: (metadata: IConfigMetadata | undefined) => Promise<IParsedTypeOverrides | undefined>;
|
|
@@ -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
|
+
};
|
|
@@ -13,6 +13,23 @@ export type PropertyValue = string | number | boolean | ts.Expression | Property
|
|
|
13
13
|
* @returns {string}
|
|
14
14
|
*/
|
|
15
15
|
export declare const nodeToString: (node: ts.Node) => string;
|
|
16
|
+
/**
|
|
17
|
+
* Neutralise the block-comment terminator inside text so it cannot prematurely
|
|
18
|
+
* close a JSDoc block, by inserting a space between `*` and `/`.
|
|
19
|
+
* @param {string} comment
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
export declare const sanitiseJsDocComment: (comment: string) => string;
|
|
23
|
+
/**
|
|
24
|
+
* Attach a database column comment as a `/** … *\/` JSDoc leading comment on a
|
|
25
|
+
* declaration. Empty or whitespace-only comments are ignored; an embedded
|
|
26
|
+
* comment terminator is neutralised first. Returns the node unchanged when there
|
|
27
|
+
* is nothing to attach.
|
|
28
|
+
* @param {T} node
|
|
29
|
+
* @param {string | undefined} comment
|
|
30
|
+
* @returns {T}
|
|
31
|
+
*/
|
|
32
|
+
export declare const attachColumnCommentJsDoc: <T extends ts.Node>(node: T, comment: string | undefined) => T;
|
|
16
33
|
/**
|
|
17
34
|
* Generate named imports code (e.g. `import { Something, Else } from "module"`)
|
|
18
35
|
* @param {string[]} importsSpecifier
|
|
@@ -52,8 +69,9 @@ export declare const buildObjectLiteralExpression: (props: {
|
|
|
52
69
|
[key: string]: PropertyValue;
|
|
53
70
|
}, isMultiLine: boolean) => ts.ObjectLiteralExpression;
|
|
54
71
|
/**
|
|
55
|
-
* Build a type node from a JS type name: number/string/boolean/object keywords,
|
|
56
|
-
* Date and Uint8Array references, and the unknown keyword for anything else.
|
|
72
|
+
* Build a type node from a JS type name: number/string/boolean/object/any keywords,
|
|
73
|
+
* Date and Uint8Array references, and the unknown keyword for anything else. A name
|
|
74
|
+
* with a trailing `[]` (e.g. `number[]`) yields an array type node of the element.
|
|
57
75
|
* @param {string} jsType
|
|
58
76
|
* @returns {ts.TypeNode}
|
|
59
77
|
*/
|
package/build/builders/utils.js
CHANGED
|
@@ -15,6 +15,28 @@ export const nodeToString = (node) => {
|
|
|
15
15
|
// Reference: https://github.com/microsoft/TypeScript/issues/36174
|
|
16
16
|
return unescape(sourceCode.replace(/\\u/g, "%u"));
|
|
17
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* Neutralise the block-comment terminator inside text so it cannot prematurely
|
|
20
|
+
* close a JSDoc block, by inserting a space between `*` and `/`.
|
|
21
|
+
* @param {string} comment
|
|
22
|
+
* @returns {string}
|
|
23
|
+
*/
|
|
24
|
+
export const sanitiseJsDocComment = (comment) => comment.replace(/\*\//g, '* /');
|
|
25
|
+
/**
|
|
26
|
+
* Attach a database column comment as a `/** … *\/` JSDoc leading comment on a
|
|
27
|
+
* declaration. Empty or whitespace-only comments are ignored; an embedded
|
|
28
|
+
* comment terminator is neutralised first. Returns the node unchanged when there
|
|
29
|
+
* is nothing to attach.
|
|
30
|
+
* @param {T} node
|
|
31
|
+
* @param {string | undefined} comment
|
|
32
|
+
* @returns {T}
|
|
33
|
+
*/
|
|
34
|
+
export const attachColumnCommentJsDoc = (node, comment) => {
|
|
35
|
+
if (!comment || comment.trim().length === 0) {
|
|
36
|
+
return node;
|
|
37
|
+
}
|
|
38
|
+
return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `* ${sanitiseJsDocComment(comment.trim())} `, true);
|
|
39
|
+
};
|
|
18
40
|
/**
|
|
19
41
|
* Generate named imports code (e.g. `import { Something, Else } from "module"`)
|
|
20
42
|
* @param {string[]} importsSpecifier
|
|
@@ -98,12 +120,16 @@ export const createPropertyValueExpression = (value, isMultiLine) => {
|
|
|
98
120
|
*/
|
|
99
121
|
export const buildObjectLiteralExpression = (props, isMultiLine) => ts.factory.createObjectLiteralExpression(Object.entries(props).map(([key, value]) => ts.factory.createPropertyAssignment(createPropertyName(key), createPropertyValueExpression(value, isMultiLine))), isMultiLine);
|
|
100
122
|
/**
|
|
101
|
-
* Build a type node from a JS type name: number/string/boolean/object keywords,
|
|
102
|
-
* Date and Uint8Array references, and the unknown keyword for anything else.
|
|
123
|
+
* Build a type node from a JS type name: number/string/boolean/object/any keywords,
|
|
124
|
+
* Date and Uint8Array references, and the unknown keyword for anything else. A name
|
|
125
|
+
* with a trailing `[]` (e.g. `number[]`) yields an array type node of the element.
|
|
103
126
|
* @param {string} jsType
|
|
104
127
|
* @returns {ts.TypeNode}
|
|
105
128
|
*/
|
|
106
129
|
export const createTypeNodeFromName = (jsType) => {
|
|
130
|
+
if (jsType.endsWith('[]')) {
|
|
131
|
+
return ts.factory.createArrayTypeNode(createTypeNodeFromName(jsType.slice(0, -2)));
|
|
132
|
+
}
|
|
107
133
|
switch (jsType) {
|
|
108
134
|
case 'number':
|
|
109
135
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
|
|
@@ -113,6 +139,8 @@ export const createTypeNodeFromName = (jsType) => {
|
|
|
113
139
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
|
|
114
140
|
case 'object':
|
|
115
141
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword);
|
|
142
|
+
case 'any':
|
|
143
|
+
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);
|
|
116
144
|
case 'Date':
|
|
117
145
|
return ts.factory.createTypeReferenceNode('Date', undefined);
|
|
118
146
|
case 'Uint8Array':
|
|
@@ -157,9 +185,15 @@ export const buildDataTypeExpression = (dataType, namespace) => {
|
|
|
157
185
|
if (dataType.args.length === 0) {
|
|
158
186
|
return memberAccess;
|
|
159
187
|
}
|
|
160
|
-
return ts.factory.createCallExpression(memberAccess, undefined, dataType.args.map(arg =>
|
|
161
|
-
|
|
162
|
-
|
|
188
|
+
return ts.factory.createCallExpression(memberAccess, undefined, dataType.args.map(arg => {
|
|
189
|
+
if (typeof arg === 'number') {
|
|
190
|
+
return createNumericLiteralExpression(arg);
|
|
191
|
+
}
|
|
192
|
+
if (typeof arg === 'string') {
|
|
193
|
+
return ts.factory.createStringLiteral(arg);
|
|
194
|
+
}
|
|
195
|
+
return buildDataTypeExpression(arg, namespace);
|
|
196
|
+
}));
|
|
163
197
|
};
|
|
164
198
|
/**
|
|
165
199
|
* Generate model export for index file
|
|
@@ -178,6 +212,9 @@ export const generateIndexExport = (modelFileName) => {
|
|
|
178
212
|
export const generateObjectLiteralDecorator = (decoratorIdentifier, props) => {
|
|
179
213
|
const _createPropertyAssignment = (propName, propValue) => {
|
|
180
214
|
let expression;
|
|
215
|
+
if (isTsExpression(propValue)) {
|
|
216
|
+
return ts.factory.createPropertyAssignment(propName, propValue);
|
|
217
|
+
}
|
|
181
218
|
switch (typeof propValue) {
|
|
182
219
|
case 'number':
|
|
183
220
|
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 {
|