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.
Files changed (42) 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 +155 -15
  7. package/build/builders/NativeModelRenderer.d.ts +4 -3
  8. package/build/builders/NativeModelRenderer.js +41 -13
  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 +12 -1
  13. package/build/builders/jsonSupport.d.ts +69 -0
  14. package/build/builders/jsonSupport.js +89 -0
  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.d.ts +20 -2
  22. package/build/builders/utils.js +42 -5
  23. package/build/config/IConfig.d.ts +22 -0
  24. package/build/dialects/Dialect.d.ts +57 -3
  25. package/build/dialects/DialectMSSQL.d.ts +2 -2
  26. package/build/dialects/DialectMSSQL.js +1 -6
  27. package/build/dialects/DialectMariaDB.d.ts +13 -2
  28. package/build/dialects/DialectMariaDB.js +46 -6
  29. package/build/dialects/DialectMySQL.d.ts +2 -2
  30. package/build/dialects/DialectMySQL.js +2 -6
  31. package/build/dialects/DialectPostgres.d.ts +36 -3
  32. package/build/dialects/DialectPostgres.js +111 -13
  33. package/build/dialects/DialectSQLite.d.ts +2 -2
  34. package/build/dialects/DialectSQLite.js +1 -6
  35. package/build/dialects/dataTypes.d.ts +26 -4
  36. package/build/dialects/dataTypes.js +50 -5
  37. package/build/dialects/mariadbJson.d.ts +39 -0
  38. package/build/dialects/mariadbJson.js +52 -0
  39. package/build/dialects/utils.d.ts +0 -6
  40. package/build/dialects/utils.js +0 -10
  41. package/build/index.d.ts +2 -2
  42. package/package.json +3 -3
@@ -3,14 +3,130 @@ import path from 'path';
3
3
  import * as ts from 'typescript';
4
4
  import { Linter } from '../lint/index.js';
5
5
  import { resolveFormat, shouldNoticeIgnoredStrict, STRICT_IGNORED_NOTICE } from '../config/format.js';
6
+ import { DATA_TYPE_NAMESPACES } from '../dialects/dataTypes.js';
6
7
  import { isErrnoException } from '../utils/errors.js';
7
8
  import { Builder } from './Builder.js';
8
9
  import { resolveAssociationPropertyName } from './associationNaming.js';
9
10
  import { renderNativeFiles, writeGeneratedFiles } from './generatedFile.js';
10
11
  import { warnWhenDecoratorsDependencyIsMissing } from './decoratorsDependency.js';
11
- import { nodeToString, generateArrowDecorator, generateNamedImports, generateObjectLiteralDecorator, generateIndexExport, } from './utils.js';
12
+ import { attachColumnCommentJsDoc, buildDataTypeExpression, nodeToString, createGenericTypeReference, createTypeNodeFromName, generateArrowDecorator, generateNamedImports, generateObjectLiteralDecorator, generateIndexExport, } from './utils.js';
13
+ import { buildJsonTypeImport, JSON_SUPPORT_FILE_NAME, JSON_TYPE_NAME, renderJsonSupportFile, tableHasJsonColumn, tablesHaveJsonColumn, warnJsonSupportFileNameCollision, } from './jsonSupport.js';
14
+ import { assignSharedEnumTypeNames, buildEnumColumnTypeNode, buildEnumTypesImport, ENUM_SUPPORT_FILE_NAME, renderEnumSupportFile, tablesHaveSharedEnumType, warnEnumSupportFileNameCollision, } from './enumSupport.js';
15
+ import { indexTablesByModelName } from './nativeAttributes.js';
16
+ import { collectSequelizeImports } from './nativeAssociations.js';
17
+ import { UNMAPPED_TS_TYPE_BY_FORMAT, warnUnmappedTypes } from './unmappedTypes.js';
18
+ import { loadTypeOverrides } from './typeOverridesParser.js';
19
+ import { applyTypeOverrides, warnUnmatchedTypeOverrides } from './typeOverrides.js';
12
20
  export { resolveAssociationPropertyName } from './associationNaming.js';
