sequelize-typescript-generator 13.0.1 → 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.
- package/build/builders/ModelBuilder.js +26 -5
- package/build/builders/NativeModelRenderer.js +10 -2
- package/build/builders/generatedFile.js +5 -0
- package/build/builders/jsonSupport.d.ts +62 -0
- package/build/builders/jsonSupport.js +82 -0
- package/build/builders/utils.d.ts +20 -2
- package/build/builders/utils.js +39 -5
- package/build/dialects/Dialect.d.ts +1 -0
- package/build/dialects/DialectMariaDB.d.ts +11 -0
- package/build/dialects/DialectMariaDB.js +45 -0
- package/build/dialects/DialectMySQL.js +1 -0
- package/build/dialects/DialectPostgres.d.ts +3 -1
- package/build/dialects/DialectPostgres.js +38 -7
- package/build/dialects/dataTypes.d.ts +18 -4
- package/build/dialects/dataTypes.js +21 -4
- package/build/dialects/mariadbJson.d.ts +39 -0
- package/build/dialects/mariadbJson.js +52 -0
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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),
|
|
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,
|
|
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
|
*/
|
package/build/builders/utils.js
CHANGED
|
@@ -15,6 +15,28 @@ export const nodeToString = (node) => {
|
|
|
15
15
|
// Reference: https://github.com/microsoft/TypeScript/issues/36174
|
|
16
16
|
return unescape(sourceCode.replace(/\\u/g, "%u"));
|
|
17
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* Neutralise the block-comment terminator inside text so it cannot prematurely
|
|
20
|
+
* close a JSDoc block, by inserting a space between `*` and `/`.
|
|
21
|
+
* @param {string} comment
|
|
22
|
+
* @returns {string}
|
|
23
|
+
*/
|
|
24
|
+
export const sanitiseJsDocComment = (comment) => comment.replace(/\*\//g, '* /');
|
|
25
|
+
/**
|
|
26
|
+
* Attach a database column comment as a `/** … *\/` JSDoc leading comment on a
|
|
27
|
+
* declaration. Empty or whitespace-only comments are ignored; an embedded
|
|
28
|
+
* comment terminator is neutralised first. Returns the node unchanged when there
|
|
29
|
+
* is nothing to attach.
|
|
30
|
+
* @param {T} node
|
|
31
|
+
* @param {string | undefined} comment
|
|
32
|
+
* @returns {T}
|
|
33
|
+
*/
|
|
34
|
+
export const attachColumnCommentJsDoc = (node, comment) => {
|
|
35
|
+
if (!comment || comment.trim().length === 0) {
|
|
36
|
+
return node;
|
|
37
|
+
}
|
|
38
|
+
return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `* ${sanitiseJsDocComment(comment.trim())} `, true);
|
|
39
|
+
};
|
|
18
40
|
/**
|
|
19
41
|
* Generate named imports code (e.g. `import { Something, Else } from "module"`)
|
|
20
42
|
* @param {string[]} importsSpecifier
|
|
@@ -98,12 +120,16 @@ export const createPropertyValueExpression = (value, isMultiLine) => {
|
|
|
98
120
|
*/
|
|
99
121
|
export const buildObjectLiteralExpression = (props, isMultiLine) => ts.factory.createObjectLiteralExpression(Object.entries(props).map(([key, value]) => ts.factory.createPropertyAssignment(createPropertyName(key), createPropertyValueExpression(value, isMultiLine))), isMultiLine);
|
|
100
122
|
/**
|
|
101
|
-
* Build a type node from a JS type name: number/string/boolean/object keywords,
|
|
102
|
-
* Date and Uint8Array references, and the unknown keyword for anything else.
|
|
123
|
+
* Build a type node from a JS type name: number/string/boolean/object/any keywords,
|
|
124
|
+
* Date and Uint8Array references, and the unknown keyword for anything else. A name
|
|
125
|
+
* with a trailing `[]` (e.g. `number[]`) yields an array type node of the element.
|
|
103
126
|
* @param {string} jsType
|
|
104
127
|
* @returns {ts.TypeNode}
|
|
105
128
|
*/
|
|
106
129
|
export const createTypeNodeFromName = (jsType) => {
|
|
130
|
+
if (jsType.endsWith('[]')) {
|
|
131
|
+
return ts.factory.createArrayTypeNode(createTypeNodeFromName(jsType.slice(0, -2)));
|
|
132
|
+
}
|
|
107
133
|
switch (jsType) {
|
|
108
134
|
case 'number':
|
|
109
135
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
|
|
@@ -113,6 +139,8 @@ export const createTypeNodeFromName = (jsType) => {
|
|
|
113
139
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
|
|
114
140
|
case 'object':
|
|
115
141
|
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword);
|
|
142
|
+
case 'any':
|
|
143
|
+
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);
|
|
116
144
|
case 'Date':
|
|
117
145
|
return ts.factory.createTypeReferenceNode('Date', undefined);
|
|
118
146
|
case 'Uint8Array':
|
|
@@ -157,9 +185,15 @@ export const buildDataTypeExpression = (dataType, namespace) => {
|
|
|
157
185
|
if (dataType.args.length === 0) {
|
|
158
186
|
return memberAccess;
|
|
159
187
|
}
|
|
160
|
-
return ts.factory.createCallExpression(memberAccess, undefined, dataType.args.map(arg =>
|
|
161
|
-
|
|
162
|
-
|
|
188
|
+
return ts.factory.createCallExpression(memberAccess, undefined, dataType.args.map(arg => {
|
|
189
|
+
if (typeof arg === 'number') {
|
|
190
|
+
return createNumericLiteralExpression(arg);
|
|
191
|
+
}
|
|
192
|
+
if (typeof arg === 'string') {
|
|
193
|
+
return ts.factory.createStringLiteral(arg);
|
|
194
|
+
}
|
|
195
|
+
return buildDataTypeExpression(arg, namespace);
|
|
196
|
+
}));
|
|
163
197
|
};
|
|
164
198
|
/**
|
|
165
199
|
* Generate model export for index file
|
|
@@ -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
|
|
@@ -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
|
-
//
|
|
202
|
-
|
|
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 (
|
|
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
|
|
225
|
-
? buildSequelizeDataType(
|
|
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,
|
|
@@ -1,15 +1,28 @@
|
|
|
1
1
|
import { DataTypes } from 'sequelize';
|
|
2
2
|
import type { AbstractDataTypeConstructor } from 'sequelize';
|
|
3
3
|
export type SequelizeDataTypeKey = keyof typeof DataTypes;
|
|
4
|
-
export type DataTypeArgument = string | number;
|
|
5
4
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* A single argument of a Sequelize data type. A scalar argument is a number
|
|
6
|
+
* (precision, length) or a string (ENUM value); a nested argument is itself a
|
|
7
|
+
* data type, so an argument list can carry another data type such as the element
|
|
8
|
+
* type of `ARRAY(INTEGER)`.
|
|
9
|
+
*/
|
|
10
|
+
export type DataTypeArgument = string | number | ISequelizeDataType;
|
|
11
|
+
/**
|
|
12
|
+
* Format-neutral Sequelize data type: a DataTypes key plus its arguments. Scalar
|
|
13
|
+
* arguments render bare (numbers) or single-quoted (strings, for ENUM values); a
|
|
14
|
+
* nested data type argument renders as its own data type expression.
|
|
8
15
|
*/
|
|
9
16
|
export interface ISequelizeDataType {
|
|
10
17
|
key: SequelizeDataTypeKey;
|
|
11
18
|
args: DataTypeArgument[];
|
|
12
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Type guard for a nested data type argument.
|
|
22
|
+
* @param {DataTypeArgument} arg
|
|
23
|
+
* @returns {boolean}
|
|
24
|
+
*/
|
|
25
|
+
export declare const isNestedDataType: (arg: DataTypeArgument) => arg is ISequelizeDataType;
|
|
13
26
|
/**
|
|
14
27
|
* Namespaces under which a data type expression is rendered.
|
|
15
28
|
*/
|
|
@@ -43,7 +56,8 @@ export declare const resolveSequelizeDataTypeKey: (ctor: AbstractDataTypeConstru
|
|
|
43
56
|
*/
|
|
44
57
|
export declare const buildSequelizeDataType: (ctor: AbstractDataTypeConstructor, args: Array<DataTypeArgument | null | undefined>) => ISequelizeDataType | undefined;
|
|
45
58
|
/**
|
|
46
|
-
* Render a data type expression, e.g. DataType.DECIMAL(7,3)
|
|
59
|
+
* Render a data type expression, e.g. DataType.DECIMAL(7,3), DataTypes.ENUM('AA','BB')
|
|
60
|
+
* or DataTypes.ARRAY(DataTypes.INTEGER).
|
|
47
61
|
* @param {ISequelizeDataType} dataType
|
|
48
62
|
* @param {DataTypeNamespace} namespace
|
|
49
63
|
* @returns {string}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { DataTypes } from 'sequelize';
|
|
2
|
+
/**
|
|
3
|
+
* Type guard for a nested data type argument.
|
|
4
|
+
* @param {DataTypeArgument} arg
|
|
5
|
+
* @returns {boolean}
|
|
6
|
+
*/
|
|
7
|
+
export const isNestedDataType = (arg) => typeof arg === 'object' && arg !== null && 'key' in arg && 'args' in arg;
|
|
2
8
|
/**
|
|
3
9
|
* Namespaces under which a data type expression is rendered.
|
|
4
10
|
*/
|
|
@@ -47,20 +53,31 @@ export const buildSequelizeDataType = (ctor, args) => {
|
|
|
47
53
|
};
|
|
48
54
|
/**
|
|
49
55
|
* Render a single data type argument. Numbers render bare; strings render
|
|
50
|
-
* single-quoted with internal single quotes doubled
|
|
56
|
+
* single-quoted with internal single quotes doubled; a nested data type renders
|
|
57
|
+
* as its own expression under the same namespace.
|
|
51
58
|
* @param {DataTypeArgument} arg
|
|
59
|
+
* @param {DataTypeNamespace} namespace
|
|
52
60
|
* @returns {string}
|
|
53
61
|
*/
|
|
54
|
-
const renderDataTypeArgument = (arg) =>
|
|
62
|
+
const renderDataTypeArgument = (arg, namespace) => {
|
|
63
|
+
if (typeof arg === 'number') {
|
|
64
|
+
return String(arg);
|
|
65
|
+
}
|
|
66
|
+
if (typeof arg === 'string') {
|
|
67
|
+
return `'${arg.replace(/'/g, "''")}'`;
|
|
68
|
+
}
|
|
69
|
+
return renderDataTypeExpression(arg, namespace);
|
|
70
|
+
};
|
|
55
71
|
/**
|
|
56
|
-
* Render a data type expression, e.g. DataType.DECIMAL(7,3)
|
|
72
|
+
* Render a data type expression, e.g. DataType.DECIMAL(7,3), DataTypes.ENUM('AA','BB')
|
|
73
|
+
* or DataTypes.ARRAY(DataTypes.INTEGER).
|
|
57
74
|
* @param {ISequelizeDataType} dataType
|
|
58
75
|
* @param {DataTypeNamespace} namespace
|
|
59
76
|
* @returns {string}
|
|
60
77
|
*/
|
|
61
78
|
export const renderDataTypeExpression = (dataType, namespace) => {
|
|
62
79
|
const signature = dataType.args.length
|
|
63
|
-
? `(${dataType.args.map(renderDataTypeArgument).join(',')})`
|
|
80
|
+
? `(${dataType.args.map(arg => renderDataTypeArgument(arg, namespace)).join(',')})`
|
|
64
81
|
: '';
|
|
65
82
|
return `${namespace}.${dataType.key}${signature}`;
|
|
66
83
|
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MariaDB stores a `JSON` column as `longtext` with a `CHECK (json_valid(<col>))`
|
|
3
|
+
* constraint. These helpers recover the JSON columns of a table from the check
|
|
4
|
+
* clauses (information_schema.CHECK_CONSTRAINTS) or, as a fallback for MariaDB
|
|
5
|
+
* versions without that view, from the `SHOW CREATE TABLE` statement.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* A row of information_schema.CHECK_CONSTRAINTS relevant to JSON detection.
|
|
9
|
+
*/
|
|
10
|
+
export interface ICheckConstraintRow {
|
|
11
|
+
CHECK_CLAUSE: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A row of `SHOW CREATE TABLE`, whose second column holds the create statement.
|
|
15
|
+
*/
|
|
16
|
+
export interface IShowCreateTableRow {
|
|
17
|
+
'Create Table'?: string;
|
|
18
|
+
'CREATE TABLE'?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Extract the column names guarded by a `json_valid(...)` check from a set of
|
|
22
|
+
* check clauses.
|
|
23
|
+
* @param {ICheckConstraintRow[]} rows
|
|
24
|
+
* @returns {Set<string>}
|
|
25
|
+
*/
|
|
26
|
+
export declare const extractJsonColumnsFromCheckConstraints: (rows: ICheckConstraintRow[]) => Set<string>;
|
|
27
|
+
/**
|
|
28
|
+
* Extract the column names guarded by a `json_valid(...)` check from a
|
|
29
|
+
* `SHOW CREATE TABLE` statement.
|
|
30
|
+
* @param {string} createTableStatement
|
|
31
|
+
* @returns {Set<string>}
|
|
32
|
+
*/
|
|
33
|
+
export declare const extractJsonColumnsFromCreateTable: (createTableStatement: string) => Set<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Read the create statement out of a `SHOW CREATE TABLE` result row.
|
|
36
|
+
* @param {IShowCreateTableRow | undefined} row
|
|
37
|
+
* @returns {string}
|
|
38
|
+
*/
|
|
39
|
+
export declare const getCreateTableStatement: (row: IShowCreateTableRow | undefined) => string;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MariaDB stores a `JSON` column as `longtext` with a `CHECK (json_valid(<col>))`
|
|
3
|
+
* constraint. These helpers recover the JSON columns of a table from the check
|
|
4
|
+
* clauses (information_schema.CHECK_CONSTRAINTS) or, as a fallback for MariaDB
|
|
5
|
+
* versions without that view, from the `SHOW CREATE TABLE` statement.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Match a `json_valid(<column>)` call, capturing the column name with its
|
|
9
|
+
* optional surrounding backticks stripped. Case-insensitive and global so every
|
|
10
|
+
* occurrence in a statement can be scanned.
|
|
11
|
+
*/
|
|
12
|
+
const JSON_VALID_PATTERN = /json_valid\(\s*`?([^`()\s]+)`?\s*\)/gi;
|
|
13
|
+
/**
|
|
14
|
+
* Extract the column names guarded by a `json_valid(...)` check from a set of
|
|
15
|
+
* check clauses.
|
|
16
|
+
* @param {ICheckConstraintRow[]} rows
|
|
17
|
+
* @returns {Set<string>}
|
|
18
|
+
*/
|
|
19
|
+
export const extractJsonColumnsFromCheckConstraints = (rows) => {
|
|
20
|
+
const columns = new Set();
|
|
21
|
+
for (const row of rows) {
|
|
22
|
+
for (const columnName of matchJsonValidColumns(row.CHECK_CLAUSE ?? '')) {
|
|
23
|
+
columns.add(columnName);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return columns;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Extract the column names guarded by a `json_valid(...)` check from a
|
|
30
|
+
* `SHOW CREATE TABLE` statement.
|
|
31
|
+
* @param {string} createTableStatement
|
|
32
|
+
* @returns {Set<string>}
|
|
33
|
+
*/
|
|
34
|
+
export const extractJsonColumnsFromCreateTable = (createTableStatement) => new Set(matchJsonValidColumns(createTableStatement));
|
|
35
|
+
/**
|
|
36
|
+
* Read the create statement out of a `SHOW CREATE TABLE` result row.
|
|
37
|
+
* @param {IShowCreateTableRow | undefined} row
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export const getCreateTableStatement = (row) => row?.['Create Table'] ?? row?.['CREATE TABLE'] ?? '';
|
|
41
|
+
/**
|
|
42
|
+
* Collect every column name captured by a `json_valid(...)` call in a string.
|
|
43
|
+
* @param {string} value
|
|
44
|
+
* @returns {string[]}
|
|
45
|
+
*/
|
|
46
|
+
const matchJsonValidColumns = (value) => {
|
|
47
|
+
const columns = [];
|
|
48
|
+
for (const match of value.matchAll(JSON_VALID_PATTERN)) {
|
|
49
|
+
columns.push(match[1]);
|
|
50
|
+
}
|
|
51
|
+
return columns;
|
|
52
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sequelize-typescript-generator",
|
|
3
|
-
"version": "13.0
|
|
3
|
+
"version": "13.1.0",
|
|
4
4
|
"description": "Automatically generate type-safe Sequelize models from your source database via the TypeScript compiler API — native or sequelize-typescript (decorators) format.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "build/index.js",
|