sequelize-typescript-generator 13.0.0 → 13.1.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 (40) hide show
  1. package/README.md +7 -7
  2. package/build/bin/utils.js +1 -1
  3. package/build/builders/ModelBuilder.js +26 -5
  4. package/build/builders/NativeModelRenderer.js +10 -2
  5. package/build/builders/generatedFile.js +5 -0
  6. package/build/builders/jsonSupport.d.ts +62 -0
  7. package/build/builders/jsonSupport.js +82 -0
  8. package/build/builders/utils.d.ts +20 -2
  9. package/build/builders/utils.js +39 -5
  10. package/build/dialects/Dialect.d.ts +1 -0
  11. package/build/dialects/DialectMariaDB.d.ts +11 -0
  12. package/build/dialects/DialectMariaDB.js +45 -0
  13. package/build/dialects/DialectMySQL.js +2 -1
  14. package/build/dialects/DialectPostgres.d.ts +3 -1
  15. package/build/dialects/DialectPostgres.js +38 -7
  16. package/build/dialects/dataTypes.d.ts +18 -4
  17. package/build/dialects/dataTypes.js +21 -4
  18. package/build/dialects/mariadbJson.d.ts +39 -0
  19. package/build/dialects/mariadbJson.js +52 -0
  20. package/package.json +5 -2
  21. package/.github/FUNDING.yml +0 -1
  22. package/.github/workflows/ci.yml +0 -224
  23. package/.vscode/launch.json +0 -212
  24. package/.vscode/tasks.json +0 -95
  25. package/CHANGELOG.md +0 -47
  26. package/CLAUDE.md +0 -13
  27. package/CONTEXT.md +0 -67
  28. package/docker-compose.yml +0 -65
  29. package/docs/adr/0001-esm-only-package.md +0 -36
  30. package/docs/adr/0002-native-default-output-format.md +0 -41
  31. package/docs/agents/domain.md +0 -51
  32. package/docs/agents/issue-tracker.md +0 -45
  33. package/docs/agents/triage-labels.md +0 -15
  34. package/docs/migration/12-to-13.md +0 -248
  35. package/docs/plans/v13-phase5-association-discovery.md +0 -168
  36. package/docs/plans/v13-phase6-native-emitter.md +0 -537
  37. package/docs/plans/v13-upgrade-plan.md +0 -137
  38. package/jest.config.cjs +0 -31
  39. package/scripts/check-no-sequelize-typescript.cjs +0 -68
  40. package/tsconfig.json +0 -22
package/README.md CHANGED
@@ -35,17 +35,17 @@
35
35
 
36
36
  This library is tested on the following databases:
37
37
 
38
- - Postgres (11, 14, 16)
39
- - Mysql (5, 8)
40
- - MariaDB (10, 11)
41
- - SQL Server (2019, 2022)
38
+ - Postgres (16, 18)
39
+ - Mysql (8, 9)
40
+ - MariaDB (11, 12)
41
+ - SQL Server (2022, 2025)
42
42
  - SQLite (3)
43
43
 
44
44
  ## Prerequisites