13
21
  const foreignKeyDecorator = 'ForeignKey';
22
+ /**
23
+ * Names every decorators model file imports from `sequelize-typescript`.
24
+ */
25
+ const DECORATORS_BASE_IMPORTS = [
26
+ 'Model',
27
+ 'Table',
28
+ 'Column',
29
+ 'DataType',
30
+ 'Index',
31
+ 'Sequelize',
32
+ foreignKeyDecorator,
33
+ ];
34
+ /**
35
+ * Association decorators a decorators model file may import from `sequelize-typescript`.
36
+ */
37
+ const ASSOCIATION_DECORATORS = ['BelongsTo', 'BelongsToMany', 'HasMany', 'HasOne'];
38
+ /**
39
+ * Global type names a generated model references.
40
+ */
41
+ const REFERENCED_GLOBAL_TYPE_NAMES = ['Date'];
42
+ /**
43
+ * Leftmost identifier of an entity name, e.g. `ns` for `ns.Inner.Type`.
44
+ * @param {ts.EntityName} name
45
+ * @returns {ts.Identifier}
46
+ */
47
+ const leftmostIdentifier = (name) => ts.isIdentifier(name) ? name : leftmostIdentifier(name.left);
48
+ /**
49
+ * Collect the identifiers a type node references by name: the leftmost
50
+ * identifier of every type reference and type query.
51
+ * @param {ts.Node} node
52
+ * @param {Set<string>} identifiers
53
+ * @returns {void}
54
+ */
55
+ const collectReferencedIdentifiers = (node, identifiers) => {
56
+ if (ts.isTypeReferenceNode(node)) {
57
+ identifiers.add(leftmostIdentifier(node.typeName).text);
58
+ }
59
+ else if (ts.isTypeQueryNode(node)) {
60
+ identifiers.add(leftmostIdentifier(node.exprName).text);
61
+ }
62
+ ts.forEachChild(node, child => collectReferencedIdentifiers(child, identifiers));
63
+ };
64
+ /**
65
+ * Collect the identifiers the enum shared type names must not take in either
66
+ * format: the generated model names, and every other name a model file declares
67
+ * (decorators attributes interfaces), imports (`sequelize`/`sequelize-typescript`
68
+ * names, the `Json` shared type) or references (global types, dialect type
69
+ * names, type override TypeScript types).
70
+ * @param {ITablesMetadata} tablesMetadata
71
+ * @param {Dialect} dialect
72
+ * @returns {IReservedIdentifiers}
73
+ */
74
+ const collectReservedIdentifiers = (tablesMetadata, dialect) => {
75
+ const tables = Object.values(tablesMetadata);
76
+ const tablesByModel = indexTablesByModelName(tablesMetadata);
77
+ const nonModelIdentifiers = new Set([
78
+ ...DECORATORS_BASE_IMPORTS,
79
+ ...ASSOCIATION_DECORATORS,
80
+ ...REFERENCED_GLOBAL_TYPE_NAMES,
81
+ JSON_TYPE_NAME,
82
+ ]);
83
+ for (const table of tables) {
84
+ nonModelIdentifiers.add(`${table.name}Attributes`);
85
+ collectSequelizeImports(table, tablesByModel).forEach(name => nonModelIdentifiers.add(name));
86
+ for (const column of Object.values(table.columns)) {
87
+ const jsType = dialect.mapDbTypeToJs(column.type);
88
+ if (jsType) {
89
+ nonModelIdentifiers.add(jsType.replace(/(\[\])+$/, ''));
90
+ }
91
+ if (column.typeOverride?.tsType) {
92
+ collectReferencedIdentifiers(column.typeOverride.tsType, nonModelIdentifiers);
93
+ }
94
+ }
95
+ }
96
+ return { modelNames: new Set(tables.map(table => table.name)), nonModelIdentifiers };
97
+ };
98
+ /**
99
+ * Build the TypeScript type node of a column: a type override's TypeScript type,
100
+ * the shared `Json` type for a JSON column, the enum shared type for a database
101
+ * enum column, otherwise the dialect JS mapping, or `any` for an unmapped type.
102
+ * @param {IColumnMetadata} col
103
+ * @param {Dialect} dialect
104
+ * @returns {ts.TypeNode}
105
+ */
106
+ const buildColumnTypeNode = (col, dialect) => {
107
+ const overriddenTsType = col.typeOverride?.tsType;
108
+ if (overriddenTsType) {
109
+ return overriddenTsType;
110
+ }
111
+ if (col.isJson) {
112
+ return createGenericTypeReference(JSON_TYPE_NAME, []);
113
+ }
114
+ return col.enumType
115
+ ? buildEnumColumnTypeNode(col.enumType)
116
+ : createTypeNodeFromName(dialect.mapDbTypeToJs(col.type) ?? UNMAPPED_TS_TYPE_BY_FORMAT.decorators);
117
+ };
118
+ /**
119
+ * Build the `type` option of the `@Column` decorator: a type override's data type
120
+ * is built as a compiler expression, otherwise the rendered data type expression.
121
+ * @param {IColumnMetadata} col
122
+ * @returns {string | ts.Expression | undefined}
123
+ */
124
+ const buildColumnDecoratorType = (col) => {
125
+ const overriddenDataType = col.typeOverride?.dataType;
126
+ return overriddenDataType
127
+ ? buildDataTypeExpression(overriddenDataType, DATA_TYPE_NAMESPACES.decorators)
128
+ : col.dataType;
129
+ };
14
130
  /**
15
131
  * Build the `@Table` decorator options for a table. The `hasTrigger` flag is
16
132
  * emitted only when the source table carries at least one enabled trigger.
@@ -80,12 +196,13 @@ export class ModelBuilder extends Builder {
80
196
  */
