sequelize-typescript-generator 13.1.0 → 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.
Files changed (39) hide show
  1. package/README.md +274 -20
  2. package/build/bin/cli.js +3 -3
  3. package/build/bin/utils.d.ts +13 -0
  4. package/build/bin/utils.js +25 -0
  5. package/build/builders/ModelBuilder.d.ts +2 -1
  6. package/build/builders/ModelBuilder.js +135 -16
  7. package/build/builders/NativeModelRenderer.d.ts +4 -3
  8. package/build/builders/NativeModelRenderer.js +31 -11
  9. package/build/builders/enumSupport.d.ts +104 -0
  10. package/build/builders/enumSupport.js +323 -0
  11. package/build/builders/generatedFile.d.ts +2 -1
  12. package/build/builders/generatedFile.js +7 -1
  13. package/build/builders/jsonSupport.d.ts +10 -3
  14. package/build/builders/jsonSupport.js +10 -3
  15. package/build/builders/typeOverrides.d.ts +30 -0
  16. package/build/builders/typeOverrides.js +93 -0
  17. package/build/builders/typeOverridesParser.d.ts +48 -0
  18. package/build/builders/typeOverridesParser.js +305 -0
  19. package/build/builders/unmappedTypes.d.ts +50 -0
  20. package/build/builders/unmappedTypes.js +62 -0
  21. package/build/builders/utils.js +3 -0
  22. package/build/config/IConfig.d.ts +22 -0
  23. package/build/dialects/Dialect.d.ts +56 -3
  24. package/build/dialects/DialectMSSQL.d.ts +2 -2
  25. package/build/dialects/DialectMSSQL.js +1 -6
  26. package/build/dialects/DialectMariaDB.d.ts +2 -2
  27. package/build/dialects/DialectMariaDB.js +1 -6
  28. package/build/dialects/DialectMySQL.d.ts +2 -2
  29. package/build/dialects/DialectMySQL.js +1 -6
  30. package/build/dialects/DialectPostgres.d.ts +33 -2
  31. package/build/dialects/DialectPostgres.js +77 -10
  32. package/build/dialects/DialectSQLite.d.ts +2 -2
  33. package/build/dialects/DialectSQLite.js +1 -6
  34. package/build/dialects/dataTypes.d.ts +8 -0
  35. package/build/dialects/dataTypes.js +32 -4
  36. package/build/dialects/utils.d.ts +0 -6
  37. package/build/dialects/utils.js +0 -10
  38. package/build/index.d.ts +2 -2
  39. package/package.json +3 -3