45
45
  See [sequelize-typescript installation](https://www.npmjs.com/package/sequelize-typescript#installation).
46
46
 
47
47
  You should also install the specific driver library for your database, see
48
- [sequelize documentation](https://sequelize.org/v5/manual/getting-started.html):
48
+ [sequelize documentation](https://sequelize.org/docs/v6/getting-started/):
49
49
  ```shell
50
50
  npm install -S pg pg-hstore # Postgres
51
51
  npm install -S mysql2 # MySQL
@@ -1460,8 +1460,8 @@ export const eslintDefaultConfig = [
1460
1460
  ];
1461
1461
  ```
1462
1462
 
1463
- You can provide your own rules by passing a config file to `--lint-file` / `-L`. Only ESLint flat config files are
1464
- accepted: `.mjs`, `.js`, or `.cjs` modules that export a config array. Legacy `.eslintrc*` files, and configs using
1463
+ You can provide your own rules by passing a config file to `--lint-file` / `-L`. The file must be a JS module that
1464
+ exports an ESLint flat config array (loaded via a dynamic `import()`). Legacy `.eslintrc*` files, and configs using
1465
1465
  `extends`, `env`, or a string `parser`, are rejected — see the
1466
1466
  [ESLint flat config migration guide](https://eslint.org/docs/latest/use/configure/migration-guide).
1467
1467
 
@@ -149,7 +149,7 @@ export const buildConfig = (argv) => {
149
149
  ...argv[aliasesMap.CASE] && { case: parseCase(argv[aliasesMap.CASE]) },
150
150
  ...argv[aliasesMap.ASSOCIATIONS_FILE] && { associationsFile: argv[aliasesMap.ASSOCIATIONS_FILE] },
151
151
  ...(argv[aliasesMap.ASSOCIATIONS] === false && { associations: false }),
152
- noViews: !!argv[aliasesMap.DISABLE_VIEWS],
152
+ noViews: !!argv[aliasesMap.DISABLE_VIEWS] || argv['views'] === false,
153
153
  },
154
154
  output: {
155
155
  outDir: argv[aliasesMap.OUTPUT_DIR] ?
@@ -8,9 +8,20 @@ import { Builder } from './Builder.js';
8
8
  import { resolveAssociationPropertyName } from './associationNaming.js';
9
9
  import { renderNativeFiles, writeGeneratedFiles } from './generatedFile.js';
10
10
  import { warnWhenDecoratorsDependencyIsMissing } from './decoratorsDependency.js';
11
- import { nodeToString, generateArrowDecorator, generateNamedImports, generateObjectLiteralDecorator, generateIndexExport, } from './utils.js';
11
+ import { attachColumnCommentJsDoc, nodeToString, createGenericTypeReference, createTypeNodeFromName, generateArrowDecorator, generateNamedImports, generateObjectLiteralDecorator, generateIndexExport, } from './utils.js';
12
+ import { buildJsonTypeImport, JSON_SUPPORT_FILE_NAME, JSON_TYPE_NAME, renderJsonSupportFile, tableHasJsonColumn, tablesHaveJsonColumn, warnJsonSupportFileNameCollision, } from './jsonSupport.js';
12
13
  export { resolveAssociationPropertyName } from './associationNaming.js';
13
14
  const foreignKeyDecorator = 'ForeignKey';
15
+ /**
16
+ * Build the TypeScript type node of a column: the shared `Json` type for a JSON
17
+ * column, otherwise the dialect JS mapping.
18
+ * @param {IColumnMetadata} col
19
+ * @param {Dialect} dialect
20
+ * @returns {ts.TypeNode}
21
+ */
22
+ const buildColumnTypeNode = (col, dialect) => col.isJson
23
+ ? createGenericTypeReference(JSON_TYPE_NAME, [])
24
+ : createTypeNodeFromName(dialect.mapDbTypeToJs(col.type) ?? 'any');
14
25
  /**
15
26
  * Build the `@Table` decorator options for a table. The `hasTrigger` flag is
16
27
  * emitted only when the source table carries at least one enabled trigger.
@@ -100,7 +111,7 @@ export class ModelBuilder extends Builder {
100
111
  };
101
112
  return props;
102
113
  };
103
- return ts.factory.createPropertyDeclaration([
114
+ const propertyDeclaration = ts.factory.createPropertyDeclaration([
104
115
  ...(col.foreignKey ?
105
116
  [generateArrowDecorator(foreignKeyDecorator, [col.foreignKey.targetModel])]
106
117
  : []),
@@ -109,7 +120,8 @@ export class ModelBuilder extends Builder {
109
120
  col.indices.map(index => generateObjectLiteralDecorator('Index', buildIndexDecoratorProps(index)))
110
121
  : [])
111
122
  ], 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);
123
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : ts.factory.createToken(ts.SyntaxKind.ExclamationToken), buildColumnTypeNode(col, dialect), undefined);
124
+ return attachColumnCommentJsDoc(propertyDeclaration, col.comment);
113
125
  }
114
126
  /**
115
127
  * Build table class declaration
@@ -149,14 +161,19 @@ export class ModelBuilder extends Builder {
149
161
  generatedCode += nodeToString(generateNamedImports([modelName], `./${modelName}`));
150
162
  generatedCode += '\n';
151
163
  });
164
+ // Type-only import of the shared Json type for JSON/JSONB columns.
165
+ if (tableHasJsonColumn(tableMetadata)) {
166
+ generatedCode += nodeToString(buildJsonTypeImport());
167
+ generatedCode += '\n';
168
+ }
152
169
  const attributesInterfaceName = `${name}Attributes`;
153
170
  if (strict) {
154
171
  generatedCode += '\n';
155
172
  const attributesInterface = ts.factory.createInterfaceDeclaration([
156
173
  ts.factory.createToken(ts.SyntaxKind.ExportKeyword),
157
174
  ], 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))))
175
+ ...(Object.values(columns).map(c => attachColumnCommentJsDoc(ts.factory.createPropertySignature(undefined, ts.factory.createIdentifier(c.name), c.autoIncrement || c.allowNull || c.defaultValue !== undefined ?
176
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, buildColumnTypeNode(c, dialect)), c.comment)))
160
177
  ]);
161
178
  generatedCode += nodeToString(attributesInterface);
162
179
  generatedCode += '\n';
@@ -213,6 +230,10 @@ export class ModelBuilder extends Builder {
213
230
  fileName: `${tableMetadata.name}.ts`,
214
231
  content: ModelBuilder.buildTableClassDeclaration(tableMetadata, dialect, strict),
215
232
  }));
233
+ if (tablesHaveJsonColumn(tablesMetadata)) {
234
+ warnJsonSupportFileNameCollision(tablesMetadata);
235
+ files.push({ fileName: JSON_SUPPORT_FILE_NAME, content: renderJsonSupportFile() });
236
+ }
216
237
  files.push({ fileName: 'index.ts', content: ModelBuilder.buildIndexExports(tablesMetadata) });
217
238
  return files;
218
239
  }
@@ -1,10 +1,11 @@
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
5
  import { classifyAttribute, collectTableIndexes, COLUMN_OPTION_KEYS, isParanoidColumn, resolveForeignKeyTargetAttribute, resolvePrimaryKeyAttribute, TIMESTAMP_ATTRIBUTES, } from './nativeAttributes.js';
6
6
  import { buildAssociationMixinDeclarations, collectModelTypeImports, collectSequelizeImports, isToManyAssociation, resolveAssociationForeignKey, } from './nativeAssociations.js';
7
7
  import { resolveAssociationPropertyName } from './associationNaming.js';
8
+ import { buildJsonTypeImport, JSON_TYPE_NAME, tableHasJsonColumn } from './jsonSupport.js';
8
9
  const NATIVE_NAMESPACE = DATA_TYPE_NAMESPACES.native;
9
10
  /**
10
11
  * Union a type node with the null literal type, flattening an existing union so
@@ -44,6 +45,9 @@ const buildBaseTypeNode = (column, table, dialect) => {
44
45
  if (isParanoidColumn(column, table)) {
45
46
  return createTypeNodeFromName('Date');
46
47
  }
48
+ if (column.isJson) {
49
+ return createGenericTypeReference(JSON_TYPE_NAME, []);
50
+ }
47
51
  const { sequelizeType } = column;
48
52
  if (sequelizeType && sequelizeType.key === 'ENUM' && sequelizeType.args.length > 0) {
49
53
  return ts.factory.createUnionTypeNode(sequelizeType.args.map(arg => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(String(arg)))));
@@ -95,7 +99,7 @@ export const buildAttributeTypeNode = (column, table, dialect, tablesByModel) =>
95
99
  * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
96
100
  * @returns {ts.PropertyDeclaration}
97
101
  */
98
- export const buildAttributeDeclaration = (column, table, dialect, tablesByModel) => buildDeclareField(column.name, buildAttributeTypeNode(column, table, dialect, tablesByModel));
102
+ export const buildAttributeDeclaration = (column, table, dialect, tablesByModel) => attachColumnCommentJsDoc(buildDeclareField(column.name, buildAttributeTypeNode(column, table, dialect, tablesByModel)), column.comment);
99
103
  /**
100
104
  * Build the `declare createdAt`/`declare updatedAt` members of a model, emitted
101
105
  * only when timestamps are enabled.
@@ -347,6 +351,10 @@ export const renderNativeModelFile = (table, dialect, tablesByModel) => {
347
351
  code += nodeToString(generateTypeOnlyImport([modelName], `./${modelName}`));
348
352
  code += '\n';
349
353
  }
354
+ if (tableHasJsonColumn(table)) {
355
+ code += nodeToString(buildJsonTypeImport());
356
+ code += '\n';
357
+ }
350
358
  code += '\n';
351
359
  code += nodeToString(buildModelClassDeclaration(table, dialect, tablesByModel));
352
360
  return code;
@@ -3,6 +3,7 @@ import path from 'path';
3
3
  import { indexTablesByModelName } from './nativeAttributes.js';
4
4
  import { renderNativeModelFile } from './NativeModelRenderer.js';
5
5
  import { renderInitModelsFile, renderNativeIndexFile } from './nativeWiring.js';
6
+ import { JSON_SUPPORT_FILE_NAME, renderJsonSupportFile, tablesHaveJsonColumn, warnJsonSupportFileNameCollision, } from './jsonSupport.js';
6
7
  /**
7
8
  * Render the complete set of native output files: one model file per table, the
8
9
  * `initModels.ts` wiring file and the `index.ts` barrel, in table order.
@@ -16,6 +17,10 @@ export const renderNativeFiles = (tablesMetadata, dialect) => {
16
17
  fileName: `${table.name}.ts`,
17
18
  content: renderNativeModelFile(table, dialect, tablesByModel),
18
19
  }));
20
+ if (tablesHaveJsonColumn(tablesMetadata)) {
21
+ warnJsonSupportFileNameCollision(tablesMetadata);
22
+ files.push({ fileName: JSON_SUPPORT_FILE_NAME, content: renderJsonSupportFile() });
23
+ }
19
24
  files.push({ fileName: 'initModels.ts', content: renderInitModelsFile(tablesMetadata, tablesByModel) });
20
25
  files.push({ fileName: 'index.ts', content: renderNativeIndexFile(tablesMetadata) });
21
26
  return files;
@@ -0,0 +1,62 @@
1
+ import * as ts from 'typescript';
2
+ import type { ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
3
+ /**
4
+ * Base name of the shared support file holding the recursive `Json` type. Chosen
5
+ * to be distinct from generated model names; a collision with a model name is
6
+ * reported by `findJsonSupportFileNameCollision`.
7
+ */
8
+ export declare const JSON_SUPPORT_FILE_BASENAME = "jsonType";
9
+ /**
10
+ * File name of the shared JSON support file.
11
+ */
12
+ export declare const JSON_SUPPORT_FILE_NAME = "jsonType.ts";
13
+ /**
14
+ * Exported type name of the recursive JSON union.
15
+ */
16
+ export declare const JSON_TYPE_NAME = "Json";
17
+ /**
18
+ * Sibling module specifier used by model files to import the `Json` type.
19
+ */
20
+ export declare const JSON_SUPPORT_MODULE_SPECIFIER = "./jsonType";
21
+ /**
22
+ * Build the recursive `Json` type alias declaration:
23
+ * `export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };`
24
+ * @returns {ts.TypeAliasDeclaration}
25
+ */
26
+ export declare const buildJsonTypeAliasDeclaration: () => ts.TypeAliasDeclaration;
27
+ /**
28
+ * Render the shared JSON support file source.
29
+ * @returns {string}
30
+ */
31
+ export declare const renderJsonSupportFile: () => string;
32
+ /**
33
+ * Build the type-only import of the `Json` type from the shared support file.
34
+ * @returns {ts.ImportDeclaration}
35
+ */
36
+ export declare const buildJsonTypeImport: () => ts.ImportDeclaration;
37
+ /**
38
+ * Report whether a table has at least one JSON/JSONB column.
39
+ * @param {ITableMetadata} table
40
+ * @returns {boolean}
41
+ */
42
+ export declare const tableHasJsonColumn: (table: ITableMetadata) => boolean;
43
+ /**
44
+ * Report whether any table has at least one JSON/JSONB column.
45
+ * @param {ITablesMetadata} tablesMetadata
46
+ * @returns {boolean}
47
+ */
48
+ export declare const tablesHaveJsonColumn: (tablesMetadata: ITablesMetadata) => boolean;
49
+ /**
50
+ * Find a generated model whose name collides with the shared support file name,
51
+ * returning the model name, or undefined when there is no collision.
52
+ * @param {ITablesMetadata} tablesMetadata
53
+ * @returns {string | undefined}
54
+ */
55
+ export declare const findJsonSupportFileNameCollision: (tablesMetadata: ITablesMetadata) => string | undefined;
56
+ /**
57
+ * Warn when a generated model name collides with the shared JSON support file
58
+ * name, which would make both write to the same file.
59
+ * @param {ITablesMetadata} tablesMetadata
60
+ * @returns {void}
61
+ */
62
+ export declare const warnJsonSupportFileNameCollision: (tablesMetadata: ITablesMetadata) => void;
@@ -0,0 +1,82 @@
1
+ import * as ts from 'typescript';
2
+ import { generateTypeOnlyImport, nodeToString } from './utils.js';
3
+ /**
4
+ * Base name of the shared support file holding the recursive `Json` type. Chosen
5
+ * to be distinct from generated model names; a collision with a model name is
6
+ * reported by `findJsonSupportFileNameCollision`.
7
+ */
8
+ export const JSON_SUPPORT_FILE_BASENAME = 'jsonType';
9
+ /**
10
+ * File name of the shared JSON support file.
11
+ */
12
+ export const JSON_SUPPORT_FILE_NAME = `${JSON_SUPPORT_FILE_BASENAME}.ts`;
13
+ /**
14
+ * Exported type name of the recursive JSON union.
15
+ */
16
+ export const JSON_TYPE_NAME = 'Json';
17
+ /**
18
+ * Sibling module specifier used by model files to import the `Json` type.
19
+ */
20
+ export const JSON_SUPPORT_MODULE_SPECIFIER = `./${JSON_SUPPORT_FILE_BASENAME}`;
21
+ /**
22
+ * Build the recursive `Json` type alias declaration:
23
+ * `export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };`
24
+ * @returns {ts.TypeAliasDeclaration}
25
+ */
26
+ export const buildJsonTypeAliasDeclaration = () => {
27
+ const jsonReference = ts.factory.createTypeReferenceNode(JSON_TYPE_NAME, undefined);
28
+ const indexSignature = ts.factory.createTypeLiteralNode([
29
+ ts.factory.createIndexSignature(undefined, [ts.factory.createParameterDeclaration(undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined)], jsonReference),
30
+ ]);
31
+ const union = ts.factory.createUnionTypeNode([
32
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
33
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
34
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
35
+ ts.factory.createLiteralTypeNode(ts.factory.createNull()),
36
+ ts.factory.createArrayTypeNode(jsonReference),
37
+ indexSignature,
38
+ ]);
39
+ return ts.factory.createTypeAliasDeclaration([ts.factory.createToken(ts.SyntaxKind.ExportKeyword)], JSON_TYPE_NAME, undefined, union);
40
+ };
41
+ /**
42
+ * Render the shared JSON support file source.
43
+ * @returns {string}
44
+ */
45
+ export const renderJsonSupportFile = () => nodeToString(buildJsonTypeAliasDeclaration());
46
+ /**
47
+ * Build the type-only import of the `Json` type from the shared support file.
48
+ * @returns {ts.ImportDeclaration}
49
+ */
50
+ export const buildJsonTypeImport = () => generateTypeOnlyImport([JSON_TYPE_NAME], JSON_SUPPORT_MODULE_SPECIFIER);
51
+ /**
52
+ * Report whether a table has at least one JSON/JSONB column.
53
+ * @param {ITableMetadata} table
54
+ * @returns {boolean}
55
+ */
56
+ export const tableHasJsonColumn = (table) => Object.values(table.columns).some(column => column.isJson === true);
57
+ /**
58
+ * Report whether any table has at least one JSON/JSONB column.
59
+ * @param {ITablesMetadata} tablesMetadata
60
+ * @returns {boolean}
61
+ */
62
+ export const tablesHaveJsonColumn = (tablesMetadata) => Object.values(tablesMetadata).some(tableHasJsonColumn);
63
+ /**
64
+ * Find a generated model whose name collides with the shared support file name,
65
+ * returning the model name, or undefined when there is no collision.
66
+ * @param {ITablesMetadata} tablesMetadata
67
+ * @returns {string | undefined}
68
+ */
69
+ export const findJsonSupportFileNameCollision = (tablesMetadata) => Object.values(tablesMetadata).find(table => table.name === JSON_SUPPORT_FILE_BASENAME)?.name;
70
+ /**
71
+ * Warn when a generated model name collides with the shared JSON support file
72
+ * name, which would make both write to the same file.
73
+ * @param {ITablesMetadata} tablesMetadata
74
+ * @returns {void}
75
+ */
76
+ export const warnJsonSupportFileNameCollision = (tablesMetadata) => {
77
+ const collision = findJsonSupportFileNameCollision(tablesMetadata);
78
+ if (collision) {
79
+ console.warn('[WARNING]', `Model '${collision}' collides with the shared JSON support file '${JSON_SUPPORT_FILE_NAME}'; ` +
80
+ `the generated model and the '${JSON_TYPE_NAME}' type file would overwrite each other.`);
81
+ }
82
+ };
@@ -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
  */
@@ -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 => typeof arg === 'number'
161
- ? createNumericLiteralExpression(arg)
162
- : ts.factory.createStringLiteral(arg)));
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
@@ -49,6 +49,7 @@ export interface IColumnMetadata {
49
49
  typeExt: string;
50
50
  dataType?: string;
51
51
  sequelizeType?: ISequelizeDataType;
52
+ isJson?: boolean;
52
53
  primaryKey: boolean;
53
54
  foreignKey?: IColumnForeignKeyMetadata;
54
55
  allowNull: boolean;
@@ -41,6 +41,17 @@ export declare class DialectMariaDB extends Dialect {
41
41
  * @returns {Promise<IColumnMetadata[]>}
42
42
  */
43
43
  protected fetchColumnsMetadata(connection: Sequelize, config: IConfig, table: string): Promise<IColumnMetadata[]>;
44
+ /**
45
+ * Fetch the database column names of a table backed by longtext with a
46
+ * `json_valid(...)` CHECK constraint. Detection reads information_schema.
47
+ * CHECK_CONSTRAINTS and falls back to parsing `SHOW CREATE TABLE` when that
48
+ * view is unavailable (MariaDB before 10.5).
49
+ * @param {Sequelize} connection
50
+ * @param {IConfig} config
51
+ * @param {string} table
52
+ * @returns {Promise<Set<string>>}
53
+ */
54
+ private fetchJsonColumnNames;
44
55
  /**
45
56
  * Fetch index metadata for the provided table and column
46
57
  * @param {Sequelize} connection
@@ -4,6 +4,7 @@ import { Dialect } from './Dialect.js';
4
4
  import { warnUnknownMappingForDataType } from './utils.js';
5
5
  import { buildSequelizeDataType, renderDataTypeExpression, parseEnumValues, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
6
6
  import { groupForeignKeyRows, buildInformationSchemaForeignKeysQuery, mapForeignKeyQueryRow, } from './foreignKeys.js';
7
+ import { extractJsonColumnsFromCheckConstraints, extractJsonColumnsFromCreateTable, getCreateTableStatement, } from './mariadbJson.js';
7
8
  const sequelizeDataTypesMap = {
8
9
  bigint: DataTypes.BIGINT,
9
10
  int: DataTypes.INTEGER,
@@ -228,8 +229,52 @@ export class DialectMariaDB extends Dialect {
228
229
  };
229
230
  columnsMetadata.push(columnMetadata);
230
231
  }
232
+ // MariaDB reports a JSON column as longtext with a json_valid CHECK constraint.
233
+ // Reclassify those columns as JSON so they emit DataTypes.JSON and the Json type.
234
+ const jsonColumnNames = await this.fetchJsonColumnNames(connection, config, table);
235
+ for (const columnMetadata of columnsMetadata) {
236
+ if (columnMetadata.type !== 'longtext' || !jsonColumnNames.has(columnMetadata.originName)) {
237
+ continue;
238
+ }
239
+ const jsonSequelizeType = buildSequelizeDataType(DataTypes.JSON, []);
240
+ if (jsonSequelizeType) {
241
+ columnMetadata.sequelizeType = jsonSequelizeType;
242
+ columnMetadata.dataType = renderDataTypeExpression(jsonSequelizeType, DATA_TYPE_NAMESPACES.decorators);
243
+ columnMetadata.isJson = true;
244
+ }
245
+ }
231
246
  return columnsMetadata;
232
247
  }
248
+ /**
249
+ * Fetch the database column names of a table backed by longtext with a
250
+ * `json_valid(...)` CHECK constraint. Detection reads information_schema.
251
+ * CHECK_CONSTRAINTS and falls back to parsing `SHOW CREATE TABLE` when that
252
+ * view is unavailable (MariaDB before 10.5).
253
+ * @param {Sequelize} connection
254
+ * @param {IConfig} config
255
+ * @param {string} table
256
+ * @returns {Promise<Set<string>>}
257
+ */
258
+ async fetchJsonColumnNames(connection, config, table) {
259
+ try {
260
+ const rows = await connection.query(`
261
+ SELECT CHECK_CLAUSE
262
+ FROM information_schema.CHECK_CONSTRAINTS
263
+ WHERE CONSTRAINT_SCHEMA = '${config.connection.database}' AND TABLE_NAME = '${table}';
264
+ `, {
265
+ type: QueryTypes.SELECT,
266
+ raw: true,
267
+ });
268
+ return extractJsonColumnsFromCheckConstraints(rows);
269
+ }
270
+ catch {
271
+ const rows = await connection.query(`SHOW CREATE TABLE \`${table}\`;`, {
272
+ type: QueryTypes.SELECT,
273
+ raw: true,
274
+ });
275
+ return extractJsonColumnsFromCreateTable(getCreateTableStatement(rows[0]));
276
+ }
277
+ }
233
278
  /**
234
279
  * Fetch index metadata for the provided table and column
235
280
  * @param {Sequelize} connection
@@ -43,7 +43,7 @@ const sequelizeDataTypesMap = {
43
43
  json: DataTypes.JSON,
44
44
  };
45
45
  const jsDataTypesMap = {
46
- bigint: 'number',
46
+ bigint: 'string',
47
47
  smallint: 'number',
48
48
  mediumint: 'number',
49
49
  tinyint: 'number',
@@ -236,6 +236,7 @@ export class DialectMySQL extends Dialect {
236
236
  sequelizeType,
237
237
  dataType: renderDataTypeExpression(sequelizeType, DATA_TYPE_NAMESPACES.decorators),
238
238
  },
239
+ ...column.DATA_TYPE === 'json' && { isJson: true },
239
240
  allowNull: column.IS_NULLABLE === 'YES',
240
241
  primaryKey: column.COLUMN_KEY === 'PRI',
241
242
  autoIncrement: column.EXTRA === 'auto_increment',
@@ -15,7 +15,9 @@ export declare class DialectPostgres extends Dialect {
15
15
  */
16
16
  mapDbTypeToSequelize(dbType: string): AbstractDataTypeConstructor;
17
17
  /**
18
- * Map database data type to javascript data type
18
+ * Map database data type to javascript data type. An array type maps to the
19
+ * element JS type suffixed with `[]`; an array whose element has no scalar
20
+ * mapping degrades to `unknown[]`.
19
21
  * @param {string} dbType
20
22
  * @returns {string}
21
23
  */
@@ -43,6 +43,21 @@ const sequelizeDataTypesMap = {
43
43
  jsonb: DataTypes.JSONB,
44
44
  jsonpath: DataTypes.JSON,
45
45
  };
46
+ // Postgres reports array columns with an underscore-prefixed udt_name (e.g. _int4,
47
+ // _text). The element type is the same name without the leading underscore.
48
+ const POSTGRES_ARRAY_PREFIX = '_';
49
+ /**
50
+ * Report whether a Postgres udt_name denotes an array type.
51
+ * @param {string} udtName
52
+ * @returns {boolean}
53
+ */
54
+ const isPostgresArrayType = (udtName) => udtName.startsWith(POSTGRES_ARRAY_PREFIX);
55
+ /**
56
+ * Strip the leading underscore of an array udt_name to get its element type name.
57
+ * @param {string} udtName
58
+ * @returns {string}
59
+ */
60
+ const stripPostgresArrayPrefix = (udtName) => udtName.slice(POSTGRES_ARRAY_PREFIX.length);
46
61
  const jsDataTypesMap = {
47
62
  int2: 'number',
48
63
  int4: 'number',
@@ -99,11 +114,17 @@ export class DialectPostgres extends Dialect {
99
114
  return sequelizeDataTypesMap[dbType];
100
115
  }
101
116
  /**
102
- * Map database data type to javascript data type
117
+ * Map database data type to javascript data type. An array type maps to the
118
+ * element JS type suffixed with `[]`; an array whose element has no scalar
119
+ * mapping degrades to `unknown[]`.
103
120
  * @param {string} dbType
104
121
  * @returns {string}
105
122
  */
106
123
  mapDbTypeToJs(dbType) {
124
+ if (isPostgresArrayType(dbType)) {
125
+ const elementJsType = jsDataTypesMap[stripPostgresArrayPrefix(dbType)];
126
+ return `${elementJsType ?? 'unknown'}[]`;
127
+ }
107
128
  return jsDataTypesMap[dbType];
108
129
  }
109
130
  /**
@@ -198,14 +219,20 @@ export class DialectPostgres extends Dialect {
198
219
  raw: true,
199
220
  });
200
221
  for (const column of columns) {
201
- // Unknown data type
202
- if (!this.mapDbTypeToSequelize(column.udt_name)) {
222
+ // For an array column the element type drives the mapping; the ARRAY
223
+ // wrapper is added afterwards.
224
+ const isArray = isPostgresArrayType(column.udt_name);
225
+ const elementTypeName = isArray ? stripPostgresArrayPrefix(column.udt_name) : column.udt_name;
226
+ const elementConstructor = this.mapDbTypeToSequelize(elementTypeName);
227
+ // Unknown data type. An array whose element has no scalar mapping is
228
+ // reported once and degrades gracefully: no `type` is emitted and the
229
+ // TypeScript type falls back to `unknown[]`.
230
+ if (!elementConstructor) {
203
231
  warnUnknownMappingForDataType(column.udt_name);
204
232
  }
205
- const sequelizeConstructor = this.mapDbTypeToSequelize(column.udt_name);
206
233
  // Data type arguments (precision or length)
207
234
  let dataTypeArgs = [];
208
- switch (column.udt_name) {
235
+ switch (elementTypeName) {
209
236
  case 'decimal':
210
237
  case 'numeric':
211
238
  case 'float':
@@ -221,9 +248,12 @@ export class DialectPostgres extends Dialect {
221
248
  dataTypeArgs = [column.character_maximum_length];
222
249
  break;
223
250
  }
224
- const sequelizeType = sequelizeConstructor
225
- ? buildSequelizeDataType(sequelizeConstructor, dataTypeArgs)
251
+ const elementType = elementConstructor
252
+ ? buildSequelizeDataType(elementConstructor, dataTypeArgs)
226
253
  : undefined;
254
+ const sequelizeType = elementType && isArray
255
+ ? buildSequelizeDataType(DataTypes.ARRAY, [elementType])
256
+ : elementType;
227
257
  const columnMetadata = {
228
258
  name: column.column_name,
229
259
  originName: column.column_name,
@@ -233,6 +263,7 @@ export class DialectPostgres extends Dialect {
233
263
  sequelizeType,
234
264
  dataType: renderDataTypeExpression(sequelizeType, DATA_TYPE_NAMESPACES.decorators),
235
265
  },
266
+ ...!isArray && (elementTypeName === 'json' || elementTypeName === 'jsonb') && { isJson: true },
236
267
  allowNull: column.is_nullable === 'YES' && !column.is_primary,
237
268
  primaryKey: column.is_primary,
238
269
  autoIncrement: column.is_sequence,