81
197
  static buildColumnPropertyDecl(col, dialect) {
82
198
  const buildColumnDecoratorProps = (col) => {
199
+ const columnType = buildColumnDecoratorType(col);
83
200
  const props = {
84
201
  ...col.originName && col.name !== col.originName && { field: col.originName },
85
202
  ...col.primaryKey && { primaryKey: col.primaryKey },
86
203
  ...col.autoIncrement && { autoIncrement: col.autoIncrement },
87
204
  ...col.allowNull && { allowNull: col.allowNull },
88
- ...col.dataType && { type: col.dataType },
205
+ ...columnType && { type: columnType },
89
206
  ...col.comment && { comment: col.comment },
90
207
  ...col.defaultValue !== undefined && { defaultValue: dialect.mapDefaultValueToSequelize(col.defaultValue) },
91
208
  };
@@ -100,7 +217,7 @@ export class ModelBuilder extends Builder {
100
217
  };
101
218
  return props;
102
219
  };
103
- return ts.factory.createPropertyDeclaration([
220
+ const propertyDeclaration = ts.factory.createPropertyDeclaration([
104
221
  ...(col.foreignKey ?
105
222
  [generateArrowDecorator(foreignKeyDecorator, [col.foreignKey.targetModel])]
106
223
  : []),
@@ -109,7 +226,8 @@ export class ModelBuilder extends Builder {
109
226
  col.indices.map(index => generateObjectLiteralDecorator('Index', buildIndexDecoratorProps(index)))
110
227
  : [])
111
228
  ], col.name, (col.autoIncrement || col.allowNull || col.defaultValue !== undefined) ?
112
- ts.factory.createToken(ts.SyntaxKind.QuestionToken) : ts.factory.createToken(ts.SyntaxKind.ExclamationToken), ts.factory.createTypeReferenceNode(dialect.mapDbTypeToJs(col.type) ?? 'any', undefined), undefined);
229
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : ts.factory.createToken(ts.SyntaxKind.ExclamationToken), buildColumnTypeNode(col, dialect), undefined);
230
+ return attachColumnCommentJsDoc(propertyDeclaration, col.comment);
113
231
  }
114
232
  /**
115
233
  * Build table class declaration
@@ -122,13 +240,7 @@ export class ModelBuilder extends Builder {
122
240
  let generatedCode = '';
123
241
  // Named imports from sequelize-typescript
124
242
  generatedCode += nodeToString(generateNamedImports([
125
- 'Model',
126
- 'Table',
127
- 'Column',
128
- 'DataType',
129
- 'Index',
130
- 'Sequelize',
131
- foreignKeyDecorator,
243
+ ...DECORATORS_BASE_IMPORTS,
132
244
  ...new Set(tableMetadata.associations?.map(a => a.associationName)),
133
245
  ], 'sequelize-typescript'));
134
246
  generatedCode += '\n';
@@ -149,14 +261,25 @@ export class ModelBuilder extends Builder {
149
261
  generatedCode += nodeToString(generateNamedImports([modelName], `./${modelName}`));
150
262
  generatedCode += '\n';
151
263
  });
264
+ // Type-only import of the shared Json type for JSON/JSONB columns.
265
+ if (tableHasJsonColumn(tableMetadata)) {
266
+ generatedCode += nodeToString(buildJsonTypeImport());
267
+ generatedCode += '\n';
268
+ }
269
+ // Type-only import of the enum shared types the model uses.
270
+ const enumTypesImport = buildEnumTypesImport(tableMetadata);
271
+ if (enumTypesImport) {
272
+ generatedCode += nodeToString(enumTypesImport);
273
+ generatedCode += '\n';
274
+ }
152
275
  const attributesInterfaceName = `${name}Attributes`;
153
276
  if (strict) {
154
277
  generatedCode += '\n';
155
278
  const attributesInterface = ts.factory.createInterfaceDeclaration([
156
279
  ts.factory.createToken(ts.SyntaxKind.ExportKeyword),
157
280
  ], ts.factory.createIdentifier(attributesInterfaceName), undefined, undefined, [
158
- ...(Object.values(columns).map(c => ts.factory.createPropertySignature(undefined, ts.factory.createIdentifier(c.name), c.autoIncrement || c.allowNull || c.defaultValue !== undefined ?
159
- ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, ts.factory.createTypeReferenceNode(dialect.mapDbTypeToJs(c.type) ?? 'any', undefined))))
281
+ ...(Object.values(columns).map(c => attachColumnCommentJsDoc(ts.factory.createPropertySignature(undefined, ts.factory.createIdentifier(c.name), c.autoIncrement || c.allowNull || c.defaultValue !== undefined ?
282
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, buildColumnTypeNode(c, dialect)), c.comment)))
160
283
  ]);
161
284
  generatedCode += nodeToString(attributesInterface);
162
285
  generatedCode += '\n';
@@ -202,7 +325,8 @@ export class ModelBuilder extends Builder {
202
325
  .join('\n');
203
326
  }
204
327
  /**
205
- * Render the decorators output as one file per table plus the index barrel.
328
+ * Render the decorators output as one file per table, the shared type files the
329
+ * models use, and the index barrel.
206
330
  * @param {ITablesMetadata} tablesMetadata
207
331
  * @param {Dialect} dialect
208
332
  * @param {boolean | undefined} strict
@@ -213,6 +337,14 @@ export class ModelBuilder extends Builder {
213
337
  fileName: `${tableMetadata.name}.ts`,
214
338
  content: ModelBuilder.buildTableClassDeclaration(tableMetadata, dialect, strict),
215
339
  }));
340
+ if (tablesHaveJsonColumn(tablesMetadata)) {
341
+ warnJsonSupportFileNameCollision(tablesMetadata);
342
+ files.push({ fileName: JSON_SUPPORT_FILE_NAME, content: renderJsonSupportFile() });
343
+ }
344
+ if (tablesHaveSharedEnumType(tablesMetadata)) {
345
+ warnEnumSupportFileNameCollision(tablesMetadata);
346
+ files.push({ fileName: ENUM_SUPPORT_FILE_NAME, content: renderEnumSupportFile(tablesMetadata) });
347
+ }
216
348
  files.push({ fileName: 'index.ts', content: ModelBuilder.buildIndexExports(tablesMetadata) });
217
349
  return files;
218
350
  }
@@ -229,12 +361,20 @@ export class ModelBuilder extends Builder {
229
361
  if (shouldNoticeIgnoredStrict(this.config)) {
230
362
  console.warn(STRICT_IGNORED_NOTICE);
231
363
  }
364
+ const typeOverrides = await loadTypeOverrides(this.config.metadata);
232
365
  console.log(`Fetching metadata from source`);
233
- const tablesMetadata = await this.dialect.buildTablesMetadata(this.config);
366
+ let tablesMetadata = await this.dialect.buildTablesMetadata(this.config);
234
367
  if (Object.keys(tablesMetadata).length === 0) {
235
368
  console.warn(`Couldn't find any table for database ${this.config.connection.database} and provided filters`);
236
369
  return;
237
370
  }
371
+ if (typeOverrides) {
372
+ const application = applyTypeOverrides(tablesMetadata, typeOverrides);
373
+ tablesMetadata = application.tablesMetadata;
374
+ warnUnmatchedTypeOverrides(application.unmatchedEntries);
375
+ }
376
+ tablesMetadata = assignSharedEnumTypeNames(tablesMetadata, collectReservedIdentifiers(tablesMetadata, this.dialect));
377
+ warnUnmappedTypes(tablesMetadata, this.dialect, format);
238
378
  // Check if output dir exists
239
379
  try {
240
380
  await fs.access(outDir);
@@ -6,8 +6,9 @@ import { INativeIndex } from './nativeAttributes.js';
6
6
  import { IMixinDeclaration } from './nativeAssociations.js';
7
7
  /**
8
8
  * Build the declared type node of a column attribute. Foreign keys to generated
9
- * models are branded with `ForeignKey<Target["key"]>`; other columns are wrapped
10
- * with `CreationOptional` and `| null` according to their attribute kind.
9
+ * models are branded with `ForeignKey<Target["key"]>`, or with the type override's
10
+ * TypeScript type when one is set; other columns are wrapped with
11
+ * `CreationOptional` and `| null` according to their attribute kind.
11
12
  * @param {IColumnMetadata} column
12
13
  * @param {ITableMetadata} table
13
14
  * @param {Dialect} dialect
@@ -89,7 +90,7 @@ export declare const buildInitModelMethod: (table: ITableMetadata, dialect: Dial
89
90
  export declare const buildModelClassDeclaration: (table: ITableMetadata, dialect: Dialect, tablesByModel: ReadonlyMap<string, ITableMetadata>) => ts.ClassDeclaration;
90
91
  /**
91
92
  * Render one native model source file: the `sequelize` named import, the
92
- * cross-model `import type` declarations and the model class.
93
+ * cross-model and shared type `import type` declarations and the model class.
93
94
  * @param {ITableMetadata} table
94
95
  * @param {Dialect} dialect
95
96
  * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
@@ -1,10 +1,13 @@
1
1
  import * as ts from 'typescript';
2
2
  import { DATA_TYPE_NAMESPACES } from '../dialects/dataTypes.js';
3
- import { buildDataTypeExpression, buildObjectLiteralExpression, createGenericTypeReference, createIndexedAccessTypeNode, createTypeNodeFromName, generateNamedImports, generateTypeOnlyImport, nodeToString, } from './utils.js';
3
+ import { attachColumnCommentJsDoc, buildDataTypeExpression, buildObjectLiteralExpression, createGenericTypeReference, createIndexedAccessTypeNode, createTypeNodeFromName, generateNamedImports, generateTypeOnlyImport, nodeToString, } from './utils.js';
4
4
  import { buildDefaultValueExpression, parseDefaultValue } from './defaultValues.js';
5
+ import { UNMAPPED_TS_TYPE_BY_FORMAT } from './unmappedTypes.js';
5
6
  import { classifyAttribute, collectTableIndexes, COLUMN_OPTION_KEYS, isParanoidColumn, resolveForeignKeyTargetAttribute, resolvePrimaryKeyAttribute, TIMESTAMP_ATTRIBUTES, } from './nativeAttributes.js';
6
7
  import { buildAssociationMixinDeclarations, collectModelTypeImports, collectSequelizeImports, isToManyAssociation, resolveAssociationForeignKey, } from './nativeAssociations.js';
7
8
  import { resolveAssociationPropertyName } from './associationNaming.js';
9
+ import { buildJsonTypeImport, JSON_TYPE_NAME, tableHasJsonColumn } from './jsonSupport.js';
10
+ import { buildEnumColumnTypeNode, buildEnumTypesImport } from './enumSupport.js';
8
11
  const NATIVE_NAMESPACE = DATA_TYPE_NAMESPACES.native;
9
12
  /**
10
13
  * Union a type node with the null literal type, flattening an existing union so
@@ -33,27 +36,41 @@ const buildDeclareField = (name, type, options = {}) => {
33
36
  };
34
37
  /**
35
38
  * Build the base TypeScript type node of a column, before nullability and brand
36
- * wrapping. Paranoid soft-delete columns are always `Date`; enum columns become a
37
- * string-literal union; everything else maps through the dialect JS mapping.
39
+ * wrapping. A type override's TypeScript type wins; otherwise paranoid soft-delete
40
+ * columns are always `Date`, JSON columns use the shared `Json` type, database
41
+ * enum columns use their enum shared type, other enum columns become a
42
+ * string-literal union, and everything else maps through the dialect JS mapping,
43
+ * or is `unknown` for an unmapped type.
38
44
  * @param {IColumnMetadata} column
39
45
  * @param {ITableMetadata} table
40
46
  * @param {Dialect} dialect
41
47
  * @returns {ts.TypeNode}
42
48
  */
43
49
  const buildBaseTypeNode = (column, table, dialect) => {
50
+ const overriddenTsType = column.typeOverride?.tsType;
51
+ if (overriddenTsType) {
52
+ return overriddenTsType;
53
+ }
44
54
  if (isParanoidColumn(column, table)) {
45
55
  return createTypeNodeFromName('Date');
46
56
  }
57
+ if (column.isJson) {
58
+ return createGenericTypeReference(JSON_TYPE_NAME, []);
59
+ }
60
+ if (column.enumType) {
61
+ return buildEnumColumnTypeNode(column.enumType);
62
+ }
47
63
  const { sequelizeType } = column;
48
64
  if (sequelizeType && sequelizeType.key === 'ENUM' && sequelizeType.args.length > 0) {
49
65
  return ts.factory.createUnionTypeNode(sequelizeType.args.map(arg => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(String(arg)))));
50
66
  }
51
- return createTypeNodeFromName(dialect.mapDbTypeToJs(column.type));
67
+ return createTypeNodeFromName(dialect.mapDbTypeToJs(column.type) ?? UNMAPPED_TS_TYPE_BY_FORMAT.native);
52
68
  };