@@ -0,0 +1,323 @@
1
+ import * as ts from 'typescript';
2
+ import { pascalCase } from 'change-case';
3
+ import { generateTypeOnlyImport, nodeToString } from './utils.js';
4
+ /**
5
+ * Base name of the shared support file holding the enum shared types. A
6
+ * collision with a model name is reported by `warnEnumSupportFileNameCollision`.
7
+ */
8
+ export const ENUM_SUPPORT_FILE_BASENAME = 'enums';
9
+ /**
10
+ * File name of the shared enum support file.
11
+ */
12
+ export const ENUM_SUPPORT_FILE_NAME = `${ENUM_SUPPORT_FILE_BASENAME}.ts`;
13
+ /**
14
+ * Sibling module specifier used by model files to import enum shared types.
15
+ */
16
+ export const ENUM_SUPPORT_MODULE_SPECIFIER = `./${ENUM_SUPPORT_FILE_BASENAME}`;
17
+ /**
18
+ * Suffix appended to an enum shared type name that clashes with a generated
19
+ * model name or another identifier declared or imported by a model file.
20
+ */
21
+ export const ENUM_RESERVED_NAME_SUFFIX = 'Enum';
22
+ /**
23
+ * Prefix given to an enum shared type name that does not start with a valid
24
+ * identifier character, e.g. a database name starting with a digit.
25
+ */
26
+ const ENUM_INVALID_START_PREFIX = 'Enum';
27
+ /**
28
+ * First numeric suffix given to clashing names that need a counter.
29
+ */
30
+ const FIRST_NUMERIC_SUFFIX = 2;
31
+ /**
32
+ * Unique key of a database enum type: its schema and name.
33
+ * @param {Pick<IColumnEnumType, 'schema' | 'name'>} enumType
34
+ * @returns {string}
35
+ */
36
+ const buildEnumTypeKey = ({ schema, name }) => JSON.stringify([schema, name]);
37
+ /**
38
+ * Qualified database name of an enum type, e.g. `public.plan_tier`.
39
+ * @param {Pick<IColumnEnumType, 'schema' | 'name'>} enumType
40
+ * @returns {string}
41
+ */
42
+ const formatEnumTypeName = ({ schema, name }) => `${schema}.${name}`;
43
+ /**
44
+ * Compare two strings by code point, independently of the locale.
45
+ * @param {string} left
46
+ * @param {string} right
47
+ * @returns {number}
48
+ */
49
+ const compareCodePoints = (left, right) => left < right ? -1 : left > right ? 1 : 0;
50
+ /**
51
+ * Report whether a column is typed with an enum shared type: an enum column
52
+ * whose TypeScript type no type override replaces.
53
+ * @param {IColumnMetadata} column
54
+ * @returns {boolean}
55
+ */
56
+ export const columnUsesSharedEnumType = (column) => column.enumType !== undefined && column.typeOverride?.tsType === undefined;
57
+ /**
58
+ * Collect the database enums of every enum column, sorted by schema then name.
59
+ * @param {ITablesMetadata} tablesMetadata
60
+ * @returns {IColumnEnumType[]}
61
+ */
62
+ const collectEnumTypes = (tablesMetadata) => {
63
+ const enumTypes = new Map();
64
+ for (const table of Object.values(tablesMetadata)) {
65
+ for (const column of Object.values(table.columns)) {
66
+ if (column.enumType) {
67
+ enumTypes.set(buildEnumTypeKey(column.enumType), column.enumType);
68
+ }
69
+ }
70
+ }
71
+ return [...enumTypes.values()].sort((left, right) => compareCodePoints(left.schema, right.schema) || compareCodePoints(left.name, right.name));
72
+ };
73
+ /**
74
+ * Collect the keys of the database enums used by at least one column typed with
75
+ * an enum shared type.
76
+ * @param {ITablesMetadata} tablesMetadata
77
+ * @returns {Set<string>}
78
+ */
79
+ const collectUsedEnumTypeKeys = (tablesMetadata) => new Set(Object.values(tablesMetadata).flatMap(table => Object.values(table.columns).flatMap(column => column.enumType && columnUsesSharedEnumType(column) ? [buildEnumTypeKey(column.enumType)] : [])));
80
+ /**
81
+ * Turn a database name into a Pascal-case identifier, dropping characters that
82
+ * are not valid in an identifier and prefixing a name that does not start with
83
+ * a valid identifier character.
84
+ * @param {string} name
85
+ * @returns {string}
86
+ */
87
+ export const toPascalCaseIdentifier = (name) => {
88
+ const identifier = [...pascalCase(name)]
89
+ .filter(character => ts.isIdentifierPart(character.codePointAt(0) ?? 0, ts.ScriptTarget.Latest))
90
+ .join('');
91
+ const firstCodePoint = identifier.codePointAt(0);
92
+ return firstCodePoint !== undefined && ts.isIdentifierStart(firstCodePoint, ts.ScriptTarget.Latest)
93
+ ? identifier
94
+ : `${ENUM_INVALID_START_PREFIX}${identifier}`;
95
+ };
96
+ /**
97
+ * Resolve the shared type name of every enum. The name is the Pascal case of the
98
+ * database type name. On a clash, only the clashing enums are renamed:
99
+ * - an enum from a schema none of the generated tables belong to is prefixed
100
+ * with its Pascal-cased schema when another enum of the same name exists;
101
+ * - a name equal to a generated model name or to another reserved identifier
102
+ * gets the `Enum` suffix;
103
+ * - names still equal after that are disambiguated in code-point order of the
104
+ * database schema then type name: the first keeps the name, the next ones get
105
+ * the suffix 2, 3, and so on.
106
+ * @param {IColumnEnumType[]} enumTypes Enums sorted by schema then name
107
+ * @param {ReadonlySet<string>} tableSchemas
108
+ * @param {IReservedIdentifiers} reserved
109
+ * @returns {{ names: Map<string, string>; clashes: IEnumNameClash[] }}
110
+ */
111
+ const resolveSharedEnumTypeNames = (enumTypes, tableSchemas, reserved) => {
112
+ const namedEnumTypes = enumTypes.map(enumType => ({
113
+ enumType,
114
+ baseName: toPascalCaseIdentifier(enumType.name),
115
+ }));
116
+ const schemasByBaseName = new Map();
117
+ for (const { enumType, baseName } of namedEnumTypes) {
118
+ const schemas = schemasByBaseName.get(baseName) ?? new Set();
119
+ schemas.add(enumType.schema);
120
+ schemasByBaseName.set(baseName, schemas);
121
+ }
122
+ const candidates = namedEnumTypes.map(({ enumType, baseName }) => {
123
+ const isForeignSchemaClash = !tableSchemas.has(enumType.schema) &&
124
+ (schemasByBaseName.get(baseName)?.size ?? 0) > 1;
125
+ const schemaQualified = isForeignSchemaClash
126
+ ? `${toPascalCaseIdentifier(enumType.schema)}${baseName}`
127
+ : baseName;
128
+ const isModelName = reserved.modelNames.has(schemaQualified);
129
+ const isReserved = isModelName || reserved.nonModelIdentifiers.has(schemaQualified);
130
+ return {
131
+ enumType,
132
+ baseName,
133
+ candidate: isReserved ? `${schemaQualified}${ENUM_RESERVED_NAME_SUFFIX}` : schemaQualified,
134
+ reasons: [
135
+ ...isForeignSchemaClash ? [`an enum type of the same name in another schema`] : [],
136
+ ...isModelName ? [`the model '${schemaQualified}'`] : [],
137
+ ...isReserved && !isModelName ? [`the identifier '${schemaQualified}' used by the model files`] : [],
138
+ ],
139
+ };
140
+ });
141
+ const taken = new Set([...reserved.modelNames, ...reserved.nonModelIdentifiers]);
142
+ const typeNames = new Map();
143
+ // The first enum in order keeps a candidate name; the others sharing it are
144
+ // suffixed once every unsuffixed name is taken, so a suffix never steals a
145
+ // name another enum resolves to on its own.
146
+ for (const { enumType, candidate } of candidates) {
147
+ if (!taken.has(candidate)) {
148
+ taken.add(candidate);
149
+ typeNames.set(buildEnumTypeKey(enumType), candidate);
150
+ }
151
+ }
152
+ for (const { enumType, candidate } of candidates) {
153
+ if (!typeNames.has(buildEnumTypeKey(enumType))) {
154
+ let suffix = FIRST_NUMERIC_SUFFIX;
155
+ while (taken.has(`${candidate}${suffix}`)) {
156
+ suffix++;
157
+ }
158
+ taken.add(`${candidate}${suffix}`);
159
+ typeNames.set(buildEnumTypeKey(enumType), `${candidate}${suffix}`);
160
+ }
161
+ }
162
+ const clashes = [];
163
+ for (const { enumType, baseName, candidate, reasons } of candidates) {
164
+ const typeName = typeNames.get(buildEnumTypeKey(enumType)) ?? candidate;
165
+ if (typeName === baseName) {
166
+ continue;
167
+ }
168
+ const sharingEnums = candidates
169
+ .filter(other => other.enumType !== enumType && other.candidate === candidate)
170
+ .map(other => `'${formatEnumTypeName(other.enumType)}'`);
171
+ const allReasons = typeName === candidate || sharingEnums.length === 0
172
+ ? reasons
173
+ : [...reasons, `the enum type ${sharingEnums.join(', ')}`];
174
+ clashes.push({
175
+ enumType,
176
+ baseName,
177
+ typeName,
178
+ reason: allReasons.length > 0 ? allReasons.join(' and ') : `an identifier used by the model files`,
179
+ });
180
+ }
181
+ return { names: typeNames, clashes };
182
+ };
183
+ /**
184
+ * Build the warning for an enum whose shared type is renamed to avoid a name clash.
185
+ * @param {IEnumNameClash} clash
186
+ * @returns {string}
187
+ */
188
+ const buildEnumNameClashWarning = ({ enumType, baseName, typeName, reason }) => `Enum type '${formatEnumTypeName(enumType)}' is emitted as '${typeName}' instead of '${baseName}' ` +
189
+ `to avoid a name clash with ${reason}.`;
190
+ /**
191
+ * Name the enum shared types of the run and record each name on the columns
192
+ * typed with it. Names are resolved over every database enum of the generated
193
+ * columns, so a type override never renames another enum; an enum whose
194
+ * TypeScript type a type override replaces on every column gets no shared type.
195
+ * A warning is emitted for every renamed enum that has a shared type.
196
+ * @param {ITablesMetadata} tablesMetadata
197
+ * @param {IReservedIdentifiers} reserved
198
+ * @returns {ITablesMetadata}
199
+ */
200
+ export const assignSharedEnumTypeNames = (tablesMetadata, reserved) => {
201
+ const usedEnumTypeKeys = collectUsedEnumTypeKeys(tablesMetadata);
202
+ if (usedEnumTypeKeys.size === 0) {
203
+ return tablesMetadata;
204
+ }
205
+ const enumTypes = collectEnumTypes(tablesMetadata);
206
+ const tableSchemas = new Set(Object.values(tablesMetadata)
207
+ .map(table => table.schema)
208
+ .filter(schema => schema !== undefined));
209
+ const { names, clashes } = resolveSharedEnumTypeNames(enumTypes, tableSchemas, reserved);
210
+ for (const clash of clashes.filter(({ enumType }) => usedEnumTypeKeys.has(buildEnumTypeKey(enumType)))) {
211
+ console.warn('[WARNING]', buildEnumNameClashWarning(clash));
212
+ }
213
+ const named = {};
214
+ for (const [tableKey, table] of Object.entries(tablesMetadata)) {
215
+ const columns = {};
216
+ for (const [columnKey, column] of Object.entries(table.columns)) {
217
+ const sharedTypeName = column.enumType && columnUsesSharedEnumType(column)
218
+ ? names.get(buildEnumTypeKey(column.enumType))
219
+ : undefined;
220
+ columns[columnKey] = column.enumType && sharedTypeName
221
+ ? { ...column, enumType: { ...column.enumType, sharedTypeName } }
222
+ : column;
223
+ }
224
+ named[tableKey] = { ...table, columns };
225
+ }
226
+ return named;
227
+ };
228
+ /**
229
+ * Build the TypeScript type of an enum column: a reference to its shared type,
230
+ * or the union of its labels when no shared type name is assigned, as an array
231
+ * for an enum array column.
232
+ * @param {IColumnEnumType} enumType
233
+ * @returns {ts.TypeNode}
234
+ */
235
+ export const buildEnumColumnTypeNode = (enumType) => {
236
+ const elementType = enumType.sharedTypeName
237
+ ? ts.factory.createTypeReferenceNode(enumType.sharedTypeName, undefined)
238
+ : buildEnumLabelsUnionTypeNode(enumType.labels);
239
+ return enumType.isArray
240
+ ? ts.factory.createArrayTypeNode(ts.isUnionTypeNode(elementType) ? ts.factory.createParenthesizedType(elementType) : elementType)
241
+ : elementType;
242
+ };
243
+ /**
244
+ * Build the union of string literal types of the enum labels, or `never` for
245
+ * an enum without labels.
246
+ * @param {string[]} labels
247
+ * @returns {ts.TypeNode}
248
+ */
249
+ const buildEnumLabelsUnionTypeNode = (labels) => labels.length > 0
250
+ ? ts.factory.createUnionTypeNode(labels.map(label => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(label))))
251
+ : ts.factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword);
252
+ /**
253
+ * Collect the enum shared types used by the columns of the given tables, sorted
254
+ * by type name.
255
+ * @param {ITableMetadata[]} tables
256
+ * @returns {ISharedEnumType[]}
257
+ */
258
+ const collectSharedEnumTypes = (tables) => {
259
+ const sharedEnumTypes = new Map();
260
+ for (const table of tables) {
261
+ for (const column of Object.values(table.columns)) {
262
+ const enumType = column.enumType;
263
+ if (enumType?.sharedTypeName && columnUsesSharedEnumType(column)) {
264
+ sharedEnumTypes.set(enumType.sharedTypeName, {
265
+ schema: enumType.schema,
266
+ name: enumType.name,
267
+ labels: enumType.labels,
268
+ typeName: enumType.sharedTypeName,
269
+ });
270
+ }
271
+ }
272
+ }
273
+ return [...sharedEnumTypes.values()]
274
+ .sort((left, right) => compareCodePoints(left.typeName, right.typeName));
275
+ };
276
+ /**
277
+ * Report whether any table has a column typed with an enum shared type.
278
+ * @param {ITablesMetadata} tablesMetadata
279
+ * @returns {boolean}
280
+ */
281
+ export const tablesHaveSharedEnumType = (tablesMetadata) => collectSharedEnumTypes(Object.values(tablesMetadata)).length > 0;
282
+ /**
283
+ * Build the exported type alias of an enum shared type, e.g.
284
+ * `export type PlanTier = "free" | "pro";`, with the labels in database order.
285
+ * @param {ISharedEnumType} sharedEnumType
286
+ * @returns {ts.TypeAliasDeclaration}
287
+ */
288
+ export const buildSharedEnumTypeAliasDeclaration = (sharedEnumType) => ts.factory.createTypeAliasDeclaration([ts.factory.createToken(ts.SyntaxKind.ExportKeyword)], sharedEnumType.typeName, undefined, buildEnumLabelsUnionTypeNode(sharedEnumType.labels));
289
+ /**
290
+ * Render the shared enum support file: one exported type alias per enum shared
291
+ * type used by a generated column, sorted by type name.
292
+ * @param {ITablesMetadata} tablesMetadata
293
+ * @returns {string}
294
+ */
295
+ export const renderEnumSupportFile = (tablesMetadata) => collectSharedEnumTypes(Object.values(tablesMetadata))
296
+ .map(sharedEnumType => nodeToString(buildSharedEnumTypeAliasDeclaration(sharedEnumType)))
297
+ .join('\n');
298
+ /**
299
+ * Build the type-only import of the enum shared types a model uses, or
300
+ * undefined when it uses none.
301
+ * @param {ITableMetadata} table
302
+ * @returns {ts.ImportDeclaration | undefined}
303
+ */
304
+ export const buildEnumTypesImport = (table) => {
305
+ const typeNames = collectSharedEnumTypes([table]).map(sharedEnumType => sharedEnumType.typeName);
306
+ return typeNames.length > 0
307
+ ? generateTypeOnlyImport(typeNames, ENUM_SUPPORT_MODULE_SPECIFIER)
308
+ : undefined;
309
+ };
310
+ /**
311
+ * Warn when a generated model name collides with the shared enum support file
312
+ * name, which would make both write to the same file.
313
+ * @param {ITablesMetadata} tablesMetadata
314
+ * @returns {void}
315
+ */
316
+ export const warnEnumSupportFileNameCollision = (tablesMetadata) => {
317
+ const collision = Object.values(tablesMetadata)
318
+ .find(table => table.name === ENUM_SUPPORT_FILE_BASENAME)?.name;
319
+ if (collision) {
320
+ console.warn('[WARNING]', `Model '${collision}' collides with the shared enum support file '${ENUM_SUPPORT_FILE_NAME}'; ` +
321
+ `the generated model and the enum support file would overwrite each other.`);
322
+ }
323
+ };
@@ -8,7 +8,8 @@ export interface IGeneratedFile {
8
8
  }
