sequelize-typescript-generator 12.0.1 → 13.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +832 -204
- package/build/bin/cli.js +65 -47
- package/build/bin/utils.d.ts +5 -2
- package/build/bin/utils.js +87 -104
- package/build/builders/Builder.d.ts +2 -2
- package/build/builders/Builder.js +3 -5
- package/build/builders/ModelBuilder.d.ts +43 -8
- package/build/builders/ModelBuilder.js +120 -122
- package/build/builders/NativeModelRenderer.d.ts +98 -0
- package/build/builders/NativeModelRenderer.js +353 -0
- package/build/builders/associationNaming.d.ts +9 -0
- package/build/builders/associationNaming.js +15 -0
- package/build/builders/decoratorsDependency.d.ts +27 -0
- package/build/builders/decoratorsDependency.js +45 -0
- package/build/builders/defaultValues.d.ts +40 -0
- package/build/builders/defaultValues.js +56 -0
- package/build/builders/generatedFile.d.ts +23 -0
- package/build/builders/generatedFile.js +31 -0
- package/build/builders/index.d.ts +1 -1
- package/build/builders/index.js +1 -5
- package/build/builders/nativeAssociations.d.ts +109 -0
- package/build/builders/nativeAssociations.js +308 -0
- package/build/builders/nativeAttributes.d.ts +96 -0
- package/build/builders/nativeAttributes.js +174 -0
- package/build/builders/nativeWiring.d.ts +51 -0
- package/build/builders/nativeWiring.js +108 -0
- package/build/builders/utils.d.ts +75 -0
- package/build/builders/utils.js +142 -48
- package/build/config/IConfig.d.ts +11 -2
- package/build/config/IConfig.js +4 -6
- package/build/config/format.d.ts +27 -0
- package/build/config/format.js +26 -0
- package/build/config/index.d.ts +1 -1
- package/build/config/index.js +1 -2
- package/build/connection/createConnection.d.ts +8 -1
- package/build/connection/createConnection.js +30 -7
- package/build/connection/index.d.ts +1 -1
- package/build/connection/index.js +1 -17
- package/build/dialects/AssociationsParser.d.ts +10 -2
- package/build/dialects/AssociationsParser.js +16 -19
- package/build/dialects/Dialect.d.ts +52 -9
- package/build/dialects/Dialect.js +93 -57
- package/build/dialects/DialectMSSQL.d.ts +22 -3
- package/build/dialects/DialectMSSQL.js +169 -75
- package/build/dialects/DialectMariaDB.d.ts +13 -3
- package/build/dialects/DialectMariaDB.js +98 -79
- package/build/dialects/DialectMySQL.d.ts +13 -3
- package/build/dialects/DialectMySQL.js +102 -84
- package/build/dialects/DialectPostgres.d.ts +14 -3
- package/build/dialects/DialectPostgres.js +129 -75
- package/build/dialects/DialectSQLite.d.ts +41 -3
- package/build/dialects/DialectSQLite.js +166 -24
- package/build/dialects/associationDiscovery.d.ts +64 -0
- package/build/dialects/associationDiscovery.js +275 -0
- package/build/dialects/associationsFileMerge.d.ts +21 -0
- package/build/dialects/associationsFileMerge.js +107 -0
- package/build/dialects/createDialect.d.ts +8 -0
- package/build/dialects/createDialect.js +24 -0
- package/build/dialects/dataTypes.d.ts +58 -0
- package/build/dialects/dataTypes.js +108 -0
- package/build/dialects/foreignKeys.d.ts +115 -0
- package/build/dialects/foreignKeys.js +198 -0
- package/build/dialects/index.d.ts +5 -5
- package/build/dialects/index.js +5 -13
- package/build/dialects/paranoid.d.ts +24 -0
- package/build/dialects/paranoid.js +29 -0
- package/build/dialects/utils.d.ts +2 -8
- package/build/dialects/utils.js +61 -58
- package/build/index.d.ts +11 -3
- package/build/index.js +5 -19
- package/build/lint/Linter.d.ts +14 -3
- package/build/lint/Linter.js +114 -14
- package/build/lint/eslintDefaultConfig.d.ts +2 -2
- package/build/lint/eslintDefaultConfig.js +28 -23
- package/build/lint/index.d.ts +1 -1
- package/build/lint/index.js +1 -5
- package/build/utils/errors.d.ts +6 -0
- package/build/utils/errors.js +6 -0
- package/package.json +48 -28
- package/.github/FUNDING.yml +0 -1
- package/.github/workflows/ci.yml +0 -199
- package/CHANGELOG.md +0 -30
- package/tsconfig.json +0 -21
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import * as ts from 'typescript';
|
|
2
|
+
import { DATA_TYPE_NAMESPACES } from '../dialects/dataTypes.js';
|
|
3
|
+
import { buildDataTypeExpression, buildObjectLiteralExpression, createGenericTypeReference, createIndexedAccessTypeNode, createTypeNodeFromName, generateNamedImports, generateTypeOnlyImport, nodeToString, } from './utils.js';
|
|
4
|
+
import { buildDefaultValueExpression, parseDefaultValue } from './defaultValues.js';
|
|
5
|
+
import { classifyAttribute, collectTableIndexes, COLUMN_OPTION_KEYS, isParanoidColumn, resolveForeignKeyTargetAttribute, resolvePrimaryKeyAttribute, TIMESTAMP_ATTRIBUTES, } from './nativeAttributes.js';
|
|
6
|
+
import { buildAssociationMixinDeclarations, collectModelTypeImports, collectSequelizeImports, isToManyAssociation, resolveAssociationForeignKey, } from './nativeAssociations.js';
|
|
7
|
+
import { resolveAssociationPropertyName } from './associationNaming.js';
|
|
8
|
+
const NATIVE_NAMESPACE = DATA_TYPE_NAMESPACES.native;
|
|
9
|
+
/**
|
|
10
|
+
* Union a type node with the null literal type, flattening an existing union so
|
|
11
|
+
* that a string-literal union renders as `"AA" | "BB" | null` rather than nesting.
|
|
12
|
+
* @param {ts.TypeNode} type
|
|
13
|
+
* @returns {ts.TypeNode}
|
|
14
|
+
*/
|
|
15
|
+
const buildNullableTypeNode = (type) => {
|
|
16
|
+
const nullType = ts.factory.createLiteralTypeNode(ts.factory.createNull());
|
|
17
|
+
const members = ts.isUnionTypeNode(type) ? [...type.types, nullType] : [type, nullType];
|
|
18
|
+
return ts.factory.createUnionTypeNode(members);
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Build a `declare` field declaration, optionally static and optionally optional.
|
|
22
|
+
* @param {string} name
|
|
23
|
+
* @param {ts.TypeNode} type
|
|
24
|
+
* @param {{ isStatic?: boolean; isOptional?: boolean }} options
|
|
25
|
+
* @returns {ts.PropertyDeclaration}
|
|
26
|
+
*/
|
|
27
|
+
const buildDeclareField = (name, type, options = {}) => {
|
|
28
|
+
const modifiers = [ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)];
|
|
29
|
+
if (options.isStatic) {
|
|
30
|
+
modifiers.push(ts.factory.createToken(ts.SyntaxKind.StaticKeyword));
|
|
31
|
+
}
|
|
32
|
+
return ts.factory.createPropertyDeclaration(modifiers, name, options.isOptional ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, type, undefined);
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* 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.
|
|
38
|
+
* @param {IColumnMetadata} column
|
|
39
|
+
* @param {ITableMetadata} table
|
|
40
|
+
* @param {Dialect} dialect
|
|
41
|
+
* @returns {ts.TypeNode}
|
|
42
|
+
*/
|
|
43
|
+
const buildBaseTypeNode = (column, table, dialect) => {
|
|
44
|
+
if (isParanoidColumn(column, table)) {
|
|
45
|
+
return createTypeNodeFromName('Date');
|
|
46
|
+
}
|
|
47
|
+
const { sequelizeType } = column;
|
|
48
|
+
if (sequelizeType && sequelizeType.key === 'ENUM' && sequelizeType.args.length > 0) {
|
|
49
|
+
return ts.factory.createUnionTypeNode(sequelizeType.args.map(arg => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(String(arg)))));
|
|
50
|
+
}
|
|
51
|
+
return createTypeNodeFromName(dialect.mapDbTypeToJs(column.type));
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* 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.
|
|
57
|
+
* @param {IColumnMetadata} column
|
|
58
|
+
* @param {ITableMetadata} table
|
|
59
|
+
* @param {Dialect} dialect
|
|
60
|
+
* @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
|
|
61
|
+
* @returns {ts.TypeNode}
|
|
62
|
+
*/
|
|
63
|
+
export const buildAttributeTypeNode = (column, table, dialect, tablesByModel) => {
|
|
64
|
+
const targetModel = column.foreignKey?.targetModel;
|
|
65
|
+
const isForeignKeyTargetGenerated = targetModel !== undefined && tablesByModel.has(targetModel);
|
|
66
|
+
const kind = classifyAttribute(column, table, isForeignKeyTargetGenerated);
|
|
67
|
+
if (column.foreignKey && (kind === 'foreignKey' || kind === 'foreignKeyNullable')) {
|
|
68
|
+
const target = tablesByModel.get(column.foreignKey.targetModel);
|
|
69
|
+
const targetAttribute = target
|
|
70
|
+
? resolveForeignKeyTargetAttribute(column.foreignKey, target)
|
|
71
|
+
: undefined;
|
|
72
|
+
const referenced = targetAttribute
|
|
73
|
+
? createIndexedAccessTypeNode(column.foreignKey.targetModel, targetAttribute)
|
|
74
|
+
: ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
|
|
75
|
+
const inner = kind === 'foreignKeyNullable' ? buildNullableTypeNode(referenced) : referenced;
|
|
76
|
+
return createGenericTypeReference('ForeignKey', [inner]);
|
|
77
|
+
}
|
|
78
|
+
const base = buildBaseTypeNode(column, table, dialect);
|
|
79
|
+
switch (kind) {
|
|
80
|
+
case 'nullable':
|
|
81
|
+
return buildNullableTypeNode(base);
|
|
82
|
+
case 'creationOptional':
|
|
83
|
+
return createGenericTypeReference('CreationOptional', [base]);
|
|
84
|
+
case 'creationOptionalNullable':
|
|
85
|
+
return createGenericTypeReference('CreationOptional', [buildNullableTypeNode(base)]);
|
|
86
|
+
default:
|
|
87
|
+
return base;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Build the `declare` attribute member of a column.
|
|
92
|
+
* @param {IColumnMetadata} column
|
|
93
|
+
* @param {ITableMetadata} table
|
|
94
|
+
* @param {Dialect} dialect
|
|
95
|
+
* @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
|
|
96
|
+
* @returns {ts.PropertyDeclaration}
|
|
97
|
+
*/
|
|
98
|
+
export const buildAttributeDeclaration = (column, table, dialect, tablesByModel) => buildDeclareField(column.name, buildAttributeTypeNode(column, table, dialect, tablesByModel));
|
|
99
|
+
/**
|
|
100
|
+
* Build the `declare createdAt`/`declare updatedAt` members of a model, emitted
|
|
101
|
+
* only when timestamps are enabled.
|
|
102
|
+
* @param {ITableMetadata} table
|
|
103
|
+
* @returns {ts.PropertyDeclaration[]}
|
|
104
|
+
*/
|
|
105
|
+
export const buildTimestampDeclarations = (table) => {
|
|
106
|
+
if (!table.timestamps) {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
return TIMESTAMP_ATTRIBUTES.map(attribute => buildDeclareField(attribute, createGenericTypeReference('CreationOptional', [createTypeNodeFromName('Date')])));
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Turn a mixin type argument descriptor into a type node.
|
|
113
|
+
* @param {MixinTypeArgument} argument
|
|
114
|
+
* @returns {ts.TypeNode}
|
|
115
|
+
*/
|
|
116
|
+
const buildMixinTypeArgument = (argument) => {
|
|
117
|
+
switch (argument.kind) {
|
|
118
|
+
case 'model':
|
|
119
|
+
return createGenericTypeReference(argument.name, []);
|
|
120
|
+
case 'attribute':
|
|
121
|
+
return createIndexedAccessTypeNode(argument.model, argument.attribute);
|
|
122
|
+
case 'literal':
|
|
123
|
+
return ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(argument.value));
|
|
124
|
+
case 'number':
|
|
125
|
+
return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Build the `declare` member of an association mixin.
|
|
130
|
+
* @param {IMixinDeclaration} mixin
|
|
131
|
+
* @returns {ts.PropertyDeclaration}
|
|
132
|
+
*/
|
|
133
|
+
export const buildMixinDeclaration = (mixin) => buildDeclareField(mixin.propertyName, createGenericTypeReference(mixin.mixinTypeName, mixin.typeArguments.map(buildMixinTypeArgument)));
|
|
134
|
+
/**
|
|
135
|
+
* Build the optional `NonAttribute` member exposing the associated model(s).
|
|
136
|
+
* @param {IAssociationMetadata} association
|
|
137
|
+
* @returns {ts.PropertyDeclaration}
|
|
138
|
+
*/
|
|
139
|
+
export const buildIncludedAssociationDeclaration = (association) => {
|
|
140
|
+
const alias = resolveAssociationPropertyName(association);
|
|
141
|
+
const targetReference = createGenericTypeReference(association.targetModel, []);
|
|
142
|
+
const included = isToManyAssociation(association)
|
|
143
|
+
? ts.factory.createArrayTypeNode(targetReference)
|
|
144
|
+
: targetReference;
|
|
145
|
+
return buildDeclareField(alias, createGenericTypeReference('NonAttribute', [included]), { isOptional: true });
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Build the `declare static associations` member, or undefined when the model has
|
|
149
|
+
* no associations.
|
|
150
|
+
* @param {ITableMetadata} table
|
|
151
|
+
* @returns {ts.PropertyDeclaration | undefined}
|
|
152
|
+
*/
|
|
153
|
+
export const buildStaticAssociationsDeclaration = (table) => {
|
|
154
|
+
const associations = table.associations ?? [];
|
|
155
|
+
if (associations.length === 0) {
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
const members = associations.map(association => ts.factory.createPropertySignature(undefined, resolveAssociationPropertyName(association), undefined, createGenericTypeReference('Association', [
|
|
159
|
+
createGenericTypeReference(table.name, []),
|
|
160
|
+
createGenericTypeReference(association.targetModel, []),
|
|
161
|
+
])));
|
|
162
|
+
return buildDeclareField('associations', ts.factory.createTypeLiteralNode(members), { isStatic: true });
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Build the ordered column option record for a column's init entry.
|
|
166
|
+
* @param {IColumnMetadata} column
|
|
167
|
+
* @param {ITableMetadata} table
|
|
168
|
+
* @param {Dialect} dialect
|
|
169
|
+
* @returns {ts.ObjectLiteralExpression}
|
|
170
|
+
*/
|
|
171
|
+
export const buildColumnInitOptions = (column, table, dialect) => {
|
|
172
|
+
const options = {};
|
|
173
|
+
for (const key of COLUMN_OPTION_KEYS) {
|
|
174
|
+
switch (key) {
|
|
175
|
+
case 'type':
|
|
176
|
+
if (column.sequelizeType) {
|
|
177
|
+
options.type = buildDataTypeExpression(column.sequelizeType, NATIVE_NAMESPACE);
|
|
178
|
+
}
|
|
179
|
+
break;
|
|
180
|
+
case 'primaryKey':
|
|
181
|
+
if (column.primaryKey) {
|
|
182
|
+
options.primaryKey = true;
|
|
183
|
+
}
|
|
184
|
+
break;
|
|
185
|
+
case 'autoIncrement':
|
|
186
|
+
if (column.autoIncrement) {
|
|
187
|
+
options.autoIncrement = true;
|
|
188
|
+
}
|
|
189
|
+
break;
|
|
190
|
+
case 'allowNull':
|
|
191
|
+
if (!column.primaryKey) {
|
|
192
|
+
options.allowNull = column.allowNull;
|
|
193
|
+
}
|
|
194
|
+
break;
|
|
195
|
+
case 'defaultValue': {
|
|
196
|
+
if (column.defaultValue === undefined) {
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
const raw = column.defaultValue;
|
|
200
|
+
const spelled = typeof raw === 'string' ? dialect.mapDefaultValueToSequelize(raw) : raw;
|
|
201
|
+
const descriptor = parseDefaultValue(spelled);
|
|
202
|
+
if (descriptor) {
|
|
203
|
+
options.defaultValue = buildDefaultValueExpression(descriptor, NATIVE_NAMESPACE);
|
|
204
|
+
}
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
case 'comment':
|
|
208
|
+
if (column.comment) {
|
|
209
|
+
options.comment = column.comment;
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
case 'field':
|
|
213
|
+
if (column.originName && column.name !== column.originName) {
|
|
214
|
+
options.field = column.originName;
|
|
215
|
+
}
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return buildObjectLiteralExpression(options, true);
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* Build the object literal for a single native index.
|
|
223
|
+
* @param {INativeIndex} index
|
|
224
|
+
* @returns {ts.ObjectLiteralExpression}
|
|
225
|
+
*/
|
|
226
|
+
export const buildIndexLiteral = (index) => buildObjectLiteralExpression({
|
|
227
|
+
name: index.name,
|
|
228
|
+
unique: index.isUnique,
|
|
229
|
+
fields: index.fields,
|
|
230
|
+
...index.using && { using: index.using },
|
|
231
|
+
}, true);
|
|
232
|
+
/**
|
|
233
|
+
* Build the model init options object literal in the fixed key order.
|
|
234
|
+
* @param {ITableMetadata} table
|
|
235
|
+
* @returns {ts.ObjectLiteralExpression}
|
|
236
|
+
*/
|
|
237
|
+
export const buildModelInitOptions = (table) => {
|
|
238
|
+
const elements = [
|
|
239
|
+
ts.factory.createShorthandPropertyAssignment('sequelize'),
|
|
240
|
+
ts.factory.createPropertyAssignment('tableName', ts.factory.createStringLiteral(table.originName)),
|
|
241
|
+
ts.factory.createPropertyAssignment('freezeTableName', ts.factory.createTrue()),
|
|
242
|
+
];
|
|
243
|
+
if (table.schema) {
|
|
244
|
+
elements.push(ts.factory.createPropertyAssignment('schema', ts.factory.createStringLiteral(table.schema)));
|
|
245
|
+
}
|
|
246
|
+
elements.push(ts.factory.createPropertyAssignment('timestamps', table.timestamps ? ts.factory.createTrue() : ts.factory.createFalse()));
|
|
247
|
+
if (table.paranoid) {
|
|
248
|
+
elements.push(ts.factory.createPropertyAssignment('paranoid', ts.factory.createTrue()));
|
|
249
|
+
if (table.deletedAt) {
|
|
250
|
+
elements.push(ts.factory.createPropertyAssignment('deletedAt', ts.factory.createStringLiteral(table.deletedAt)));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (table.hasTrigger) {
|
|
254
|
+
elements.push(ts.factory.createPropertyAssignment('hasTrigger', ts.factory.createTrue()));
|
|
255
|
+
}
|
|
256
|
+
if (table.comment) {
|
|
257
|
+
elements.push(ts.factory.createPropertyAssignment('comment', ts.factory.createStringLiteral(table.comment)));
|
|
258
|
+
}
|
|
259
|
+
const indexes = collectTableIndexes(table);
|
|
260
|
+
if (indexes.length > 0) {
|
|
261
|
+
elements.push(ts.factory.createPropertyAssignment('indexes', ts.factory.createArrayLiteralExpression(indexes.map(buildIndexLiteral), true)));
|
|
262
|
+
}
|
|
263
|
+
return ts.factory.createObjectLiteralExpression(elements, true);
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* Build the attributes object literal passed to `Model.init`: one entry per
|
|
267
|
+
* column followed by the Sequelize timestamp attributes when enabled.
|
|
268
|
+
* @param {ITableMetadata} table
|
|
269
|
+
* @param {Dialect} dialect
|
|
270
|
+
* @returns {ts.ObjectLiteralExpression}
|
|
271
|
+
*/
|
|
272
|
+
const buildInitAttributes = (table, dialect) => {
|
|
273
|
+
const elements = Object.values(table.columns).map(column => ts.factory.createPropertyAssignment(column.name, buildColumnInitOptions(column, table, dialect)));
|
|
274
|
+
if (table.timestamps) {
|
|
275
|
+
for (const attribute of TIMESTAMP_ATTRIBUTES) {
|
|
276
|
+
elements.push(ts.factory.createPropertyAssignment(attribute, ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(NATIVE_NAMESPACE), ts.factory.createIdentifier('DATE'))));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return ts.factory.createObjectLiteralExpression(elements, true);
|
|
280
|
+
};
|
|
281
|
+
/**
|
|
282
|
+
* Build the `static initModel(sequelize)` method that calls `Model.init` and
|
|
283
|
+
* returns the model class.
|
|
284
|
+
* @param {ITableMetadata} table
|
|
285
|
+
* @param {Dialect} dialect
|
|
286
|
+
* @returns {ts.MethodDeclaration}
|
|
287
|
+
*/
|
|
288
|
+
export const buildInitModelMethod = (table, dialect) => {
|
|
289
|
+
const initCall = ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(table.name), ts.factory.createIdentifier('init')), undefined, [buildInitAttributes(table, dialect), buildModelInitOptions(table)]));
|
|
290
|
+
return ts.factory.createMethodDeclaration([ts.factory.createToken(ts.SyntaxKind.StaticKeyword)], undefined, 'initModel', undefined, undefined, [ts.factory.createParameterDeclaration(undefined, undefined, 'sequelize', undefined, createGenericTypeReference('Sequelize', []), undefined)], ts.factory.createTypeQueryNode(ts.factory.createIdentifier(table.name)), ts.factory.createBlock([initCall, ts.factory.createReturnStatement(ts.factory.createIdentifier(table.name))], true));
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* Build the association mixin members a model contributes for one association.
|
|
294
|
+
* @param {IAssociationMetadata} association
|
|
295
|
+
* @param {ITableMetadata} table
|
|
296
|
+
* @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
|
|
297
|
+
* @returns {ts.PropertyDeclaration[]}
|
|
298
|
+
*/
|
|
299
|
+
const buildAssociationMixinMembers = (association, table, tablesByModel) => {
|
|
300
|
+
const alias = resolveAssociationPropertyName(association);
|
|
301
|
+
const target = tablesByModel.get(association.targetModel);
|
|
302
|
+
const targetPrimaryKeyAttribute = target ? resolvePrimaryKeyAttribute(target) : undefined;
|
|
303
|
+
const foreignKeyAttribute = resolveAssociationForeignKey(table, association, tablesByModel);
|
|
304
|
+
return buildAssociationMixinDeclarations(association, alias, targetPrimaryKeyAttribute, foreignKeyAttribute)
|
|
305
|
+
.map(buildMixinDeclaration);
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Build the model class declaration with its attribute, timestamp, mixin,
|
|
309
|
+
* included-association and static-association members and the init method.
|
|
310
|
+
* @param {ITableMetadata} table
|
|
311
|
+
* @param {Dialect} dialect
|
|
312
|
+
* @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
|
|
313
|
+
* @returns {ts.ClassDeclaration}
|
|
314
|
+
*/
|
|
315
|
+
export const buildModelClassDeclaration = (table, dialect, tablesByModel) => {
|
|
316
|
+
const associations = table.associations ?? [];
|
|
317
|
+
const members = [
|
|
318
|
+
...Object.values(table.columns).map(column => buildAttributeDeclaration(column, table, dialect, tablesByModel)),
|
|
319
|
+
...buildTimestampDeclarations(table),
|
|
320
|
+
...associations.flatMap(association => buildAssociationMixinMembers(association, table, tablesByModel)),
|
|
321
|
+
...associations.map(buildIncludedAssociationDeclaration),
|
|
322
|
+
];
|
|
323
|
+
const staticAssociations = buildStaticAssociationsDeclaration(table);
|
|
324
|
+
if (staticAssociations) {
|
|
325
|
+
members.push(staticAssociations);
|
|
326
|
+
}
|
|
327
|
+
members.push(buildInitModelMethod(table, dialect));
|
|
328
|
+
return ts.factory.createClassDeclaration([ts.factory.createToken(ts.SyntaxKind.ExportKeyword)], table.name, undefined, [ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [
|
|
329
|
+
ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier('Model'), [
|
|
330
|
+
createGenericTypeReference('InferAttributes', [createGenericTypeReference(table.name, [])]),
|
|
331
|
+
createGenericTypeReference('InferCreationAttributes', [createGenericTypeReference(table.name, [])]),
|
|
332
|
+
]),
|
|
333
|
+
])], members);
|
|
334
|
+
};
|
|
335
|
+
/**
|
|
336
|
+
* Render one native model source file: the `sequelize` named import, the
|
|
337
|
+
* cross-model `import type` declarations and the model class.
|
|
338
|
+
* @param {ITableMetadata} table
|
|
339
|
+
* @param {Dialect} dialect
|
|
340
|
+
* @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
|
|
341
|
+
* @returns {string}
|
|
342
|
+
*/
|
|
343
|
+
export const renderNativeModelFile = (table, dialect, tablesByModel) => {
|
|
344
|
+
let code = nodeToString(generateNamedImports(collectSequelizeImports(table, tablesByModel), 'sequelize'));
|
|
345
|
+
code += '\n';
|
|
346
|
+
for (const modelName of collectModelTypeImports(table, tablesByModel)) {
|
|
347
|
+
code += nodeToString(generateTypeOnlyImport([modelName], `./${modelName}`));
|
|
348
|
+
code += '\n';
|
|
349
|
+
}
|
|
350
|
+
code += '\n';
|
|
351
|
+
code += nodeToString(buildModelClassDeclaration(table, dialect, tablesByModel));
|
|
352
|
+
return code;
|
|
353
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IAssociationMetadata } from '../dialects/AssociationsParser.js';
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the class property name an association is exposed under. When the
|
|
4
|
+
* association carries a discovered alias it wins; otherwise the target model
|
|
5
|
+
* name is pluralized for to-many associations and singularized otherwise.
|
|
6
|
+
* @param {IAssociationMetadata} association
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export declare const resolveAssociationPropertyName: (association: IAssociationMetadata) => string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import pluralize from 'pluralize';
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the class property name an association is exposed under. When the
|
|
4
|
+
* association carries a discovered alias it wins; otherwise the target model
|
|
5
|
+
* name is pluralized for to-many associations and singularized otherwise.
|
|
6
|
+
* @param {IAssociationMetadata} association
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export const resolveAssociationPropertyName = (association) => {
|
|
10
|
+
if (association.alias) {
|
|
11
|
+
return association.alias;
|
|
12
|
+
}
|
|
13
|
+
return association.associationName.includes('Many') ?
|
|
14
|
+
pluralize.plural(association.targetModel) : pluralize.singular(association.targetModel);
|
|
15
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime package the decorators format depends on in the target project.
|
|
3
|
+
*/
|
|
4
|
+
export declare const DECORATORS_RUNTIME_PACKAGE = "sequelize-typescript";
|
|
5
|
+
/**
|
|
6
|
+
* Build the warning shown when the decorators runtime dependency cannot be
|
|
7
|
+
* resolved from the output directory.
|
|
8
|
+
* @param {string} outDir
|
|
9
|
+
* @returns {string}
|
|
10
|
+
*/
|
|
11
|
+
export declare const buildDecoratorsDependencyWarning: (outDir: string) => string;
|
|
12
|
+
/**
|
|
13
|
+
* Whether a package can be resolved starting from a directory. Never throws:
|
|
14
|
+
* a missing module resolves to false, any other resolution error to true so a
|
|
15
|
+
* transient failure does not surface a misleading dependency warning.
|
|
16
|
+
* @param {string} packageName
|
|
17
|
+
* @param {string} directory
|
|
18
|
+
* @returns {boolean}
|
|
19
|
+
*/
|
|
20
|
+
export declare const isPackageResolvableFrom: (packageName: string, directory: string) => boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Warn once when the decorators runtime dependency is missing from the output
|
|
23
|
+
* directory. Emitted only for the decorators format; never throws.
|
|
24
|
+
* @param {string} outDir
|
|
25
|
+
* @returns {void}
|
|
26
|
+
*/
|
|
27
|
+
export declare const warnWhenDecoratorsDependencyIsMissing: (outDir: string) => void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createRequire } from 'module';
|
|
2
|
+
import { isErrnoException } from '../utils/errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* Runtime package the decorators format depends on in the target project.
|
|
5
|
+
*/
|
|
6
|
+
export const DECORATORS_RUNTIME_PACKAGE = 'sequelize-typescript';
|
|
7
|
+
/**
|
|
8
|
+
* Build the warning shown when the decorators runtime dependency cannot be
|
|
9
|
+
* resolved from the output directory.
|
|
10
|
+
* @param {string} outDir
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export const buildDecoratorsDependencyWarning = (outDir) => `Warning: --format decorators emits models that import "${DECORATORS_RUNTIME_PACKAGE}", ` +
|
|
14
|
+
`but it cannot be resolved from ${outDir}. ` +
|
|
15
|
+
`Install it in the target project: npm install sequelize-typescript reflect-metadata\n` +
|
|
16
|
+
`Or use --format native (the default), which depends on sequelize only.`;
|
|
17
|
+
/**
|
|
18
|
+
* Whether a package can be resolved starting from a directory. Never throws:
|
|
19
|
+
* a missing module resolves to false, any other resolution error to true so a
|
|
20
|
+
* transient failure does not surface a misleading dependency warning.
|
|
21
|
+
* @param {string} packageName
|
|
22
|
+
* @param {string} directory
|
|
23
|
+
* @returns {boolean}
|
|
24
|
+
*/
|
|
25
|
+
export const isPackageResolvableFrom = (packageName, directory) => {
|
|
26
|
+
const require = createRequire(import.meta.url);
|
|
27
|
+
try {
|
|
28
|
+
require.resolve(packageName, { paths: [directory] });
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
return !(isErrnoException(err) && err.code === 'MODULE_NOT_FOUND');
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Warn once when the decorators runtime dependency is missing from the output
|
|
37
|
+
* directory. Emitted only for the decorators format; never throws.
|
|
38
|
+
* @param {string} outDir
|
|
39
|
+
* @returns {void}
|
|
40
|
+
*/
|
|
41
|
+
export const warnWhenDecoratorsDependencyIsMissing = (outDir) => {
|
|
42
|
+
if (!isPackageResolvableFrom(DECORATORS_RUNTIME_PACKAGE, outDir)) {
|
|
43
|
+
console.warn(buildDecoratorsDependencyWarning(outDir));
|
|
44
|
+
}
|
|
45
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as ts from 'typescript';
|
|
2
|
+
import type { DataTypeNamespace } from '../dialects/dataTypes.js';
|
|
3
|
+
/**
|
|
4
|
+
* Namespace-neutral description of a column default value. A `dataTypeMember`
|
|
5
|
+
* carries only the member name (e.g. `NOW`) so the target namespace is chosen at
|
|
6
|
+
* render time; a `sqlLiteral` carries the unescaped SQL passed to Sequelize.literal.
|
|
7
|
+
*/
|
|
8
|
+
export type DefaultValueDescriptor = {
|
|
9
|
+
kind: 'dataTypeMember';
|
|
10
|
+
member: string;
|
|
11
|
+
} | {
|
|
12
|
+
kind: 'sqlLiteral';
|
|
13
|
+
sql: string;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'number';
|
|
16
|
+
value: number;
|
|
17
|
+
} | {
|
|
18
|
+
kind: 'boolean';
|
|
19
|
+
value: boolean;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'string';
|
|
22
|
+
value: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Parse a decorators-spelled default value into a namespace-neutral descriptor.
|
|
26
|
+
* `DataType.NOW` becomes a data type member, `Sequelize.literal("...")` becomes a
|
|
27
|
+
* SQL literal with its double quotes unescaped, numbers and booleans pass through,
|
|
28
|
+
* and any other string becomes a quoted string. Returns undefined for a missing default.
|
|
29
|
+
* @param {unknown} raw
|
|
30
|
+
* @returns {DefaultValueDescriptor | undefined}
|
|
31
|
+
*/
|
|
32
|
+
export declare const parseDefaultValue: (raw: unknown) => DefaultValueDescriptor | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Build a compiler expression for a default value descriptor. Data type members
|
|
35
|
+
* render under the given namespace; SQL literals always render through Sequelize.literal.
|
|
36
|
+
* @param {DefaultValueDescriptor} descriptor
|
|
37
|
+
* @param {DataTypeNamespace} namespace
|
|
38
|
+
* @returns {ts.Expression}
|
|
39
|
+
*/
|
|
40
|
+
export declare const buildDefaultValueExpression: (descriptor: DefaultValueDescriptor, namespace: DataTypeNamespace) => ts.Expression;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import * as ts from 'typescript';
|
|
2
|
+
const DATA_TYPE_MEMBER_PATTERN = /^DataType\.([A-Za-z0-9_]+)$/;
|
|
3
|
+
const SQL_LITERAL_PATTERN = /^Sequelize\.literal\("([\s\S]*)"\)$/;
|
|
4
|
+
/**
|
|
5
|
+
* Parse a decorators-spelled default value into a namespace-neutral descriptor.
|
|
6
|
+
* `DataType.NOW` becomes a data type member, `Sequelize.literal("...")` becomes a
|
|
7
|
+
* SQL literal with its double quotes unescaped, numbers and booleans pass through,
|
|
8
|
+
* and any other string becomes a quoted string. Returns undefined for a missing default.
|
|
9
|
+
* @param {unknown} raw
|
|
10
|
+
* @returns {DefaultValueDescriptor | undefined}
|
|
11
|
+
*/
|
|
12
|
+
export const parseDefaultValue = (raw) => {
|
|
13
|
+
if (typeof raw === 'number') {
|
|
14
|
+
return { kind: 'number', value: raw };
|
|
15
|
+
}
|
|
16
|
+
if (typeof raw === 'boolean') {
|
|
17
|
+
return { kind: 'boolean', value: raw };
|
|
18
|
+
}
|
|
19
|
+
if (typeof raw === 'string') {
|
|
20
|
+
const memberMatch = raw.match(DATA_TYPE_MEMBER_PATTERN);
|
|
21
|
+
if (memberMatch) {
|
|
22
|
+
const [, member] = memberMatch;
|
|
23
|
+
return { kind: 'dataTypeMember', member };
|
|
24
|
+
}
|
|
25
|
+
const literalMatch = raw.match(SQL_LITERAL_PATTERN);
|
|
26
|
+
if (literalMatch) {
|
|
27
|
+
const [, sql] = literalMatch;
|
|
28
|
+
return { kind: 'sqlLiteral', sql: sql.replace(/\\"/g, '"') };
|
|
29
|
+
}
|
|
30
|
+
return { kind: 'string', value: raw };
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Build a compiler expression for a default value descriptor. Data type members
|
|
36
|
+
* render under the given namespace; SQL literals always render through Sequelize.literal.
|
|
37
|
+
* @param {DefaultValueDescriptor} descriptor
|
|
38
|
+
* @param {DataTypeNamespace} namespace
|
|
39
|
+
* @returns {ts.Expression}
|
|
40
|
+
*/
|
|
41
|
+
export const buildDefaultValueExpression = (descriptor, namespace) => {
|
|
42
|
+
switch (descriptor.kind) {
|
|
43
|
+
case 'dataTypeMember':
|
|
44
|
+
return ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespace), ts.factory.createIdentifier(descriptor.member));
|
|
45
|
+
case 'sqlLiteral':
|
|
46
|
+
return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('Sequelize'), ts.factory.createIdentifier('literal')), undefined, [ts.factory.createStringLiteral(descriptor.sql)]);
|
|
47
|
+
case 'number':
|
|
48
|
+
return descriptor.value < 0
|
|
49
|
+
? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(descriptor.value)))
|
|
50
|
+
: ts.factory.createNumericLiteral(descriptor.value);
|
|
51
|
+
case 'boolean':
|
|
52
|
+
return descriptor.value ? ts.factory.createTrue() : ts.factory.createFalse();
|
|
53
|
+
case 'string':
|
|
54
|
+
return ts.factory.createStringLiteral(descriptor.value);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Dialect, ITablesMetadata } from '../dialects/Dialect.js';
|
|
2
|
+
/**
|
|
3
|
+
* A rendered source file to write to the output directory.
|
|
4
|
+
*/
|
|
5
|
+
export interface IGeneratedFile {
|
|
6
|
+
fileName: string;
|
|
7
|
+
content: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Render the complete set of native output files: one model file per table, the
|
|
11
|
+
* `initModels.ts` wiring file and the `index.ts` barrel, in table order.
|
|
12
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
13
|
+
* @param {Dialect} dialect
|
|
14
|
+
* @returns {IGeneratedFile[]}
|
|
15
|
+
*/
|
|
16
|
+
export declare const renderNativeFiles: (tablesMetadata: ITablesMetadata, dialect: Dialect) => IGeneratedFile[];
|
|
17
|
+
/**
|
|
18
|
+
* Write the rendered files to the output directory, one file per descriptor.
|
|
19
|
+
* @param {string} outDir
|
|
20
|
+
* @param {IGeneratedFile[]} files
|
|
21
|
+
* @returns {Promise<void>}
|
|
22
|
+
*/
|
|
23
|
+
export declare const writeGeneratedFiles: (outDir: string, files: IGeneratedFile[]) => Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { indexTablesByModelName } from './nativeAttributes.js';
|
|
4
|
+
import { renderNativeModelFile } from './NativeModelRenderer.js';
|
|
5
|
+
import { renderInitModelsFile, renderNativeIndexFile } from './nativeWiring.js';
|
|
6
|
+
/**
|
|
7
|
+
* Render the complete set of native output files: one model file per table, the
|
|
8
|
+
* `initModels.ts` wiring file and the `index.ts` barrel, in table order.
|
|
9
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
10
|
+
* @param {Dialect} dialect
|
|
11
|
+
* @returns {IGeneratedFile[]}
|
|
12
|
+
*/
|
|
13
|
+
export const renderNativeFiles = (tablesMetadata, dialect) => {
|
|
14
|
+
const tablesByModel = indexTablesByModelName(tablesMetadata);
|
|
15
|
+
const files = Object.values(tablesMetadata).map(table => ({
|
|
16
|
+
fileName: `${table.name}.ts`,
|
|
17
|
+
content: renderNativeModelFile(table, dialect, tablesByModel),
|
|
18
|
+
}));
|
|
19
|
+
files.push({ fileName: 'initModels.ts', content: renderInitModelsFile(tablesMetadata, tablesByModel) });
|
|
20
|
+
files.push({ fileName: 'index.ts', content: renderNativeIndexFile(tablesMetadata) });
|
|
21
|
+
return files;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Write the rendered files to the output directory, one file per descriptor.
|
|
25
|
+
* @param {string} outDir
|
|
26
|
+
* @param {IGeneratedFile[]} files
|
|
27
|
+
* @returns {Promise<void>}
|
|
28
|
+
*/
|
|
29
|
+
export const writeGeneratedFiles = async (outDir, files) => {
|
|
30
|
+
await Promise.all(files.map(file => fs.writeFile(path.join(outDir, file.fileName), file.content, { flag: 'w', encoding: 'utf-8' })));
|
|
31
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { ModelBuilder } from './ModelBuilder';
|
|
1
|
+
export { ModelBuilder } from './ModelBuilder.js';
|
package/build/builders/index.js
CHANGED
|
@@ -1,5 +1 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ModelBuilder = void 0;
|
|
4
|
-
var ModelBuilder_1 = require("./ModelBuilder");
|
|
5
|
-
Object.defineProperty(exports, "ModelBuilder", { enumerable: true, get: function () { return ModelBuilder_1.ModelBuilder; } });
|
|
1
|
+
export { ModelBuilder } from './ModelBuilder.js';
|