53
69
  /**
54
70
  * Build the declared type node of a column attribute. Foreign keys to generated
55
- * models are branded with `ForeignKey<Target["key"]>`; other columns are wrapped
56
- * with `CreationOptional` and `| null` according to their attribute kind.
71
+ * models are branded with `ForeignKey<Target["key"]>`, or with the type override's
72
+ * TypeScript type when one is set; other columns are wrapped with
73
+ * `CreationOptional` and `| null` according to their attribute kind.
57
74
  * @param {IColumnMetadata} column
58
75
  * @param {ITableMetadata} table
59
76
  * @param {Dialect} dialect
@@ -69,9 +86,9 @@ export const buildAttributeTypeNode = (column, table, dialect, tablesByModel) =>
69
86
  const targetAttribute = target
70
87
  ? resolveForeignKeyTargetAttribute(column.foreignKey, target)
71
88
  : undefined;
72
- const referenced = targetAttribute
89
+ const referenced = column.typeOverride?.tsType ?? (targetAttribute
73
90
  ? createIndexedAccessTypeNode(column.foreignKey.targetModel, targetAttribute)
74
- : ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
91
+ : ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword));
75
92
  const inner = kind === 'foreignKeyNullable' ? buildNullableTypeNode(referenced) : referenced;
76
93
  return createGenericTypeReference('ForeignKey', [inner]);
77
94
  }
@@ -95,7 +112,7 @@ export const buildAttributeTypeNode = (column, table, dialect, tablesByModel) =>
95
112
  * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
96
113
  * @returns {ts.PropertyDeclaration}
97
114
  */