9
9
  /**
10
10
  * Render the complete set of native output files: one model file per table, the
11
- * `initModels.ts` wiring file and the `index.ts` barrel, in table order.
11
+ * shared type files the models use, the `initModels.ts` wiring file and the
12
+ * `index.ts` barrel, in table order.
12
13
  * @param {ITablesMetadata} tablesMetadata
13
14
  * @param {Dialect} dialect
14
15
  * @returns {IGeneratedFile[]}
@@ -4,9 +4,11 @@ import { indexTablesByModelName } from './nativeAttributes.js';
4
4
  import { renderNativeModelFile } from './NativeModelRenderer.js';
5
5
  import { renderInitModelsFile, renderNativeIndexFile } from './nativeWiring.js';
6
6
  import { JSON_SUPPORT_FILE_NAME, renderJsonSupportFile, tablesHaveJsonColumn, warnJsonSupportFileNameCollision, } from './jsonSupport.js';
7
+ import { ENUM_SUPPORT_FILE_NAME, renderEnumSupportFile, tablesHaveSharedEnumType, warnEnumSupportFileNameCollision, } from './enumSupport.js';
7
8
  /**
8
9
  * Render the complete set of native output files: one model file per table, the
9
- * `initModels.ts` wiring file and the `index.ts` barrel, in table order.
10
+ * shared type files the models use, the `initModels.ts` wiring file and the
11
+ * `index.ts` barrel, in table order.
10
12
  * @param {ITablesMetadata} tablesMetadata
11
13
  * @param {Dialect} dialect
12
14
  * @returns {IGeneratedFile[]}
@@ -21,6 +23,10 @@ export const renderNativeFiles = (tablesMetadata, dialect) => {
21
23
  warnJsonSupportFileNameCollision(tablesMetadata);
22
24
  files.push({ fileName: JSON_SUPPORT_FILE_NAME, content: renderJsonSupportFile() });
23
25
  }
26
+ if (tablesHaveSharedEnumType(tablesMetadata)) {
27
+ warnEnumSupportFileNameCollision(tablesMetadata);
28
+ files.push({ fileName: ENUM_SUPPORT_FILE_NAME, content: renderEnumSupportFile(tablesMetadata) });
29
+ }
24
30
  files.push({ fileName: 'initModels.ts', content: renderInitModelsFile(tablesMetadata, tablesByModel) });
25
31
  files.push({ fileName: 'index.ts', content: renderNativeIndexFile(tablesMetadata) });
26
32
  return files;
@@ -1,5 +1,5 @@
1
1
  import * as ts from 'typescript';
2
- import type { ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
2
+ import type { IColumnMetadata, ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
3
3
  /**
4
4
  * Base name of the shared support file holding the recursive `Json` type. Chosen
5
5
  * to be distinct from generated model names; a collision with a model name is
@@ -35,13 +35,20 @@ export declare const renderJsonSupportFile: () => string;
35
35
  */
