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
|
@@ -1,15 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { QueryTypes } from 'sequelize';
|
|
2
|
+
import { DataTypes } from 'sequelize';
|
|
3
|
+
import { Dialect } from './Dialect.js';
|
|
4
|
+
import { warnUnknownMappingForDataType } from './utils.js';
|
|
5
|
+
import { buildSequelizeDataType, renderDataTypeExpression, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
|
|
6
|
+
import { groupForeignKeyRows } from './foreignKeys.js';
|
|
7
|
+
/**
|
|
8
|
+
* Build a synthesized constraint name for a SQLite foreign key from its ordered source
|
|
9
|
+
* columns. SQLite foreign keys are unnamed and two of them may cover the same column set,
|
|
10
|
+
* so a name already produced for the table is disambiguated with the pragma_foreign_key_list
|
|
11
|
+
* id; the first occurrence of a name keeps the plain form.
|
|
12
|
+
* @param {string} table
|
|
13
|
+
* @param {string[]} columns
|
|
14
|
+
* @param {number} id
|
|
15
|
+
* @param {ReadonlySet<string>} takenNames
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export const synthesizeSqliteConstraintName = (table, columns, id, takenNames) => {
|
|
19
|
+
const baseName = `${table}_${columns.join('_')}_fkey`;
|
|
20
|
+
return takenNames.has(baseName) ? `${baseName}_${id}` : baseName;
|
|
21
|
+
};
|
|
8
22
|
/**
|
|
9
23
|
* Dialect for SQLite
|
|
10
24
|
* @class DialectSQLite
|
|
11
25
|
*/
|
|
12
|
-
class DialectSQLite extends
|
|
26
|
+
export class DialectSQLite extends Dialect {
|
|
13
27
|
constructor() {
|
|
14
28
|
super('sqlite');
|
|
15
29
|
}
|
|
@@ -22,19 +36,19 @@ class DialectSQLite extends Dialect_1.Dialect {
|
|
|
22
36
|
// Affinity rules from https://www.sqlite.org/datatype3.html
|
|
23
37
|
const dbTypeUpper = dbType.toUpperCase();
|
|
24
38
|
if (dbTypeUpper.includes('INT')) {
|
|
25
|
-
return
|
|
39
|
+
return DataTypes.INTEGER;
|
|
26
40
|
}
|
|
27
41
|
else if (dbTypeUpper.includes('CHAR') || dbTypeUpper.includes('CLOB') || dbTypeUpper.includes('TEXT')) {
|
|
28
|
-
return
|
|
42
|
+
return DataTypes.STRING;
|
|
29
43
|
}
|
|
30
44
|
else if (dbTypeUpper.includes('BLOB')) {
|
|
31
|
-
return
|
|
45
|
+
return DataTypes.BLOB;
|
|
32
46
|
}
|
|
33
47
|
else if (dbTypeUpper.includes('REAL') || dbTypeUpper.includes('FLOA') || dbTypeUpper.includes('DOUB')) {
|
|
34
|
-
return
|
|
48
|
+
return DataTypes.REAL;
|
|
35
49
|
}
|
|
36
50
|
else {
|
|
37
|
-
return
|
|
51
|
+
return DataTypes.DECIMAL;
|
|
38
52
|
}
|
|
39
53
|
}
|
|
40
54
|
/**
|
|
@@ -80,12 +94,12 @@ class DialectSQLite extends Dialect_1.Dialect {
|
|
|
80
94
|
WHERE type ='table' AND name NOT LIKE 'sqlite_%';
|
|
81
95
|
`;
|
|
82
96
|
const tables = (await connection.query(query, {
|
|
83
|
-
type:
|
|
97
|
+
type: QueryTypes.SELECT,
|
|
84
98
|
raw: true,
|
|
85
99
|
})).map(({ table_name, table_comment }) => {
|
|
86
100
|
const t = {
|
|
87
101
|
name: table_name,
|
|
88
|
-
comment: table_comment
|
|
102
|
+
comment: table_comment ?? undefined,
|
|
89
103
|
};
|
|
90
104
|
return t;
|
|
91
105
|
});
|
|
@@ -95,25 +109,28 @@ class DialectSQLite extends Dialect_1.Dialect {
|
|
|
95
109
|
const columnsMetadata = [];
|
|
96
110
|
const query = `PRAGMA main.table_info('${table}')`;
|
|
97
111
|
const columns = await connection.query(query, {
|
|
98
|
-
type:
|
|
112
|
+
type: QueryTypes.SELECT,
|
|
99
113
|
raw: true,
|
|
100
114
|
});
|
|
101
115
|
for (const column of columns) {
|
|
102
116
|
// Unknown data type
|
|
103
117
|
if (!this.mapDbTypeToSequelize(column.type)) {
|
|
104
|
-
|
|
118
|
+
warnUnknownMappingForDataType(column.type);
|
|
105
119
|
}
|
|
120
|
+
const sequelizeConstructor = this.mapDbTypeToSequelize(column.type);
|
|
121
|
+
const sequelizeType = sequelizeConstructor
|
|
122
|
+
? buildSequelizeDataType(sequelizeConstructor, [])
|
|
123
|
+
: undefined;
|
|
106
124
|
const columnMetadata = {
|
|
107
125
|
name: column.name,
|
|
108
126
|
originName: column.name,
|
|
109
127
|
type: column.type,
|
|
110
128
|
typeExt: column.type,
|
|
111
|
-
...
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
.split(' ')[0], // avoids 'DOUBLE PRECISION' key to include PRECISION in the mapping
|
|
129
|
+
...sequelizeType && {
|
|
130
|
+
sequelizeType,
|
|
131
|
+
dataType: renderDataTypeExpression(sequelizeType, DATA_TYPE_NAMESPACES.decorators),
|
|
115
132
|
},
|
|
116
|
-
allowNull:
|
|
133
|
+
allowNull: !column.notnull,
|
|
117
134
|
primaryKey: !!column.pk,
|
|
118
135
|
autoIncrement: !!column.pk,
|
|
119
136
|
indices: [],
|
|
@@ -142,7 +159,7 @@ class DialectSQLite extends Dialect_1.Dialect {
|
|
|
142
159
|
ORDER BY il.seq;
|
|
143
160
|
`;
|
|
144
161
|
const indices = await connection.query(query, {
|
|
145
|
-
type:
|
|
162
|
+
type: QueryTypes.SELECT,
|
|
146
163
|
raw: true,
|
|
147
164
|
});
|
|
148
165
|
for (const index of indices) {
|
|
@@ -154,5 +171,130 @@ class DialectSQLite extends Dialect_1.Dialect {
|
|
|
154
171
|
}
|
|
155
172
|
return indicesMetadata;
|
|
156
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Fetch foreign key constraints for the provided table. SQLite constraints have no
|
|
176
|
+
* name, so each one is given the synthesized name `${table}_${sourceColumns}_fkey`,
|
|
177
|
+
* built from its ordered source columns. A constraint that omits the referenced
|
|
178
|
+
* column targets the primary key of the referenced table, resolved in key order.
|
|
179
|
+
* @param {Sequelize} connection
|
|
180
|
+
* @param {IConfig} config
|
|
181
|
+
* @param {ITable} table
|
|
182
|
+
* @returns {Promise<IForeignKeyConstraintMetadata[]>}
|
|
183
|
+
*/
|
|
184
|
+
async fetchForeignKeysMetadata(connection, config, table) {
|
|
185
|
+
const foreignKeyRows = await connection.query(`
|
|
186
|
+
SELECT
|
|
187
|
+
id,
|
|
188
|
+
seq,
|
|
189
|
+
"table" AS target_table,
|
|
190
|
+
"from" AS source_column,
|
|
191
|
+
"to" AS target_column,
|
|
192
|
+
on_update,
|
|
193
|
+
on_delete
|
|
194
|
+
FROM pragma_foreign_key_list('${table.name}')
|
|
195
|
+
ORDER BY id, seq;
|
|
196
|
+
`, {
|
|
197
|
+
type: QueryTypes.SELECT,
|
|
198
|
+
raw: true,
|
|
199
|
+
});
|
|
200
|
+
if (!foreignKeyRows.length) {
|
|
201
|
+
return [];
|
|
202
|
+
}
|
|
203
|
+
const uniqueSourceColumns = await this.fetchSingleColumnUniqueColumns(connection, table.name);
|
|
204
|
+
// Primary key columns per referenced table, resolved lazily for constraints
|
|
205
|
+
// that omit the referenced column.
|
|
206
|
+
const targetPrimaryKeyColumns = new Map();
|
|
207
|
+
const resolveTargetPrimaryKeyColumns = async (targetTable) => {
|
|
208
|
+
const cached = targetPrimaryKeyColumns.get(targetTable);
|
|
209
|
+
if (cached) {
|
|
210
|
+
return cached;
|
|
211
|
+
}
|
|
212
|
+
const primaryKeyColumns = await this.fetchPrimaryKeyColumns(connection, targetTable);
|
|
213
|
+
targetPrimaryKeyColumns.set(targetTable, primaryKeyColumns);
|
|
214
|
+
return primaryKeyColumns;
|
|
215
|
+
};
|
|
216
|
+
// Rows sharing an id form one (possibly composite) constraint.
|
|
217
|
+
const rowsById = new Map();
|
|
218
|
+
for (const row of foreignKeyRows) {
|
|
219
|
+
const group = rowsById.get(row.id) ?? [];
|
|
220
|
+
group.push(row);
|
|
221
|
+
rowsById.set(row.id, group);
|
|
222
|
+
}
|
|
223
|
+
const rows = [];
|
|
224
|
+
const takenConstraintNames = new Set();
|
|
225
|
+
for (const group of rowsById.values()) {
|
|
226
|
+
const ordered = [...group].sort((a, b) => a.seq - b.seq);
|
|
227
|
+
const sourceColumns = ordered.map(row => row.source_column);
|
|
228
|
+
const [{ id: constraintId, target_table: targetTable }] = ordered;
|
|
229
|
+
const constraintName = synthesizeSqliteConstraintName(table.name, sourceColumns, constraintId, takenConstraintNames);
|
|
230
|
+
takenConstraintNames.add(constraintName);
|
|
231
|
+
const needsPrimaryKeyResolution = ordered.some(row => row.target_column === null);
|
|
232
|
+
const targetPrimaryKey = needsPrimaryKeyResolution
|
|
233
|
+
? await resolveTargetPrimaryKeyColumns(targetTable)
|
|
234
|
+
: [];
|
|
235
|
+
for (const row of ordered) {
|
|
236
|
+
const targetColumn = row.target_column ?? targetPrimaryKey[row.seq] ?? '';
|
|
237
|
+
rows.push({
|
|
238
|
+
constraintName,
|
|
239
|
+
sourceTable: table.name,
|
|
240
|
+
sourceColumn: row.source_column,
|
|
241
|
+
targetTable: row.target_table,
|
|
242
|
+
targetColumn,
|
|
243
|
+
ordinalPosition: row.seq,
|
|
244
|
+
onDelete: row.on_delete,
|
|
245
|
+
onUpdate: row.on_update,
|
|
246
|
+
isSourceColumnUnique: uniqueSourceColumns.has(row.source_column),
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return groupForeignKeyRows(rows);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Collect the source columns covered by a single-column unique index or primary key,
|
|
254
|
+
* used to flag one-to-one foreign keys.
|
|
255
|
+
* @param {Sequelize} connection
|
|
256
|
+
* @param {string} table
|
|
257
|
+
* @returns {Promise<Set<string>>}
|
|
258
|
+
*/
|
|
259
|
+
async fetchSingleColumnUniqueColumns(connection, table) {
|
|
260
|
+
const uniqueIndexColumns = await connection.query(`
|
|
261
|
+
SELECT ii.name AS column_name
|
|
262
|
+
FROM pragma_index_list('${table}') il
|
|
263
|
+
JOIN pragma_index_info(il.name) ii
|
|
264
|
+
WHERE il."unique" = 1 AND il.partial = 0
|
|
265
|
+
GROUP BY il.name
|
|
266
|
+
HAVING COUNT(*) = 1;
|
|
267
|
+
`, {
|
|
268
|
+
type: QueryTypes.SELECT,
|
|
269
|
+
raw: true,
|
|
270
|
+
});
|
|
271
|
+
const uniqueColumns = new Set(uniqueIndexColumns.map(row => row.column_name));
|
|
272
|
+
// An INTEGER PRIMARY KEY is a rowid alias with no backing index, so
|
|
273
|
+
// pragma_index_list does not report it; a single-column primary key is unique.
|
|
274
|
+
const tableInfo = await connection.query(`SELECT name, pk FROM pragma_table_info('${table}');`, {
|
|
275
|
+
type: QueryTypes.SELECT,
|
|
276
|
+
raw: true,
|
|
277
|
+
});
|
|
278
|
+
const primaryKeyColumns = tableInfo.filter(column => column.pk > 0);
|
|
279
|
+
if (primaryKeyColumns.length === 1) {
|
|
280
|
+
uniqueColumns.add(primaryKeyColumns[0].name);
|
|
281
|
+
}
|
|
282
|
+
return uniqueColumns;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Fetch the primary key column names of a table, ordered by their key position.
|
|
286
|
+
* @param {Sequelize} connection
|
|
287
|
+
* @param {string} table
|
|
288
|
+
* @returns {Promise<string[]>}
|
|
289
|
+
*/
|
|
290
|
+
async fetchPrimaryKeyColumns(connection, table) {
|
|
291
|
+
const tableInfo = await connection.query(`SELECT name, pk FROM pragma_table_info('${table}');`, {
|
|
292
|
+
type: QueryTypes.SELECT,
|
|
293
|
+
raw: true,
|
|
294
|
+
});
|
|
295
|
+
return tableInfo
|
|
296
|
+
.filter(column => column.pk > 0)
|
|
297
|
+
.sort((a, b) => a.pk - b.pk)
|
|
298
|
+
.map(column => column.name);
|
|
299
|
+
}
|
|
157
300
|
}
|
|
158
|
-
exports.DialectSQLite = DialectSQLite;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ITablesMetadata, IForeignKeyConstraintMetadata } from './Dialect.js';
|
|
2
|
+
import type { IConfigMetadata } from '../config/IConfig.js';
|
|
3
|
+
import { ForeignKeySkipReason } from './foreignKeys.js';
|
|
4
|
+
/**
|
|
5
|
+
* Foreign key column name suffixes stripped when deriving an alias from the column.
|
|
6
|
+
*/
|
|
7
|
+
export declare const FOREIGN_KEY_COLUMN_SUFFIXES: readonly ["_id", "_fk", "Id", "Fk"];
|
|
8
|
+
/**
|
|
9
|
+
* Result of association discovery: a new tables metadata carrying the discovered
|
|
10
|
+
* associations and one warning per constraint that could not become an association.
|
|
11
|
+
*/
|
|
12
|
+
export interface IAssociationDiscoveryResult {
|
|
13
|
+
tablesMetadata: ITablesMetadata;
|
|
14
|
+
warnings: string[];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A pair of aliases for the two sides of a discovered association.
|
|
18
|
+
*/
|
|
19
|
+
export interface IAliasPair {
|
|
20
|
+
belongsToAlias: string;
|
|
21
|
+
hasAlias: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Strip a foreign key column suffix to derive an alias stem.
|
|
25
|
+
* @param {string} columnName
|
|
26
|
+
* @returns {string | undefined} the stem, or undefined when no suffix matches or the remainder is empty
|
|
27
|
+
*/
|
|
28
|
+
export declare const stripForeignKeyColumnSuffix: (columnName: string) => string | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Resolve the primary alias pair for an association, before any collision handling.
|
|
31
|
+
* Unambiguous constraints use the singular/plural model names; ambiguous ones use the
|
|
32
|
+
* stripped foreign key stem when available, otherwise the composed fallback form.
|
|
33
|
+
* @param {{ sourceModel: string; targetModel: string; foreignKeyColumn: string; isAmbiguous: boolean; isOneToOne: boolean }} input
|
|
34
|
+
* @returns {IAliasPair}
|
|
35
|
+
*/
|
|
36
|
+
export declare const resolveAssociationAliases: (input: {
|
|
37
|
+
sourceModel: string;
|
|
38
|
+
targetModel: string;
|
|
39
|
+
foreignKeyColumn: string;
|
|
40
|
+
isAmbiguous: boolean;
|
|
41
|
+
isOneToOne: boolean;
|
|
42
|
+
}) => IAliasPair;
|
|
43
|
+
/**
|
|
44
|
+
* Warning texts for constraints that cannot become associations.
|
|
45
|
+
* @param {IForeignKeyConstraintMetadata} constraint
|
|
46
|
+
* @param {string | undefined} sourceSchema
|
|
47
|
+
* @param {ForeignKeySkipReason} reason
|
|
48
|
+
* @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
export declare const formatForeignKeySkipWarning: (constraint: IForeignKeyConstraintMetadata, sourceSchema: string | undefined, reason: ForeignKeySkipReason) => string;
|
|
51
|
+
/**
|
|
52
|
+
* Whether association discovery is enabled for the given config metadata.
|
|
53
|
+
* @param {IConfigMetadata | undefined} metadata
|
|
54
|
+
* @returns {boolean}
|
|
55
|
+
*/
|
|
56
|
+
export declare const isAssociationDiscoveryEnabled: (metadata: IConfigMetadata | undefined) => boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Derive one-to-one and one-to-many associations from the foreign key constraints of
|
|
59
|
+
* every table. Returns a new tables metadata with discovered associations appended and
|
|
60
|
+
* a warning per constraint that cannot become an association. The input is not mutated.
|
|
61
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
62
|
+
* @returns {IAssociationDiscoveryResult}
|
|
63
|
+
*/
|
|
64
|
+
export declare const discoverAssociations: (tablesMetadata: ITablesMetadata) => IAssociationDiscoveryResult;
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import pluralize from 'pluralize';
|
|
2
|
+
import { camelCase } from 'change-case';
|
|
3
|
+
import { classifyForeignKeyConstraint, } from './foreignKeys.js';
|
|
4
|
+
/**
|
|
5
|
+
* Foreign key column name suffixes stripped when deriving an alias from the column.
|
|
6
|
+
*/
|
|
7
|
+
export const FOREIGN_KEY_COLUMN_SUFFIXES = ['_id', '_fk', 'Id', 'Fk'];
|
|
8
|
+
/**
|
|
9
|
+
* Maximum numeric suffix tried when resolving an alias collision.
|
|
10
|
+
*/
|
|
11
|
+
const MAX_ALIAS_SUFFIX = 1000;
|
|
12
|
+
/**
|
|
13
|
+
* Strip a foreign key column suffix to derive an alias stem.
|
|
14
|
+
* @param {string} columnName
|
|
15
|
+
* @returns {string | undefined} the stem, or undefined when no suffix matches or the remainder is empty
|
|
16
|
+
*/
|
|
17
|
+
export const stripForeignKeyColumnSuffix = (columnName) => {
|
|
18
|
+
for (const suffix of FOREIGN_KEY_COLUMN_SUFFIXES) {
|
|
19
|
+
if (columnName.length > suffix.length && columnName.endsWith(suffix)) {
|
|
20
|
+
return columnName.slice(0, columnName.length - suffix.length);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The side of the source model an association exposes: singular for one-to-one,
|
|
27
|
+
* plural otherwise.
|
|
28
|
+
* @param {string} sourceModel
|
|
29
|
+
* @param {boolean} isOneToOne
|
|
30
|
+
* @returns {string}
|
|
31
|
+
*/
|
|
32
|
+
const buildSourceSideName = (sourceModel, isOneToOne) => isOneToOne ? pluralize.singular(sourceModel) : pluralize.plural(sourceModel);
|
|
33
|
+
/**
|
|
34
|
+
* Aliases used when a single constraint links the two tables.
|
|
35
|
+
* @param {string} sourceModel
|
|
36
|
+
* @param {string} targetModel
|
|
37
|
+
* @param {boolean} isOneToOne
|
|
38
|
+
* @returns {IAliasPair}
|
|
39
|
+
*/
|
|
40
|
+
const buildPrimaryAliases = (sourceModel, targetModel, isOneToOne) => ({
|
|
41
|
+
belongsToAlias: pluralize.singular(targetModel),
|
|
42
|
+
hasAlias: buildSourceSideName(sourceModel, isOneToOne),
|
|
43
|
+
});
|
|
44
|
+
/**
|
|
45
|
+
* Aliases derived from the foreign key column stem, used to disambiguate two
|
|
46
|
+
* constraints that link the same pair of tables.
|
|
47
|
+
* @param {string} stem
|
|
48
|
+
* @param {string} sourceModel
|
|
49
|
+
* @param {boolean} isOneToOne
|
|
50
|
+
* @returns {IAliasPair}
|
|
51
|
+
*/
|
|
52
|
+
const buildStrippedAliases = (stem, sourceModel, isOneToOne) => ({
|
|
53
|
+
belongsToAlias: stem,
|
|
54
|
+
hasAlias: camelCase(`${stem} ${buildSourceSideName(sourceModel, isOneToOne)}`),
|
|
55
|
+
});
|
|
56
|
+
/**
|
|
57
|
+
* Aliases composed from the target model and the foreign key column, used when the
|
|
58
|
+
* column has no strippable suffix.
|
|
59
|
+
* @param {string} sourceModel
|
|
60
|
+
* @param {string} targetModel
|
|
61
|
+
* @param {string} foreignKeyColumn
|
|
62
|
+
* @param {boolean} isOneToOne
|
|
63
|
+
* @returns {IAliasPair}
|
|
64
|
+
*/
|
|
65
|
+
const buildFallbackAliases = (sourceModel, targetModel, foreignKeyColumn, isOneToOne) => ({
|
|
66
|
+
belongsToAlias: camelCase(`${pluralize.singular(targetModel)} ${foreignKeyColumn}`),
|
|
67
|
+
hasAlias: camelCase(`${foreignKeyColumn} ${buildSourceSideName(sourceModel, isOneToOne)}`),
|
|
68
|
+
});
|
|
69
|
+
/**
|
|
70
|
+
* Resolve the primary alias pair for an association, before any collision handling.
|
|
71
|
+
* Unambiguous constraints use the singular/plural model names; ambiguous ones use the
|
|
72
|
+
* stripped foreign key stem when available, otherwise the composed fallback form.
|
|
73
|
+
* @param {{ sourceModel: string; targetModel: string; foreignKeyColumn: string; isAmbiguous: boolean; isOneToOne: boolean }} input
|
|
74
|
+
* @returns {IAliasPair}
|
|
75
|
+
*/
|
|
76
|
+
export const resolveAssociationAliases = (input) => {
|
|
77
|
+
const { sourceModel, targetModel, foreignKeyColumn, isAmbiguous, isOneToOne } = input;
|
|
78
|
+
if (!isAmbiguous) {
|
|
79
|
+
return buildPrimaryAliases(sourceModel, targetModel, isOneToOne);
|
|
80
|
+
}
|
|
81
|
+
const stem = stripForeignKeyColumnSuffix(foreignKeyColumn);
|
|
82
|
+
if (stem !== undefined) {
|
|
83
|
+
return buildStrippedAliases(stem, sourceModel, isOneToOne);
|
|
84
|
+
}
|
|
85
|
+
return buildFallbackAliases(sourceModel, targetModel, foreignKeyColumn, isOneToOne);
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Warning texts for constraints that cannot become associations.
|
|
89
|
+
* @param {IForeignKeyConstraintMetadata} constraint
|
|
90
|
+
* @param {string | undefined} sourceSchema
|
|
91
|
+
* @param {ForeignKeySkipReason} reason
|
|
92
|
+
* @returns {string}
|
|
93
|
+
*/
|
|
94
|
+
export const formatForeignKeySkipWarning = (constraint, sourceSchema, reason) => {
|
|
95
|
+
switch (reason) {
|
|
96
|
+
case 'composite':
|
|
97
|
+
return `Foreign key constraint '${constraint.constraintName}' on table '${constraint.sourceTable}' `
|
|
98
|
+
+ `spans columns (${constraint.sourceColumns.join(', ')}); Sequelize associations need a single `
|
|
99
|
+
+ `column, so the columns are generated as plain attributes`;
|
|
100
|
+
case 'cross-schema':
|
|
101
|
+
return `Foreign key constraint '${constraint.constraintName}' on table `
|
|
102
|
+
+ `'${sourceSchema}.${constraint.sourceTable}' references table `
|
|
103
|
+
+ `'${constraint.targetSchema}.${constraint.targetTable}' in another schema; `
|
|
104
|
+
+ `the column is generated as a plain attribute`;
|
|
105
|
+
case 'excluded-target':
|
|
106
|
+
return `Foreign key constraint '${constraint.constraintName}' on table '${constraint.sourceTable}' `
|
|
107
|
+
+ `references table '${constraint.targetTable}', which is not among the generated tables; `
|
|
108
|
+
+ `the column is generated as a plain attribute`;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Whether association discovery is enabled for the given config metadata.
|
|
113
|
+
* @param {IConfigMetadata | undefined} metadata
|
|
114
|
+
* @returns {boolean}
|
|
115
|
+
*/
|
|
116
|
+
export const isAssociationDiscoveryEnabled = (metadata) => metadata?.associations !== false;
|
|
117
|
+
/**
|
|
118
|
+
* Ordered alias-pair candidates tried when resolving a collision: the primary form
|
|
119
|
+
* (only when unambiguous), the ambiguous form, the fallback form, then the fallback
|
|
120
|
+
* form with an increasing numeric suffix.
|
|
121
|
+
*/
|
|
122
|
+
const buildAliasCandidates = (input) => {
|
|
123
|
+
const { sourceModel, targetModel, foreignKeyColumn, isOneToOne } = input;
|
|
124
|
+
const candidates = [];
|
|
125
|
+
if (!input.isAmbiguous) {
|
|
126
|
+
candidates.push(buildPrimaryAliases(sourceModel, targetModel, isOneToOne));
|
|
127
|
+
}
|
|
128
|
+
candidates.push(resolveAssociationAliases({ ...input, isAmbiguous: true }));
|
|
129
|
+
const fallback = buildFallbackAliases(sourceModel, targetModel, foreignKeyColumn, isOneToOne);
|
|
130
|
+
candidates.push(fallback);
|
|
131
|
+
for (let suffix = 2; suffix < MAX_ALIAS_SUFFIX; suffix++) {
|
|
132
|
+
candidates.push({
|
|
133
|
+
belongsToAlias: `${fallback.belongsToAlias}${suffix}`,
|
|
134
|
+
hasAlias: `${fallback.hasAlias}${suffix}`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return candidates;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Lazily build the set of names already taken on a model, seeded with its column
|
|
141
|
+
* field names.
|
|
142
|
+
*/
|
|
143
|
+
const getTakenNames = (takenByModel, tablesMetadata, modelKey) => {
|
|
144
|
+
const existing = takenByModel.get(modelKey);
|
|
145
|
+
if (existing) {
|
|
146
|
+
return existing;
|
|
147
|
+
}
|
|
148
|
+
const taken = new Set();
|
|
149
|
+
const table = tablesMetadata[modelKey];
|
|
150
|
+
if (table) {
|
|
151
|
+
for (const column of Object.values(table.columns)) {
|
|
152
|
+
taken.add(column.name);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
takenByModel.set(modelKey, taken);
|
|
156
|
+
return taken;
|
|
157
|
+
};
|
|
158
|
+
/**
|
|
159
|
+
* Pick the first candidate alias pair whose names are free on both models. For a
|
|
160
|
+
* self-reference both names live on the source model and must differ.
|
|
161
|
+
*/
|
|
162
|
+
const pickFreeAliases = (candidates, sourceTaken, targetTaken, isSelfReference) => {
|
|
163
|
+
for (const candidate of candidates) {
|
|
164
|
+
if (isSelfReference) {
|
|
165
|
+
const isFree = candidate.belongsToAlias !== candidate.hasAlias
|
|
166
|
+
&& !sourceTaken.has(candidate.belongsToAlias)
|
|
167
|
+
&& !sourceTaken.has(candidate.hasAlias);
|
|
168
|
+
if (isFree) {
|
|
169
|
+
return candidate;
|
|
170
|
+
}
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (!sourceTaken.has(candidate.belongsToAlias) && !targetTaken.has(candidate.hasAlias)) {
|
|
174
|
+
return candidate;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return candidates[candidates.length - 1];
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* Count the eligible constraints on a table that target a given table.
|
|
181
|
+
*/
|
|
182
|
+
const countEligibleConstraintsToTarget = (constraints, sourceSchema, generatedTables, targetTable) => constraints.filter(constraint => classifyForeignKeyConstraint(constraint, sourceSchema, generatedTables).isEligible
|
|
183
|
+
&& constraint.targetTable === targetTable).length;
|
|
184
|
+
/**
|
|
185
|
+
* Derive one-to-one and one-to-many associations from the foreign key constraints of
|
|
186
|
+
* every table. Returns a new tables metadata with discovered associations appended and
|
|
187
|
+
* a warning per constraint that cannot become an association. The input is not mutated.
|
|
188
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
189
|
+
* @returns {IAssociationDiscoveryResult}
|
|
190
|
+
*/
|
|
191
|
+
export const discoverAssociations = (tablesMetadata) => {
|
|
192
|
+
const warnings = [];
|
|
193
|
+
const generatedTables = new Set(Object.values(tablesMetadata).map(table => table.originName));
|
|
194
|
+
const takenByModel = new Map();
|
|
195
|
+
const discoveredByModel = new Map();
|
|
196
|
+
const appendAssociation = (modelKey, association) => {
|
|
197
|
+
const list = discoveredByModel.get(modelKey) ?? [];
|
|
198
|
+
list.push(association);
|
|
199
|
+
discoveredByModel.set(modelKey, list);
|
|
200
|
+
};
|
|
201
|
+
for (const sourceKey of Object.keys(tablesMetadata)) {
|
|
202
|
+
const sourceTable = tablesMetadata[sourceKey];
|
|
203
|
+
const constraints = sourceTable.foreignKeys ?? [];
|
|
204
|
+
for (const constraint of constraints) {
|
|
205
|
+
const classification = classifyForeignKeyConstraint(constraint, sourceTable.schema, generatedTables);
|
|
206
|
+
if (!classification.isEligible) {
|
|
207
|
+
warnings.push(formatForeignKeySkipWarning(constraint, sourceTable.schema, classification.reason));
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const foreignKeyColumn = constraint.sourceColumns[0];
|
|
211
|
+
const targetColumn = constraint.targetColumns[0];
|
|
212
|
+
const targetKey = constraint.targetTable;
|
|
213
|
+
const column = Object.values(sourceTable.columns).find(candidate => candidate.originName === foreignKeyColumn);
|
|
214
|
+
if (!column) {
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const primaryKeyColumns = Object.values(sourceTable.columns).filter(candidate => candidate.primaryKey);
|
|
218
|
+
const isOneToOne = constraint.isSourceColumnUnique
|
|
219
|
+
|| (column.primaryKey && primaryKeyColumns.length === 1);
|
|
220
|
+
const isSelfReference = sourceTable.originName === constraint.targetTable;
|
|
221
|
+
const eligibleToTarget = countEligibleConstraintsToTarget(constraints, sourceTable.schema, generatedTables, constraint.targetTable);
|
|
222
|
+
const isAmbiguous = eligibleToTarget > 1 || isSelfReference;
|
|
223
|
+
const candidates = buildAliasCandidates({
|
|
224
|
+
sourceModel: sourceTable.originName,
|
|
225
|
+
targetModel: constraint.targetTable,
|
|
226
|
+
foreignKeyColumn,
|
|
227
|
+
isAmbiguous,
|
|
228
|
+
isOneToOne,
|
|
229
|
+
});
|
|
230
|
+
const sourceTaken = getTakenNames(takenByModel, tablesMetadata, sourceKey);
|
|
231
|
+
const targetTaken = getTakenNames(takenByModel, tablesMetadata, targetKey);
|
|
232
|
+
const { belongsToAlias, hasAlias } = pickFreeAliases(candidates, sourceTaken, targetTaken, isSelfReference);
|
|
233
|
+
const hasDeleteRule = constraint.onDelete !== 'NO ACTION';
|
|
234
|
+
const hasUpdateRule = constraint.onUpdate !== 'NO ACTION';
|
|
235
|
+
const belongsTo = {
|
|
236
|
+
associationName: 'BelongsTo',
|
|
237
|
+
targetModel: constraint.targetTable,
|
|
238
|
+
alias: belongsToAlias,
|
|
239
|
+
foreignKey: foreignKeyColumn,
|
|
240
|
+
targetKey: targetColumn,
|
|
241
|
+
...(hasDeleteRule && { onDelete: constraint.onDelete }),
|
|
242
|
+
...(hasUpdateRule && { onUpdate: constraint.onUpdate }),
|
|
243
|
+
};
|
|
244
|
+
const has = {
|
|
245
|
+
associationName: isOneToOne ? 'HasOne' : 'HasMany',
|
|
246
|
+
targetModel: sourceTable.originName,
|
|
247
|
+
alias: hasAlias,
|
|
248
|
+
foreignKey: foreignKeyColumn,
|
|
249
|
+
sourceKey: targetColumn,
|
|
250
|
+
...(hasDeleteRule && { onDelete: constraint.onDelete }),
|
|
251
|
+
...(hasUpdateRule && { onUpdate: constraint.onUpdate }),
|
|
252
|
+
};
|
|
253
|
+
sourceTaken.add(belongsToAlias);
|
|
254
|
+
if (isSelfReference) {
|
|
255
|
+
sourceTaken.add(hasAlias);
|
|
256
|
+
appendAssociation(sourceKey, belongsTo);
|
|
257
|
+
appendAssociation(sourceKey, has);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
targetTaken.add(hasAlias);
|
|
261
|
+
appendAssociation(sourceKey, belongsTo);
|
|
262
|
+
appendAssociation(targetKey, has);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const nextTablesMetadata = {};
|
|
267
|
+
for (const [tableKey, table] of Object.entries(tablesMetadata)) {
|
|
268
|
+
const discovered = discoveredByModel.get(tableKey);
|
|
269
|
+
const nextTable = discovered
|
|
270
|
+
? { ...table, associations: [...(table.associations ?? []), ...discovered] }
|
|
271
|
+
: { ...table };
|
|
272
|
+
nextTablesMetadata[tableKey] = nextTable;
|
|
273
|
+
}
|
|
274
|
+
return { tablesMetadata: nextTablesMetadata, warnings };
|
|
275
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ITablesMetadata } from './Dialect.js';
|
|
2
|
+
import type { IAssociationsParsed } from './AssociationsParser.js';
|
|
3
|
+
/**
|
|
4
|
+
* Result of applying the associations file on top of the discovered associations: a
|
|
5
|
+
* new tables metadata and the warnings raised for entries that could not be applied.
|
|
6
|
+
*/
|
|
7
|
+
export interface IAssociationsFileMergeResult {
|
|
8
|
+
tablesMetadata: ITablesMetadata;
|
|
9
|
+
warnings: string[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Apply the parsed associations file on top of discovered associations. For every
|
|
13
|
+
* declared foreign key the paired discovered association is dropped (junction rows keep
|
|
14
|
+
* their discovered associations), the column foreign key is rewritten to the declared
|
|
15
|
+
* target, the declared associations are appended, and any discovered association whose
|
|
16
|
+
* alias collides with a declared association is dropped. The inputs are not mutated.
|
|
17
|
+
* @param {ITablesMetadata} tablesMetadata
|
|
18
|
+
* @param {IAssociationsParsed} parsed
|
|
19
|
+
* @returns {IAssociationsFileMergeResult}
|
|
20
|
+
*/
|
|
21
|
+
export declare const applyAssociationsFile: (tablesMetadata: ITablesMetadata, parsed: IAssociationsParsed) => IAssociationsFileMergeResult;
|