98
- export const buildAttributeDeclaration = (column, table, dialect, tablesByModel) => buildDeclareField(column.name, buildAttributeTypeNode(column, table, dialect, tablesByModel));
115
+ export const buildAttributeDeclaration = (column, table, dialect, tablesByModel) => attachColumnCommentJsDoc(buildDeclareField(column.name, buildAttributeTypeNode(column, table, dialect, tablesByModel)), column.comment);
99
116
  /**
100
117
  * Build the `declare createdAt`/`declare updatedAt` members of a model, emitted
101
118
  * only when timestamps are enabled.
@@ -172,11 +189,13 @@ export const buildColumnInitOptions = (column, table, dialect) => {
172
189
  const options = {};
173
190
  for (const key of COLUMN_OPTION_KEYS) {
174
191
  switch (key) {
175
- case 'type':
176
- if (column.sequelizeType) {
177
- options.type = buildDataTypeExpression(column.sequelizeType, NATIVE_NAMESPACE);
192
+ case 'type': {
193
+ const dataType = column.typeOverride?.dataType ?? column.sequelizeType;
194
+ if (dataType) {
195
+ options.type = buildDataTypeExpression(dataType, NATIVE_NAMESPACE);
178
196
  }
179
197
  break;
198
+ }
180
199
  case 'primaryKey':
181
200
  if (column.primaryKey) {
182
201
  options.primaryKey = true;
@@ -334,7 +353,7 @@ export const buildModelClassDeclaration = (table, dialect, tablesByModel) => {
334
353
  };
335
354
  /**
336
355
  * Render one native model source file: the `sequelize` named import, the
337
- * cross-model `import type` declarations and the model class.
356
+ * cross-model and shared type `import type` declarations and the model class.
338
357
  * @param {ITableMetadata} table
339
358
  * @param {Dialect} dialect
340
359
  * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
@@ -347,6 +366,15 @@ export const renderNativeModelFile = (table, dialect, tablesByModel) => {
347
366
  code += nodeToString(generateTypeOnlyImport([modelName], `./${modelName}`));
348
367
  code += '\n';
349
368
  }
369
+ if (tableHasJsonColumn(table)) {
370
+ code += nodeToString(buildJsonTypeImport());
371
+ code += '\n';
372
+ }
373
+ const enumTypesImport = buildEnumTypesImport(table);
374
+ if (enumTypesImport) {
375
+ code += nodeToString(enumTypesImport);
376
+ code += '\n';
377
+ }
350
378
  code += '\n';
351
379
  code += nodeToString(buildModelClassDeclaration(table, dialect, tablesByModel));
352
380
  return code;
@@ -0,0 +1,104 @@
1
+ import * as ts from 'typescript';
2
+ import type { IColumnEnumType, IColumnMetadata, ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
3
+ /**
4
+ * Base name of the shared support file holding the enum shared types. A
5
+ * collision with a model name is reported by `warnEnumSupportFileNameCollision`.
6
+ */
7
+ export declare const ENUM_SUPPORT_FILE_BASENAME = "enums";
8
+ /**
9
+ * File name of the shared enum support file.
10
+ */
11
+ export declare const ENUM_SUPPORT_FILE_NAME = "enums.ts";
12
+ /**
13
+ * Sibling module specifier used by model files to import enum shared types.
14
+ */
15
+ export declare const ENUM_SUPPORT_MODULE_SPECIFIER = "./enums";
16
+ /**
17
+ * Suffix appended to an enum shared type name that clashes with a generated
18
+ * model name or another identifier declared or imported by a model file.
19
+ */
20
+ export declare const ENUM_RESERVED_NAME_SUFFIX = "Enum";
21
+ /**
22
+ * A database enum used by at least one generated column, with the identifier of
23
+ * its shared type.
24
+ */
25
+ export type ISharedEnumType = Pick<IColumnEnumType, 'schema' | 'name' | 'labels'> & {
26
+ typeName: string;
27
+ };
28
+ /**
29
+ * Report whether a column is typed with an enum shared type: an enum column
30
+ * whose TypeScript type no type override replaces.
31
+ * @param {IColumnMetadata} column
32
+ * @returns {boolean}
33
+ */
34
+ export declare const columnUsesSharedEnumType: (column: IColumnMetadata) => boolean;
35
+ /**
36
+ * Turn a database name into a Pascal-case identifier, dropping characters that
37
+ * are not valid in an identifier and prefixing a name that does not start with
38
+ * a valid identifier character.
39
+ * @param {string} name
40
+ * @returns {string}
41
+ */
42
+ export declare const toPascalCaseIdentifier: (name: string) => string;
43
+ /**
44
+ * Identifiers the shared enum type names must not take: the generated model
45
+ * names and every other identifier a model file declares, imports or
46
+ * references.
47
+ */
48
+ export interface IReservedIdentifiers {
49
+ modelNames: ReadonlySet<string>;
50
+ nonModelIdentifiers: ReadonlySet<string>;
51
+ }
52
+ /**
53
+ * Name the enum shared types of the run and record each name on the columns
54
+ * typed with it. Names are resolved over every database enum of the generated
55
+ * columns, so a type override never renames another enum; an enum whose
56
+ * TypeScript type a type override replaces on every column gets no shared type.
57
+ * A warning is emitted for every renamed enum that has a shared type.
58
+ * @param {ITablesMetadata} tablesMetadata
59
+ * @param {IReservedIdentifiers} reserved
60
+ * @returns {ITablesMetadata}
61
+ */
62
+ export declare const assignSharedEnumTypeNames: (tablesMetadata: ITablesMetadata, reserved: IReservedIdentifiers) => ITablesMetadata;
63
+ /**
64
+ * Build the TypeScript type of an enum column: a reference to its shared type,
65
+ * or the union of its labels when no shared type name is assigned, as an array
66
+ * for an enum array column.
67
+ * @param {IColumnEnumType} enumType
68
+ * @returns {ts.TypeNode}
69
+ */
70
+ export declare const buildEnumColumnTypeNode: (enumType: IColumnEnumType) => ts.TypeNode;
71
+ /**
72
+ * Report whether any table has a column typed with an enum shared type.
73
+ * @param {ITablesMetadata} tablesMetadata
74
+ * @returns {boolean}
75
+ */
76
+ export declare const tablesHaveSharedEnumType: (tablesMetadata: ITablesMetadata) => boolean;
77
+ /**
78
+ * Build the exported type alias of an enum shared type, e.g.
79
+ * `export type PlanTier = "free" | "pro";`, with the labels in database order.
80
+ * @param {ISharedEnumType} sharedEnumType
81
+ * @returns {ts.TypeAliasDeclaration}
82
+ */
83
+ export declare const buildSharedEnumTypeAliasDeclaration: (sharedEnumType: ISharedEnumType) => ts.TypeAliasDeclaration;
84
+ /**
85
+ * Render the shared enum support file: one exported type alias per enum shared
86
+ * type used by a generated column, sorted by type name.
87
+ * @param {ITablesMetadata} tablesMetadata
88
+ * @returns {string}
89
+ */
90
+ export declare const renderEnumSupportFile: (tablesMetadata: ITablesMetadata) => string;
91
+ /**
92
+ * Build the type-only import of the enum shared types a model uses, or
93
+ * undefined when it uses none.
94
+ * @param {ITableMetadata} table
95
+ * @returns {ts.ImportDeclaration | undefined}
96
+ */
97
+ export declare const buildEnumTypesImport: (table: ITableMetadata) => ts.ImportDeclaration | undefined;
98
+ /**
99
+ * Warn when a generated model name collides with the shared enum support file
100
+ * name, which would make both write to the same file.
101
+ * @param {ITablesMetadata} tablesMetadata
102
+ * @returns {void}
103
+ */
104
+ export declare const warnEnumSupportFileNameCollision: (tablesMetadata: ITablesMetadata) => void;