36
36
  export declare const buildJsonTypeImport: () => ts.ImportDeclaration;
37
37
  /**
38
- * Report whether a table has at least one JSON/JSONB column.
38
+ * Report whether a column is typed with the shared `Json` type: a JSON/JSONB
39
+ * column whose TypeScript type no type override replaces.
40
+ * @param {IColumnMetadata} column
41
+ * @returns {boolean}
42
+ */
43
+ export declare const columnUsesJsonType: (column: IColumnMetadata) => boolean;
44
+ /**
45
+ * Report whether a table has at least one column typed with the shared `Json` type.
39
46
  * @param {ITableMetadata} table
40
47
  * @returns {boolean}
41
48
  */
42
49
  export declare const tableHasJsonColumn: (table: ITableMetadata) => boolean;
43
50
  /**
44
- * Report whether any table has at least one JSON/JSONB column.
51
+ * Report whether any table has at least one column typed with the shared `Json` type.
45
52
  * @param {ITablesMetadata} tablesMetadata
46
53
  * @returns {boolean}
47
54
  */
@@ -49,13 +49,20 @@ export const renderJsonSupportFile = () => nodeToString(buildJsonTypeAliasDeclar
49
49
  */
50
50
  export const buildJsonTypeImport = () => generateTypeOnlyImport([JSON_TYPE_NAME], JSON_SUPPORT_MODULE_SPECIFIER);
51
51
  /**
52
- * Report whether a table has at least one JSON/JSONB column.
52
+ * Report whether a column is typed with the shared `Json` type: a JSON/JSONB
53
+ * column whose TypeScript type no type override replaces.
54
+ * @param {IColumnMetadata} column
55
+ * @returns {boolean}
56
+ */
57
+ export const columnUsesJsonType = (column) => column.isJson === true && column.typeOverride?.tsType === undefined;
58
+ /**
59
+ * Report whether a table has at least one column typed with the shared `Json` type.
53
60
  * @param {ITableMetadata} table
54
61
  * @returns {boolean}
55
62
  */
56
- export const tableHasJsonColumn = (table) => Object.values(table.columns).some(column => column.isJson === true);
63
+ export const tableHasJsonColumn = (table) => Object.values(table.columns).some(columnUsesJsonType);
57
64
  /**
58
- * Report whether any table has at least one JSON/JSONB column.
65
+ * Report whether any table has at least one column typed with the shared `Json` type.
59
66
  * @param {ITablesMetadata} tablesMetadata
60
67
  * @returns {boolean}
61
68
  */
@@ -0,0 +1,30 @@
1
+ import type { ITablesMetadata } from '../dialects/Dialect.js';
2
+ import type { IParsedTypeOverride, IParsedTypeOverrides } from './typeOverridesParser.js';
3
+ /**
4
+ * Result of applying type overrides: the tables metadata with the overrides
5
+ * applied, and the entries that matched no column.
6
+ */
7
+ export interface ITypeOverridesApplication {
8
+ tablesMetadata: ITablesMetadata;
9
+ unmatchedEntries: IParsedTypeOverride[];
10
+ }
11
+ /**
12
+ * Apply type overrides to every column they match, and report the entries that
13
+ * matched no column.
14
+ * @param {ITablesMetadata} tablesMetadata
15
+ * @param {IParsedTypeOverrides} overrides
16
+ * @returns {ITypeOverridesApplication}
17
+ */
18
+ export declare const applyTypeOverrides: (tablesMetadata: ITablesMetadata, overrides: IParsedTypeOverrides) => ITypeOverridesApplication;
19
+ /**
20
+ * Build the warning listing the type override entries that matched no column.
21
+ * @param {IParsedTypeOverride[]} unmatchedEntries
22
+ * @returns {string}
23
+ */
24
+ export declare const buildUnmatchedTypeOverridesWarning: (unmatchedEntries: IParsedTypeOverride[]) => string;
25
+ /**
26
+ * Warn once about the type override entries that matched no column.
27
+ * @param {IParsedTypeOverride[]} unmatchedEntries
28
+ * @returns {void}
29
+ */
30
+ export declare const warnUnmatchedTypeOverrides: (unmatchedEntries: IParsedTypeOverride[]) => void;
@@ -0,0 +1,93 @@
1
+ import { formatTypeOverrideLabel } from './typeOverridesParser.js';
2
+ /**
3
+ * Collect the entries matching a column, most specific first: the
4
+ * schema-qualified column key, the unqualified column key, the schema-qualified
5
+ * type key, then the unqualified type key. Matching is case-insensitive. The
6
+ * schema of a type key is the schema the enum type is defined in for a database
7
+ * enum column, and the table schema otherwise.
8
+ * @param {ITableMetadata} table
9
+ * @param {IColumnMetadata} column
10
+ * @param {IParsedTypeOverrides} overrides
11
+ * @returns {IParsedTypeOverride[]}
12
+ */
13
+ const findMatchingEntries = (table, column, overrides) => {
14
+ const schema = table.schema ? table.schema.toLowerCase() : undefined;
15
+ const typeSchema = column.enumType ? column.enumType.schema.toLowerCase() : schema;
16
+ const columnKey = `${table.originName}.${column.originName}`.toLowerCase();
17
+ const typeKey = column.type.toLowerCase();
18
+ const candidates = [
19
+ schema !== undefined ? overrides.columns.get(`${schema}.${columnKey}`) : undefined,
20
+ overrides.columns.get(columnKey),
21
+ typeSchema !== undefined ? overrides.types.get(`${typeSchema}.${typeKey}`) : undefined,
22
+ overrides.types.get(typeKey),
23
+ ];
24
+ return candidates.filter(entry => entry !== undefined);
25
+ };
26
+ /**
27
+ * Resolve each side of the override from the most specific entry that sets it.
28
+ * @param {IParsedTypeOverride[]} entries
29
+ * @returns {IColumnTypeOverride}
30
+ */
31
+ const resolveColumnTypeOverride = (entries) => {
32
+ const tsType = entries.find(entry => entry.tsType !== undefined)?.tsType;
33
+ const dataType = entries.find(entry => entry.dataType !== undefined)?.dataType;
34
+ return {
35
+ ...tsType && { tsType },
36
+ ...dataType && { dataType },
37
+ };
38
+ };
39
+ /**
40
+ * Attach the type override resolved for a column. The generated `sequelizeType`
41
+ * and `dataType` stay untouched, so the TypeScript type the generator derives
42
+ * from them is unaffected by a data type override.
43
+ * @param {IColumnMetadata} column
44
+ * @param {IColumnTypeOverride} typeOverride
45
+ * @returns {IColumnMetadata}
46
+ */
47
+ const applyColumnTypeOverride = (column, typeOverride) => ({
48
+ ...column,
49
+ typeOverride,
50
+ });
51
+ /**
52
+ * Apply type overrides to every column they match, and report the entries that
53
+ * matched no column.
54
+ * @param {ITablesMetadata} tablesMetadata
55
+ * @param {IParsedTypeOverrides} overrides
56
+ * @returns {ITypeOverridesApplication}
57
+ */
58
+ export const applyTypeOverrides = (tablesMetadata, overrides) => {
59
+ const matchedEntries = new Set();
60
+ const overridden = {};
61
+ for (const [tableKey, table] of Object.entries(tablesMetadata)) {
62
+ const columns = {};
63
+ for (const [columnKey, column] of Object.entries(table.columns)) {
64
+ const entries = findMatchingEntries(table, column, overrides);
65
+ entries.forEach(entry => matchedEntries.add(entry));
66
+ columns[columnKey] = entries.length > 0
67
+ ? applyColumnTypeOverride(column, resolveColumnTypeOverride(entries))
68
+ : column;
69
+ }
70
+ overridden[tableKey] = { ...table, columns };
71
+ }
72
+ const unmatchedEntries = [...overrides.types.values(), ...overrides.columns.values()]
73
+ .filter(entry => !matchedEntries.has(entry));
74
+ return { tablesMetadata: overridden, unmatchedEntries };
75
+ };
76
+ /**
77
+ * Build the warning listing the type override entries that matched no column.
78
+ * @param {IParsedTypeOverride[]} unmatchedEntries
79
+ * @returns {string}
80
+ */
81
+ export const buildUnmatchedTypeOverridesWarning = (unmatchedEntries) => `Type overrides matched no column: ` +
82
+ `${unmatchedEntries.map(entry => formatTypeOverrideLabel(entry.section, entry.key)).join(', ')}. ` +
83
+ `Check them for typos; table filters may exclude the tables they target.`;
84
+ /**
85
+ * Warn once about the type override entries that matched no column.
86
+ * @param {IParsedTypeOverride[]} unmatchedEntries
87
+ * @returns {void}
88
+ */
89
+ export const warnUnmatchedTypeOverrides = (unmatchedEntries) => {
90
+ if (unmatchedEntries.length > 0) {
91
+ console.warn('[WARNING]', buildUnmatchedTypeOverridesWarning(unmatchedEntries));
92
+ }
93
+ };
@@ -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>;