@mikro-orm/sql 7.0.4-dev.8 → 7.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/AbstractSqlConnection.d.ts +94 -58
  2. package/AbstractSqlConnection.js +235 -238
  3. package/AbstractSqlDriver.d.ts +410 -155
  4. package/AbstractSqlDriver.js +2064 -1941
  5. package/AbstractSqlPlatform.d.ts +83 -73
  6. package/AbstractSqlPlatform.js +162 -158
  7. package/PivotCollectionPersister.d.ts +33 -15
  8. package/PivotCollectionPersister.js +158 -160
  9. package/README.md +1 -1
  10. package/SqlEntityManager.d.ts +67 -22
  11. package/SqlEntityManager.js +54 -38
  12. package/SqlEntityRepository.d.ts +14 -14
  13. package/SqlEntityRepository.js +23 -23
  14. package/dialects/mssql/MsSqlNativeQueryBuilder.d.ts +12 -12
  15. package/dialects/mssql/MsSqlNativeQueryBuilder.js +192 -194
  16. package/dialects/mysql/BaseMySqlPlatform.d.ts +64 -45
  17. package/dialects/mysql/BaseMySqlPlatform.js +134 -131
  18. package/dialects/mysql/MySqlExceptionConverter.d.ts +6 -6
  19. package/dialects/mysql/MySqlExceptionConverter.js +91 -77
  20. package/dialects/mysql/MySqlNativeQueryBuilder.d.ts +3 -3
  21. package/dialects/mysql/MySqlNativeQueryBuilder.js +66 -69
  22. package/dialects/mysql/MySqlSchemaHelper.d.ts +39 -39
  23. package/dialects/mysql/MySqlSchemaHelper.js +327 -319
  24. package/dialects/oracledb/OracleDialect.d.ts +81 -52
  25. package/dialects/oracledb/OracleDialect.js +155 -149
  26. package/dialects/oracledb/OracleNativeQueryBuilder.d.ts +12 -12
  27. package/dialects/oracledb/OracleNativeQueryBuilder.js +232 -236
  28. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +109 -105
  29. package/dialects/postgresql/BasePostgreSqlPlatform.js +354 -350
  30. package/dialects/postgresql/FullTextType.d.ts +10 -6
  31. package/dialects/postgresql/FullTextType.js +51 -51
  32. package/dialects/postgresql/PostgreSqlExceptionConverter.d.ts +5 -5
  33. package/dialects/postgresql/PostgreSqlExceptionConverter.js +55 -43
  34. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.d.ts +1 -1
  35. package/dialects/postgresql/PostgreSqlNativeQueryBuilder.js +4 -4
  36. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +102 -82
  37. package/dialects/postgresql/PostgreSqlSchemaHelper.js +733 -705
  38. package/dialects/sqlite/BaseSqliteConnection.d.ts +3 -5
  39. package/dialects/sqlite/BaseSqliteConnection.js +21 -19
  40. package/dialects/sqlite/NodeSqliteDialect.d.ts +1 -1
  41. package/dialects/sqlite/NodeSqliteDialect.js +23 -23
  42. package/dialects/sqlite/SqliteDriver.d.ts +1 -1
  43. package/dialects/sqlite/SqliteDriver.js +3 -3
  44. package/dialects/sqlite/SqliteExceptionConverter.d.ts +6 -6
  45. package/dialects/sqlite/SqliteExceptionConverter.js +67 -51
  46. package/dialects/sqlite/SqliteNativeQueryBuilder.d.ts +2 -2
  47. package/dialects/sqlite/SqliteNativeQueryBuilder.js +7 -7
  48. package/dialects/sqlite/SqlitePlatform.d.ts +63 -72
  49. package/dialects/sqlite/SqlitePlatform.js +139 -139
  50. package/dialects/sqlite/SqliteSchemaHelper.d.ts +70 -60
  51. package/dialects/sqlite/SqliteSchemaHelper.js +533 -520
  52. package/package.json +3 -3
  53. package/plugin/index.d.ts +42 -35
  54. package/plugin/index.js +43 -36
  55. package/plugin/transformer.d.ts +117 -94
  56. package/plugin/transformer.js +890 -881
  57. package/query/ArrayCriteriaNode.d.ts +4 -4
  58. package/query/ArrayCriteriaNode.js +18 -18
  59. package/query/CriteriaNode.d.ts +35 -25
  60. package/query/CriteriaNode.js +133 -123
  61. package/query/CriteriaNodeFactory.d.ts +49 -6
  62. package/query/CriteriaNodeFactory.js +97 -94
  63. package/query/NativeQueryBuilder.d.ts +118 -118
  64. package/query/NativeQueryBuilder.js +484 -480
  65. package/query/ObjectCriteriaNode.d.ts +12 -12
  66. package/query/ObjectCriteriaNode.js +298 -282
  67. package/query/QueryBuilder.d.ts +1557 -905
  68. package/query/QueryBuilder.js +2322 -2192
  69. package/query/QueryBuilderHelper.d.ts +153 -72
  70. package/query/QueryBuilderHelper.js +1079 -1028
  71. package/query/ScalarCriteriaNode.d.ts +3 -3
  72. package/query/ScalarCriteriaNode.js +53 -46
  73. package/query/enums.d.ts +14 -14
  74. package/query/enums.js +14 -14
  75. package/query/raw.d.ts +16 -6
  76. package/query/raw.js +10 -10
  77. package/schema/DatabaseSchema.d.ts +73 -50
  78. package/schema/DatabaseSchema.js +331 -307
  79. package/schema/DatabaseTable.d.ts +96 -73
  80. package/schema/DatabaseTable.js +1012 -927
  81. package/schema/SchemaComparator.d.ts +70 -66
  82. package/schema/SchemaComparator.js +766 -740
  83. package/schema/SchemaHelper.d.ts +109 -95
  84. package/schema/SchemaHelper.js +675 -659
  85. package/schema/SqlSchemaGenerator.d.ts +78 -58
  86. package/schema/SqlSchemaGenerator.js +535 -501
  87. package/typings.d.ts +380 -266
@@ -1,937 +1,1022 @@
1
- import { DecimalType, EntitySchema, RawQueryFragment, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
1
+ import {
2
+ DecimalType,
3
+ EntitySchema,
4
+ RawQueryFragment,
5
+ ReferenceKind,
6
+ t,
7
+ Type,
8
+ UnknownType,
9
+ Utils,
10
+ } from '@mikro-orm/core';
2
11
  /**
3
12
  * @internal
4
13
  */
5
14
  export class DatabaseTable {
6
- name;
7
- schema;
8
- #columns = {};
9
- #indexes = [];
10
- #checks = [];
11
- #foreignKeys = {};
12
- #platform;
13
- nativeEnums = {}; // for postgres
14
- comment;
15
- constructor(platform, name, schema) {
16
- this.name = name;
17
- this.schema = schema;
18
- this.#platform = platform;
19
- }
20
- getQuotedName() {
21
- return this.#platform.quoteIdentifier(this.getShortestName());
22
- }
23
- getColumns() {
24
- return Object.values(this.#columns);
25
- }
26
- getColumn(name) {
27
- return this.#columns[name];
28
- }
29
- removeColumn(name) {
30
- delete this.#columns[name];
31
- }
32
- getIndexes() {
33
- return Utils.removeDuplicates(this.#indexes);
34
- }
35
- getChecks() {
36
- return this.#checks;
37
- }
38
- /** @internal */
39
- setIndexes(indexes) {
40
- this.#indexes = indexes;
41
- }
42
- /** @internal */
43
- setChecks(checks) {
44
- this.#checks = checks;
45
- }
46
- /** @internal */
47
- setForeignKeys(fks) {
48
- this.#foreignKeys = fks;
49
- }
50
- init(cols, indexes = [], checks = [], pks, fks = {}, enums = {}) {
51
- this.#indexes = indexes;
52
- this.#checks = checks;
53
- this.#foreignKeys = fks;
54
- this.#columns = cols.reduce((o, v) => {
55
- const index = indexes.filter(i => i.columnNames[0] === v.name);
56
- v.primary = v.primary || pks.includes(v.name);
57
- v.unique = index.some(i => i.unique && !i.primary);
58
- const type = v.name in enums ? 'enum' : v.type;
59
- v.mappedType = this.#platform.getMappedType(type);
60
- v.default = v.default?.toString().startsWith('nextval(') ? null : v.default;
61
- v.enumItems ??= enums[v.name] || [];
62
- o[v.name] = v;
63
- return o;
64
- }, {});
65
- }
66
- addColumn(column) {
67
- this.#columns[column.name] = column;
68
- }
69
- addColumnFromProperty(prop, meta, config) {
70
- prop.fieldNames?.forEach((field, idx) => {
71
- const type = prop.enum ? 'enum' : prop.columnTypes[idx];
72
- const mappedType = this.#platform.getMappedType(type);
73
- if (mappedType instanceof DecimalType) {
74
- const match = /\w+\((\d+), ?(\d+)\)/.exec(prop.columnTypes[idx]);
75
- /* v8 ignore next */
76
- if (match) {
77
- prop.precision ??= +match[1];
78
- prop.scale ??= +match[2];
79
- prop.length = undefined;
80
- }
81
- }
82
- if (prop.length == null && prop.columnTypes[idx]) {
83
- prop.length = this.#platform.getSchemaHelper().inferLengthFromColumnType(prop.columnTypes[idx]);
84
- if (typeof mappedType.getDefaultLength !== 'undefined') {
85
- prop.length ??= mappedType.getDefaultLength(this.#platform);
86
- }
87
- }
88
- const primary = !meta.compositePK && prop.fieldNames.length === 1 && !!prop.primary;
89
- this.#columns[field] = {
90
- name: prop.fieldNames[idx],
91
- type: prop.columnTypes[idx],
92
- generated: prop.generated instanceof RawQueryFragment
93
- ? this.#platform.formatQuery(prop.generated.sql, prop.generated.params)
94
- : prop.generated,
95
- mappedType,
96
- unsigned: prop.unsigned && this.#platform.isNumericColumn(mappedType),
97
- autoincrement: prop.autoincrement ??
98
- (primary && prop.kind === ReferenceKind.SCALAR && this.#platform.isNumericColumn(mappedType)),
99
- primary,
100
- nullable: this.#columns[field]?.nullable ?? !!prop.nullable,
101
- nativeEnumName: prop.nativeEnumName,
102
- length: prop.length,
103
- precision: prop.precision,
104
- scale: prop.scale,
105
- default: prop.defaultRaw,
106
- enumItems: prop.nativeEnumName || prop.items?.every(i => typeof i === 'string') ? prop.items : undefined,
107
- comment: prop.comment,
108
- extra: prop.extra,
109
- ignoreSchemaChanges: prop.ignoreSchemaChanges,
110
- };
111
- this.#columns[field].unsigned ??= this.#columns[field].autoincrement;
112
- if (this.nativeEnums[type]) {
113
- this.#columns[field].enumItems ??= this.nativeEnums[type].items;
114
- }
115
- const defaultValue = this.#platform.getSchemaHelper().normalizeDefaultValue(prop.defaultRaw, prop.length);
116
- this.#columns[field].default = defaultValue;
117
- });
118
- if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.polymorphic) {
119
- const constraintName = this.getIndexName(prop.foreignKeyName ?? true, prop.fieldNames, 'foreign');
120
- let schema = prop.targetMeta.root.schema === '*'
121
- ? this.schema
122
- : (prop.targetMeta.root.schema ?? config.get('schema', this.#platform.getDefaultSchemaName()));
123
- if (prop.referencedTableName.includes('.')) {
124
- schema = undefined;
125
- }
126
- // For cross-schema FKs on MySQL/MariaDB (where schema = database), when the referenced
127
- // table has no explicit schema but the current table does, qualify with dbName so the
128
- // FK can resolve the referenced table in the correct database
129
- if (!schema && this.schema && !this.#platform.getDefaultSchemaName()) {
130
- schema = config.get('dbName');
131
- }
132
- if (prop.createForeignKeyConstraint) {
133
- this.#foreignKeys[constraintName] = {
134
- constraintName,
135
- columnNames: prop.fieldNames,
136
- localTableName: this.getShortestName(false),
137
- referencedColumnNames: prop.referencedColumnNames,
138
- referencedTableName: schema ? `${schema}.${prop.referencedTableName}` : prop.referencedTableName,
139
- };
140
- const schemaConfig = config.get('schemaGenerator');
141
- this.#foreignKeys[constraintName].deleteRule = prop.deleteRule ?? schemaConfig.defaultDeleteRule;
142
- this.#foreignKeys[constraintName].updateRule = prop.updateRule ?? schemaConfig.defaultUpdateRule;
143
- if (prop.deferMode) {
144
- this.#foreignKeys[constraintName].deferMode = prop.deferMode;
145
- }
146
- }
147
- }
148
- if (prop.index) {
149
- this.#indexes.push({
150
- columnNames: prop.fieldNames,
151
- composite: prop.fieldNames.length > 1,
152
- keyName: this.getIndexName(prop.index, prop.fieldNames, 'index'),
153
- constraint: false,
154
- primary: false,
155
- unique: false,
156
- });
157
- }
158
- if (prop.unique && !(prop.primary && !meta.compositePK)) {
159
- this.#indexes.push({
160
- columnNames: prop.fieldNames,
161
- composite: prop.fieldNames.length > 1,
162
- keyName: this.getIndexName(prop.unique, prop.fieldNames, 'unique'),
163
- constraint: !prop.fieldNames.some((d) => d.includes('.')),
164
- primary: false,
165
- unique: true,
166
- deferMode: prop.deferMode,
167
- });
168
- }
169
- }
170
- getIndexName(value, columnNames, type) {
171
- if (typeof value === 'string') {
172
- return value;
173
- }
174
- return this.#platform.getIndexName(this.name, columnNames, type);
175
- }
176
- getEntityDeclaration(namingStrategy, schemaHelper, scalarPropertiesForRelations) {
177
- const { fksOnColumnProps, fksOnStandaloneProps, columnFks, fkIndexes, nullableForeignKeys, skippedColumnNames } = this.foreignKeysToProps(namingStrategy, scalarPropertiesForRelations);
178
- const name = namingStrategy.getEntityName(this.name, this.schema);
179
- const schema = new EntitySchema({ name, collection: this.name, schema: this.schema, comment: this.comment });
180
- const compositeFkIndexes = {};
181
- const compositeFkUniques = {};
182
- const potentiallyUnmappedIndexes = this.#indexes.filter(index => !index.primary && // Skip primary index. Whether it's in use by scalar column or FK, it's already mapped.
183
- // Non-trivial non-composite indexes will be declared at the entity's metadata, though later outputted in the property
184
- (index.columnNames.length > 1 || // All composite indexes are to be mapped to entity decorators or FK props.
185
- skippedColumnNames.includes(index.columnNames[0]) || // Non-composite indexes for skipped columns are to be mapped as entity decorators.
186
- index.deferMode ||
187
- index.expression ||
188
- !(index.columnNames[0] in columnFks)) && // Trivial non-composite indexes for scalar props are to be mapped to the column.
189
- // ignore indexes that don't have all column names (this can happen in sqlite where there is no way to infer this for expressions)
190
- !(index.columnNames.some(col => !col) && !index.expression));
191
- // Helper to map column name to property name
192
- const columnToPropertyName = (colName) => this.getPropertyName(namingStrategy, colName);
193
- for (const index of potentiallyUnmappedIndexes) {
194
- // Build the index/unique options object with advanced options
195
- const ret = {
196
- name: index.keyName,
197
- deferMode: index.deferMode,
198
- expression: index.expression,
199
- // Advanced index options - convert column names to property names
200
- columns: index.columns?.map(col => ({
201
- ...col,
202
- name: columnToPropertyName(col.name),
203
- })),
204
- include: index.include?.map(colName => columnToPropertyName(colName)),
205
- fillFactor: index.fillFactor,
206
- disabled: index.disabled,
207
- };
208
- // Index-only options (not valid for Unique)
209
- if (!index.unique) {
210
- if (index.type) {
211
- // Convert index type - IndexDef.type can be string or object, IndexOptions.type is just string
212
- ret.type = typeof index.type === 'string' ? index.type : index.type.indexType;
213
- }
214
- if (index.invisible) {
215
- ret.invisible = index.invisible;
216
- }
217
- if (index.clustered) {
218
- ret.clustered = index.clustered;
219
- }
220
- }
221
- // An index is trivial if it has no special options that require entity-level declaration
222
- const hasAdvancedOptions = index.columns?.length ||
223
- index.include?.length ||
224
- index.fillFactor ||
225
- index.type ||
226
- index.invisible ||
227
- index.disabled ||
228
- index.clustered;
229
- const isTrivial = !index.deferMode && !index.expression && !hasAdvancedOptions;
230
- if (isTrivial) {
231
- // Index is for FK. Map to the FK prop and move on.
232
- const fkForIndex = fkIndexes.get(index);
233
- if (fkForIndex && !fkForIndex.fk.columnNames.some(col => !index.columnNames.includes(col))) {
234
- ret.properties = [this.getPropertyName(namingStrategy, fkForIndex.baseName, fkForIndex.fk)];
235
- const map = index.unique ? compositeFkUniques : compositeFkIndexes;
236
- if (typeof map[ret.properties[0]] === 'undefined') {
237
- map[ret.properties[0]] = index;
238
- continue;
239
- }
240
- }
241
- }
242
- const properties = ret.properties ??
243
- this.getIndexProperties(index, columnFks, fksOnColumnProps, fksOnStandaloneProps, namingStrategy);
244
- // If there is a column that cannot be unambiguously mapped to a prop, render an expression.
245
- if (typeof properties === 'undefined') {
246
- ret.expression ??= schemaHelper.getCreateIndexSQL(this.name, index);
247
- }
248
- else {
249
- ret.properties ??= properties;
250
- // If the index is for one property that is not a FK prop, map to the column prop and move on.
251
- if (properties.length === 1 && isTrivial && !fksOnStandaloneProps.has(properties[0])) {
252
- const map = index.unique ? compositeFkUniques : compositeFkIndexes;
253
- // Only map one trivial index. If the same column is indexed many times over, output
254
- if (typeof map[properties[0]] === 'undefined') {
255
- map[properties[0]] = index;
256
- continue;
257
- }
258
- }
259
- }
260
- // Composite indexes that aren't exclusively mapped to FK props get an entity decorator.
261
- if (index.unique) {
262
- schema.addUnique(ret);
263
- continue;
264
- }
265
- schema.addIndex(ret);
266
- }
267
- const addedStandaloneFkPropsBasedOnColumn = new Set();
268
- const nonSkippedColumns = this.getColumns().filter(column => !skippedColumnNames.includes(column.name));
269
- for (const column of nonSkippedColumns) {
270
- const columnName = column.name;
271
- const standaloneFkPropBasedOnColumn = fksOnStandaloneProps.get(columnName);
272
- if (standaloneFkPropBasedOnColumn && !fksOnColumnProps.get(columnName)) {
273
- addedStandaloneFkPropsBasedOnColumn.add(columnName);
274
- const { fkIndex, currentFk } = standaloneFkPropBasedOnColumn;
275
- const prop = this.getForeignKeyDeclaration(currentFk, namingStrategy, schemaHelper, fkIndex, nullableForeignKeys.has(currentFk), columnName, fksOnColumnProps);
276
- schema.addProperty(prop.name, prop.type, prop);
277
- }
278
- const prop = this.getPropertyDeclaration(column, namingStrategy, schemaHelper, compositeFkIndexes, compositeFkUniques, columnFks, fksOnColumnProps.get(columnName));
279
- schema.addProperty(prop.name, prop.type, prop);
280
- }
281
- for (const [propBaseName, { fkIndex, currentFk }] of fksOnStandaloneProps.entries()) {
282
- if (addedStandaloneFkPropsBasedOnColumn.has(propBaseName)) {
283
- continue;
284
- }
285
- const prop = this.getForeignKeyDeclaration(currentFk, namingStrategy, schemaHelper, fkIndex, nullableForeignKeys.has(currentFk), propBaseName, fksOnColumnProps);
286
- schema.addProperty(prop.name, prop.type, prop);
287
- }
288
- const meta = schema.init().meta;
289
- const oneToOneCandidateProperties = meta.relations.filter(prop => prop.primary && prop.kind === ReferenceKind.MANY_TO_ONE);
290
- if (oneToOneCandidateProperties.length === 1 &&
291
- oneToOneCandidateProperties[0].fieldNames.length ===
292
- new Set(meta.getPrimaryProps().flatMap(prop => prop.fieldNames)).size) {
293
- oneToOneCandidateProperties[0].kind = ReferenceKind.ONE_TO_ONE;
294
- }
295
- return meta;
296
- }
297
- foreignKeysToProps(namingStrategy, scalarPropertiesForRelations) {
298
- const fks = Object.values(this.getForeignKeys());
299
- const fksOnColumnProps = new Map();
300
- const fksOnStandaloneProps = new Map();
301
- const columnFks = {};
302
- const fkIndexes = new Map();
303
- const nullableForeignKeys = new Set();
304
- const standaloneFksBasedOnColumnNames = new Map();
305
- for (const currentFk of fks) {
306
- const fkIndex = this.findFkIndex(currentFk);
307
- if (currentFk.columnNames.length === 1 &&
308
- !fks.some(fk => fk !== currentFk && fk.columnNames.length === 1 && currentFk.columnNames[0] === fk.columnNames[0])) {
309
- // Non-composite FK is the only possible one for a column. Render the column with it.
310
- const columnName = currentFk.columnNames[0];
311
- columnFks[columnName] ??= [];
312
- columnFks[columnName].push(currentFk);
313
- if (this.getColumn(columnName)?.nullable) {
314
- nullableForeignKeys.add(currentFk);
315
- }
316
- if (scalarPropertiesForRelations === 'always') {
317
- const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
318
- standaloneFksBasedOnColumnNames.set(baseName, currentFk);
319
- fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
320
- if (fkIndex) {
321
- fkIndexes.set(fkIndex, { fk: currentFk, baseName });
322
- }
323
- }
324
- else {
325
- fksOnColumnProps.set(columnName, currentFk);
326
- if (fkIndex) {
327
- fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
328
- }
329
- }
330
- continue;
331
- }
332
- const specificColumnNames = [];
333
- const nullableColumnsInFk = [];
334
- for (const columnName of currentFk.columnNames) {
335
- columnFks[columnName] ??= [];
336
- columnFks[columnName].push(currentFk);
337
- if (!fks.some(fk => fk !== currentFk && fk.columnNames.includes(columnName))) {
338
- specificColumnNames.push(columnName);
339
- }
340
- if (this.getColumn(columnName)?.nullable) {
341
- nullableColumnsInFk.push(columnName);
342
- }
343
- }
344
- if (nullableColumnsInFk.length > 0) {
345
- nullableForeignKeys.add(currentFk);
346
- }
347
- if (specificColumnNames.length === 1 &&
348
- (nullableColumnsInFk.length === currentFk.columnNames.length ||
349
- nullableColumnsInFk.length === 0 ||
350
- (nullableColumnsInFk.length === 1 && nullableColumnsInFk[0] === specificColumnNames[0]))) {
351
- // Composite FK has exactly one column which is not used in any other FK.
352
- // The FK also doesn't have a mix of nullable and non-nullable columns,
353
- // or its only nullable column is this very one.
354
- // It is safe to just render this FK attached to the specific column.
355
- const columnName = specificColumnNames[0];
356
- if (scalarPropertiesForRelations === 'always') {
357
- const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
358
- standaloneFksBasedOnColumnNames.set(baseName, currentFk);
359
- fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
360
- if (fkIndex) {
361
- fkIndexes.set(fkIndex, { fk: currentFk, baseName });
362
- }
363
- }
364
- else {
365
- fksOnColumnProps.set(columnName, currentFk);
366
- if (fkIndex) {
367
- fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
368
- }
369
- }
370
- continue;
371
- }
372
- if (specificColumnNames.length === currentFk.columnNames.length) {
373
- // All columns involved with this FK are only covered by this one FK.
374
- if (nullableColumnsInFk.length <= 1) {
375
- // Also, this FK is either not nullable, or has only one nullable column.
376
- // It is safe to name the FK after the nullable column, or any non-nullable one (the first one is picked).
377
- const columnName = nullableColumnsInFk.at(0) ?? currentFk.columnNames[0];
378
- if (scalarPropertiesForRelations === 'always') {
379
- const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
380
- standaloneFksBasedOnColumnNames.set(baseName, currentFk);
381
- fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
382
- if (fkIndex) {
383
- fkIndexes.set(fkIndex, { fk: currentFk, baseName });
384
- }
385
- }
386
- else {
387
- fksOnColumnProps.set(columnName, currentFk);
388
- if (fkIndex) {
389
- fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
390
- }
391
- }
392
- continue;
393
- }
394
- // If the first nullable column's name with FK is different from the name without FK,
395
- // name a standalone prop after the column, but treat the column prop itself as not having FK.
396
- const columnName = nullableColumnsInFk[0];
397
- const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
398
- standaloneFksBasedOnColumnNames.set(baseName, currentFk);
399
- fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
400
- if (fkIndex) {
401
- fkIndexes.set(fkIndex, { fk: currentFk, baseName });
402
- }
403
- continue;
404
- }
405
- // FK is not unambiguously mappable to a column. Pick another name for a standalone FK prop.
406
- const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks);
15
+ name;
16
+ schema;
17
+ #columns = {};
18
+ #indexes = [];
19
+ #checks = [];
20
+ #foreignKeys = {};
21
+ #platform;
22
+ nativeEnums = {}; // for postgres
23
+ comment;
24
+ constructor(platform, name, schema) {
25
+ this.name = name;
26
+ this.schema = schema;
27
+ this.#platform = platform;
28
+ }
29
+ getQuotedName() {
30
+ return this.#platform.quoteIdentifier(this.getShortestName());
31
+ }
32
+ getColumns() {
33
+ return Object.values(this.#columns);
34
+ }
35
+ getColumn(name) {
36
+ return this.#columns[name];
37
+ }
38
+ removeColumn(name) {
39
+ delete this.#columns[name];
40
+ }
41
+ getIndexes() {
42
+ return Utils.removeDuplicates(this.#indexes);
43
+ }
44
+ getChecks() {
45
+ return this.#checks;
46
+ }
47
+ /** @internal */
48
+ setIndexes(indexes) {
49
+ this.#indexes = indexes;
50
+ }
51
+ /** @internal */
52
+ setChecks(checks) {
53
+ this.#checks = checks;
54
+ }
55
+ /** @internal */
56
+ setForeignKeys(fks) {
57
+ this.#foreignKeys = fks;
58
+ }
59
+ init(cols, indexes = [], checks = [], pks, fks = {}, enums = {}) {
60
+ this.#indexes = indexes;
61
+ this.#checks = checks;
62
+ this.#foreignKeys = fks;
63
+ this.#columns = cols.reduce((o, v) => {
64
+ const index = indexes.filter(i => i.columnNames[0] === v.name);
65
+ v.primary = v.primary || pks.includes(v.name);
66
+ v.unique = index.some(i => i.unique && !i.primary);
67
+ const type = v.name in enums ? 'enum' : v.type;
68
+ v.mappedType = this.#platform.getMappedType(type);
69
+ v.default = v.default?.toString().startsWith('nextval(') ? null : v.default;
70
+ v.enumItems ??= enums[v.name] || [];
71
+ o[v.name] = v;
72
+ return o;
73
+ }, {});
74
+ }
75
+ addColumn(column) {
76
+ this.#columns[column.name] = column;
77
+ }
78
+ addColumnFromProperty(prop, meta, config) {
79
+ prop.fieldNames?.forEach((field, idx) => {
80
+ const type = prop.enum ? 'enum' : prop.columnTypes[idx];
81
+ const mappedType = this.#platform.getMappedType(type);
82
+ if (mappedType instanceof DecimalType) {
83
+ const match = /\w+\((\d+), ?(\d+)\)/.exec(prop.columnTypes[idx]);
84
+ /* v8 ignore next */
85
+ if (match) {
86
+ prop.precision ??= +match[1];
87
+ prop.scale ??= +match[2];
88
+ prop.length = undefined;
89
+ }
90
+ }
91
+ if (prop.length == null && prop.columnTypes[idx]) {
92
+ prop.length = this.#platform.getSchemaHelper().inferLengthFromColumnType(prop.columnTypes[idx]);
93
+ if (typeof mappedType.getDefaultLength !== 'undefined') {
94
+ prop.length ??= mappedType.getDefaultLength(this.#platform);
95
+ }
96
+ }
97
+ const primary = !meta.compositePK && prop.fieldNames.length === 1 && !!prop.primary;
98
+ this.#columns[field] = {
99
+ name: prop.fieldNames[idx],
100
+ type: prop.columnTypes[idx],
101
+ generated:
102
+ prop.generated instanceof RawQueryFragment
103
+ ? this.#platform.formatQuery(prop.generated.sql, prop.generated.params)
104
+ : prop.generated,
105
+ mappedType,
106
+ unsigned: prop.unsigned && this.#platform.isNumericColumn(mappedType),
107
+ autoincrement:
108
+ prop.autoincrement ??
109
+ (primary && prop.kind === ReferenceKind.SCALAR && this.#platform.isNumericColumn(mappedType)),
110
+ primary,
111
+ nullable: this.#columns[field]?.nullable ?? !!prop.nullable,
112
+ nativeEnumName: prop.nativeEnumName,
113
+ length: prop.length,
114
+ precision: prop.precision,
115
+ scale: prop.scale,
116
+ default: prop.defaultRaw,
117
+ enumItems: prop.nativeEnumName || prop.items?.every(i => typeof i === 'string') ? prop.items : undefined,
118
+ comment: prop.comment,
119
+ extra: prop.extra,
120
+ ignoreSchemaChanges: prop.ignoreSchemaChanges,
121
+ };
122
+ this.#columns[field].unsigned ??= this.#columns[field].autoincrement;
123
+ if (this.nativeEnums[type]) {
124
+ this.#columns[field].enumItems ??= this.nativeEnums[type].items;
125
+ }
126
+ const defaultValue = this.#platform.getSchemaHelper().normalizeDefaultValue(prop.defaultRaw, prop.length);
127
+ this.#columns[field].default = defaultValue;
128
+ });
129
+ if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.polymorphic) {
130
+ const constraintName = this.getIndexName(prop.foreignKeyName ?? true, prop.fieldNames, 'foreign');
131
+ let schema =
132
+ prop.targetMeta.root.schema === '*'
133
+ ? this.schema
134
+ : (prop.targetMeta.root.schema ?? config.get('schema', this.#platform.getDefaultSchemaName()));
135
+ if (prop.referencedTableName.includes('.')) {
136
+ schema = undefined;
137
+ }
138
+ // For cross-schema FKs on MySQL/MariaDB (where schema = database), when the referenced
139
+ // table has no explicit schema but the current table does, qualify with dbName so the
140
+ // FK can resolve the referenced table in the correct database
141
+ if (!schema && this.schema && !this.#platform.getDefaultSchemaName()) {
142
+ schema = config.get('dbName');
143
+ }
144
+ if (prop.createForeignKeyConstraint) {
145
+ this.#foreignKeys[constraintName] = {
146
+ constraintName,
147
+ columnNames: prop.fieldNames,
148
+ localTableName: this.getShortestName(false),
149
+ referencedColumnNames: prop.referencedColumnNames,
150
+ referencedTableName: schema ? `${schema}.${prop.referencedTableName}` : prop.referencedTableName,
151
+ };
152
+ const schemaConfig = config.get('schemaGenerator');
153
+ this.#foreignKeys[constraintName].deleteRule = prop.deleteRule ?? schemaConfig.defaultDeleteRule;
154
+ this.#foreignKeys[constraintName].updateRule = prop.updateRule ?? schemaConfig.defaultUpdateRule;
155
+ if (prop.deferMode) {
156
+ this.#foreignKeys[constraintName].deferMode = prop.deferMode;
157
+ }
158
+ }
159
+ }
160
+ if (prop.index) {
161
+ this.#indexes.push({
162
+ columnNames: prop.fieldNames,
163
+ composite: prop.fieldNames.length > 1,
164
+ keyName: this.getIndexName(prop.index, prop.fieldNames, 'index'),
165
+ constraint: false,
166
+ primary: false,
167
+ unique: false,
168
+ });
169
+ }
170
+ if (prop.unique && !(prop.primary && !meta.compositePK)) {
171
+ this.#indexes.push({
172
+ columnNames: prop.fieldNames,
173
+ composite: prop.fieldNames.length > 1,
174
+ keyName: this.getIndexName(prop.unique, prop.fieldNames, 'unique'),
175
+ constraint: !prop.fieldNames.some(d => d.includes('.')),
176
+ primary: false,
177
+ unique: true,
178
+ deferMode: prop.deferMode,
179
+ });
180
+ }
181
+ }
182
+ getIndexName(value, columnNames, type) {
183
+ if (typeof value === 'string') {
184
+ return value;
185
+ }
186
+ return this.#platform.getIndexName(this.name, columnNames, type);
187
+ }
188
+ getEntityDeclaration(namingStrategy, schemaHelper, scalarPropertiesForRelations) {
189
+ const { fksOnColumnProps, fksOnStandaloneProps, columnFks, fkIndexes, nullableForeignKeys, skippedColumnNames } =
190
+ this.foreignKeysToProps(namingStrategy, scalarPropertiesForRelations);
191
+ const name = namingStrategy.getEntityName(this.name, this.schema);
192
+ const schema = new EntitySchema({ name, collection: this.name, schema: this.schema, comment: this.comment });
193
+ const compositeFkIndexes = {};
194
+ const compositeFkUniques = {};
195
+ const potentiallyUnmappedIndexes = this.#indexes.filter(
196
+ index =>
197
+ !index.primary && // Skip primary index. Whether it's in use by scalar column or FK, it's already mapped.
198
+ // Non-trivial non-composite indexes will be declared at the entity's metadata, though later outputted in the property
199
+ (index.columnNames.length > 1 || // All composite indexes are to be mapped to entity decorators or FK props.
200
+ skippedColumnNames.includes(index.columnNames[0]) || // Non-composite indexes for skipped columns are to be mapped as entity decorators.
201
+ index.deferMode ||
202
+ index.expression ||
203
+ !(index.columnNames[0] in columnFks)) && // Trivial non-composite indexes for scalar props are to be mapped to the column.
204
+ // ignore indexes that don't have all column names (this can happen in sqlite where there is no way to infer this for expressions)
205
+ !(index.columnNames.some(col => !col) && !index.expression),
206
+ );
207
+ // Helper to map column name to property name
208
+ const columnToPropertyName = colName => this.getPropertyName(namingStrategy, colName);
209
+ for (const index of potentiallyUnmappedIndexes) {
210
+ // Build the index/unique options object with advanced options
211
+ const ret = {
212
+ name: index.keyName,
213
+ deferMode: index.deferMode,
214
+ expression: index.expression,
215
+ // Advanced index options - convert column names to property names
216
+ columns: index.columns?.map(col => ({
217
+ ...col,
218
+ name: columnToPropertyName(col.name),
219
+ })),
220
+ include: index.include?.map(colName => columnToPropertyName(colName)),
221
+ fillFactor: index.fillFactor,
222
+ disabled: index.disabled,
223
+ };
224
+ // Index-only options (not valid for Unique)
225
+ if (!index.unique) {
226
+ if (index.type) {
227
+ // Convert index type - IndexDef.type can be string or object, IndexOptions.type is just string
228
+ ret.type = typeof index.type === 'string' ? index.type : index.type.indexType;
229
+ }
230
+ if (index.invisible) {
231
+ ret.invisible = index.invisible;
232
+ }
233
+ if (index.clustered) {
234
+ ret.clustered = index.clustered;
235
+ }
236
+ }
237
+ // An index is trivial if it has no special options that require entity-level declaration
238
+ const hasAdvancedOptions =
239
+ index.columns?.length ||
240
+ index.include?.length ||
241
+ index.fillFactor ||
242
+ index.type ||
243
+ index.invisible ||
244
+ index.disabled ||
245
+ index.clustered;
246
+ const isTrivial = !index.deferMode && !index.expression && !hasAdvancedOptions;
247
+ if (isTrivial) {
248
+ // Index is for FK. Map to the FK prop and move on.
249
+ const fkForIndex = fkIndexes.get(index);
250
+ if (fkForIndex && !fkForIndex.fk.columnNames.some(col => !index.columnNames.includes(col))) {
251
+ ret.properties = [this.getPropertyName(namingStrategy, fkForIndex.baseName, fkForIndex.fk)];
252
+ const map = index.unique ? compositeFkUniques : compositeFkIndexes;
253
+ if (typeof map[ret.properties[0]] === 'undefined') {
254
+ map[ret.properties[0]] = index;
255
+ continue;
256
+ }
257
+ }
258
+ }
259
+ const properties =
260
+ ret.properties ??
261
+ this.getIndexProperties(index, columnFks, fksOnColumnProps, fksOnStandaloneProps, namingStrategy);
262
+ // If there is a column that cannot be unambiguously mapped to a prop, render an expression.
263
+ if (typeof properties === 'undefined') {
264
+ ret.expression ??= schemaHelper.getCreateIndexSQL(this.name, index);
265
+ } else {
266
+ ret.properties ??= properties;
267
+ // If the index is for one property that is not a FK prop, map to the column prop and move on.
268
+ if (properties.length === 1 && isTrivial && !fksOnStandaloneProps.has(properties[0])) {
269
+ const map = index.unique ? compositeFkUniques : compositeFkIndexes;
270
+ // Only map one trivial index. If the same column is indexed many times over, output
271
+ if (typeof map[properties[0]] === 'undefined') {
272
+ map[properties[0]] = index;
273
+ continue;
274
+ }
275
+ }
276
+ }
277
+ // Composite indexes that aren't exclusively mapped to FK props get an entity decorator.
278
+ if (index.unique) {
279
+ schema.addUnique(ret);
280
+ continue;
281
+ }
282
+ schema.addIndex(ret);
283
+ }
284
+ const addedStandaloneFkPropsBasedOnColumn = new Set();
285
+ const nonSkippedColumns = this.getColumns().filter(column => !skippedColumnNames.includes(column.name));
286
+ for (const column of nonSkippedColumns) {
287
+ const columnName = column.name;
288
+ const standaloneFkPropBasedOnColumn = fksOnStandaloneProps.get(columnName);
289
+ if (standaloneFkPropBasedOnColumn && !fksOnColumnProps.get(columnName)) {
290
+ addedStandaloneFkPropsBasedOnColumn.add(columnName);
291
+ const { fkIndex, currentFk } = standaloneFkPropBasedOnColumn;
292
+ const prop = this.getForeignKeyDeclaration(
293
+ currentFk,
294
+ namingStrategy,
295
+ schemaHelper,
296
+ fkIndex,
297
+ nullableForeignKeys.has(currentFk),
298
+ columnName,
299
+ fksOnColumnProps,
300
+ );
301
+ schema.addProperty(prop.name, prop.type, prop);
302
+ }
303
+ const prop = this.getPropertyDeclaration(
304
+ column,
305
+ namingStrategy,
306
+ schemaHelper,
307
+ compositeFkIndexes,
308
+ compositeFkUniques,
309
+ columnFks,
310
+ fksOnColumnProps.get(columnName),
311
+ );
312
+ schema.addProperty(prop.name, prop.type, prop);
313
+ }
314
+ for (const [propBaseName, { fkIndex, currentFk }] of fksOnStandaloneProps.entries()) {
315
+ if (addedStandaloneFkPropsBasedOnColumn.has(propBaseName)) {
316
+ continue;
317
+ }
318
+ const prop = this.getForeignKeyDeclaration(
319
+ currentFk,
320
+ namingStrategy,
321
+ schemaHelper,
322
+ fkIndex,
323
+ nullableForeignKeys.has(currentFk),
324
+ propBaseName,
325
+ fksOnColumnProps,
326
+ );
327
+ schema.addProperty(prop.name, prop.type, prop);
328
+ }
329
+ const meta = schema.init().meta;
330
+ const oneToOneCandidateProperties = meta.relations.filter(
331
+ prop => prop.primary && prop.kind === ReferenceKind.MANY_TO_ONE,
332
+ );
333
+ if (
334
+ oneToOneCandidateProperties.length === 1 &&
335
+ oneToOneCandidateProperties[0].fieldNames.length ===
336
+ new Set(meta.getPrimaryProps().flatMap(prop => prop.fieldNames)).size
337
+ ) {
338
+ oneToOneCandidateProperties[0].kind = ReferenceKind.ONE_TO_ONE;
339
+ }
340
+ return meta;
341
+ }
342
+ foreignKeysToProps(namingStrategy, scalarPropertiesForRelations) {
343
+ const fks = Object.values(this.getForeignKeys());
344
+ const fksOnColumnProps = new Map();
345
+ const fksOnStandaloneProps = new Map();
346
+ const columnFks = {};
347
+ const fkIndexes = new Map();
348
+ const nullableForeignKeys = new Set();
349
+ const standaloneFksBasedOnColumnNames = new Map();
350
+ for (const currentFk of fks) {
351
+ const fkIndex = this.findFkIndex(currentFk);
352
+ if (
353
+ currentFk.columnNames.length === 1 &&
354
+ !fks.some(
355
+ fk => fk !== currentFk && fk.columnNames.length === 1 && currentFk.columnNames[0] === fk.columnNames[0],
356
+ )
357
+ ) {
358
+ // Non-composite FK is the only possible one for a column. Render the column with it.
359
+ const columnName = currentFk.columnNames[0];
360
+ columnFks[columnName] ??= [];
361
+ columnFks[columnName].push(currentFk);
362
+ if (this.getColumn(columnName)?.nullable) {
363
+ nullableForeignKeys.add(currentFk);
364
+ }
365
+ if (scalarPropertiesForRelations === 'always') {
366
+ const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
367
+ standaloneFksBasedOnColumnNames.set(baseName, currentFk);
368
+ fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
369
+ if (fkIndex) {
370
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName });
371
+ }
372
+ } else {
373
+ fksOnColumnProps.set(columnName, currentFk);
374
+ if (fkIndex) {
375
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
376
+ }
377
+ }
378
+ continue;
379
+ }
380
+ const specificColumnNames = [];
381
+ const nullableColumnsInFk = [];
382
+ for (const columnName of currentFk.columnNames) {
383
+ columnFks[columnName] ??= [];
384
+ columnFks[columnName].push(currentFk);
385
+ if (!fks.some(fk => fk !== currentFk && fk.columnNames.includes(columnName))) {
386
+ specificColumnNames.push(columnName);
387
+ }
388
+ if (this.getColumn(columnName)?.nullable) {
389
+ nullableColumnsInFk.push(columnName);
390
+ }
391
+ }
392
+ if (nullableColumnsInFk.length > 0) {
393
+ nullableForeignKeys.add(currentFk);
394
+ }
395
+ if (
396
+ specificColumnNames.length === 1 &&
397
+ (nullableColumnsInFk.length === currentFk.columnNames.length ||
398
+ nullableColumnsInFk.length === 0 ||
399
+ (nullableColumnsInFk.length === 1 && nullableColumnsInFk[0] === specificColumnNames[0]))
400
+ ) {
401
+ // Composite FK has exactly one column which is not used in any other FK.
402
+ // The FK also doesn't have a mix of nullable and non-nullable columns,
403
+ // or its only nullable column is this very one.
404
+ // It is safe to just render this FK attached to the specific column.
405
+ const columnName = specificColumnNames[0];
406
+ if (scalarPropertiesForRelations === 'always') {
407
+ const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
408
+ standaloneFksBasedOnColumnNames.set(baseName, currentFk);
409
+ fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
410
+ if (fkIndex) {
411
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName });
412
+ }
413
+ } else {
414
+ fksOnColumnProps.set(columnName, currentFk);
415
+ if (fkIndex) {
416
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
417
+ }
418
+ }
419
+ continue;
420
+ }
421
+ if (specificColumnNames.length === currentFk.columnNames.length) {
422
+ // All columns involved with this FK are only covered by this one FK.
423
+ if (nullableColumnsInFk.length <= 1) {
424
+ // Also, this FK is either not nullable, or has only one nullable column.
425
+ // It is safe to name the FK after the nullable column, or any non-nullable one (the first one is picked).
426
+ const columnName = nullableColumnsInFk.at(0) ?? currentFk.columnNames[0];
427
+ if (scalarPropertiesForRelations === 'always') {
428
+ const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
429
+ standaloneFksBasedOnColumnNames.set(baseName, currentFk);
407
430
  fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
408
431
  if (fkIndex) {
409
- fkIndexes.set(fkIndex, { fk: currentFk, baseName });
410
- }
411
- }
412
- const columnsInFks = Object.keys(columnFks);
413
- const skippingHandlers = {
414
- // Never generate scalar props for composite keys,
415
- // i.e. always skip columns if they are covered by foreign keys.
416
- never: (column) => columnsInFks.includes(column.name) && !fksOnColumnProps.has(column.name),
417
- // Always generate scalar props for composite keys,
418
- // i.e. do not skip columns, even if they are covered by foreign keys.
419
- always: (column) => false,
420
- // Smart scalar props generation.
421
- // Skips columns if they are covered by foreign keys.
422
- // But also does not skip if the column is not nullable, and yet all involved FKs are nullable,
423
- // or if one or more FKs involved has multiple nullable columns.
424
- smart: (column) => {
425
- return (columnsInFks.includes(column.name) &&
426
- !fksOnColumnProps.has(column.name) &&
427
- (column.nullable
428
- ? columnFks[column.name].some(fk => !fk.columnNames.some(fkColumnName => fkColumnName !== column.name && this.getColumn(fkColumnName)?.nullable))
429
- : columnFks[column.name].some(fk => !nullableForeignKeys.has(fk))));
430
- },
431
- };
432
- const skippedColumnNames = this.getColumns()
433
- .filter(skippingHandlers[scalarPropertiesForRelations])
434
- .map(column => column.name);
435
- // Check standalone FKs named after columns for potential conflicts among themselves.
436
- // This typically happens when two standalone FKs named after a column resolve to the same prop name
437
- // because the respective columns include the referenced table in the name.
438
- // Depending on naming strategy and actual names, it may also originate from other scenarios.
439
- // We do our best to de-duplicate them here.
440
- const safePropNames = new Set();
441
- const unsafePropNames = new Map();
442
- for (const [unsafeBaseName, currentFk] of standaloneFksBasedOnColumnNames) {
443
- const propName = this.getPropertyName(namingStrategy, unsafeBaseName, currentFk);
444
- if (safePropNames.has(propName)) {
445
- if (!unsafePropNames.has(propName)) {
446
- unsafePropNames.set(propName, []);
447
- }
448
- unsafePropNames.get(propName).push({ unsafeBaseName, currentFk });
449
- continue;
450
- }
451
- safePropNames.add(propName);
452
- }
453
- for (const [unsafePropName, affectedBaseNames] of unsafePropNames) {
454
- safePropNames.delete(unsafePropName);
455
- for (const { unsafeBaseName, currentFk } of affectedBaseNames) {
456
- const newBaseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks);
457
- fksOnStandaloneProps.delete(unsafeBaseName);
458
- let fkIndex;
459
- for (const [indexDef, fkIndexDesc] of fkIndexes) {
460
- if (fkIndexDesc.fk !== currentFk) {
461
- continue;
462
- }
463
- fkIndexDesc.baseName = newBaseName;
464
- fkIndex = indexDef;
465
- break;
466
- }
467
- fksOnStandaloneProps.set(newBaseName, { fkIndex, currentFk });
468
- }
469
- }
470
- return { fksOnColumnProps, fksOnStandaloneProps, columnFks, fkIndexes, nullableForeignKeys, skippedColumnNames };
471
- }
472
- findFkIndex(currentFk) {
473
- const fkColumnsLength = currentFk.columnNames.length;
474
- const possibleIndexes = this.#indexes.filter(index => {
475
- return (index.columnNames.length === fkColumnsLength &&
476
- !currentFk.columnNames.some((columnName, i) => index.columnNames[i] !== columnName));
477
- });
478
- possibleIndexes.sort((a, b) => {
479
- if (a.primary !== b.primary) {
480
- return a.primary ? -1 : 1;
481
- }
482
- if (a.unique !== b.unique) {
483
- return a.unique ? -1 : 1;
484
- }
485
- return a.keyName.localeCompare(b.keyName);
486
- });
487
- return possibleIndexes.at(0);
488
- }
489
- getIndexProperties(index, columnFks, fksOnColumnProps, fksOnStandaloneProps, namingStrategy) {
490
- const propBaseNames = new Set();
491
- const columnNames = index.columnNames;
492
- const l = columnNames.length;
493
- if (columnNames.some(col => !col)) {
494
- return;
495
- }
496
- for (let i = 0; i < l; ++i) {
497
- const columnName = columnNames[i];
498
- // The column is not involved with FKs.
499
- if (!(columnName in columnFks)) {
500
- // If there is no such column, the "name" is actually an expression.
501
- if (!this.hasColumn(columnName)) {
502
- return;
503
- }
504
- // It has a prop named after it.
505
- // Add it and move on.
506
- propBaseNames.add(columnName);
507
- continue;
508
- }
509
- // If the prop named after the column has a FK and the FK's columns are a subset of this index,
510
- // include this prop and move on.
511
- const columnPropFk = fksOnColumnProps.get(columnName);
512
- if (columnPropFk && !columnPropFk.columnNames.some(fkColumnName => !columnNames.includes(fkColumnName))) {
513
- propBaseNames.add(columnName);
514
- continue;
515
- }
516
- // If there is at least one standalone FK featuring this column,
517
- // and all of its columns are a subset of this index,
518
- // include that FK, and consider mapping of this column to a prop a success.
519
- let propAdded = false;
520
- for (const [propName, { currentFk: fk }] of fksOnStandaloneProps) {
521
- if (!columnFks[columnName].includes(fk)) {
522
- continue;
523
- }
524
- if (!fk.columnNames.some(fkColumnName => !columnNames.includes(fkColumnName))) {
525
- propBaseNames.add(propName);
526
- propAdded = true;
527
- }
528
- }
529
- if (propAdded) {
530
- continue;
531
- }
532
- // If we have reached this point, it means the column is not mappable to a prop name.
533
- // Break the whole prop creation.
534
- return;
535
- }
536
- return Array.from(propBaseNames).map(baseName => this.getPropertyName(namingStrategy, baseName, fksOnColumnProps.get(baseName)));
537
- }
538
- getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName) {
539
- if (columnName &&
540
- this.getPropertyName(namingStrategy, columnName, currentFk) !== this.getPropertyName(namingStrategy, columnName)) {
541
- // The eligible scalar column name is different from the name of the FK prop of the same column.
542
- // Both can be safely rendered.
543
- // Use the column name as a base for the FK prop.
544
- return columnName;
545
- }
546
- // Strip schema prefix from referenced table name (e.g., "public.fr_usuario" -> "fr_usuario")
547
- const getTableName = (fullName) => {
548
- const parts = fullName.split('.');
549
- return parts[parts.length - 1];
550
- };
551
- const referencedTableName = getTableName(currentFk.referencedTableName);
552
- // Check for conflicts using stripped table names (handles cross-schema FKs to same-named tables)
553
- const hasConflictingFk = fks.some(fk => fk !== currentFk && getTableName(fk.referencedTableName) === referencedTableName);
554
- if (!hasConflictingFk && !this.getColumn(referencedTableName)) {
555
- // FK is the only one in this table that references a table with this name.
556
- // The name of the referenced table is not shared with a column in this table,
557
- // so it is safe to output prop name based on the referenced entity.
558
- return referencedTableName;
559
- }
560
- // Any ambiguous FK is rendered with a name based on the FK constraint name
561
- let finalPropBaseName = currentFk.constraintName;
562
- while (this.getColumn(finalPropBaseName)) {
563
- // In the unlikely event that the FK constraint name is shared by a column name, generate a name by
564
- // continuously prefixing with "fk_", until a non-existent column is hit.
565
- // The worst case scenario is a very long name with several repeated "fk_"
566
- // that is not really a valid DB identifier but a valid JS variable name.
567
- finalPropBaseName = `fk_${finalPropBaseName}`;
568
- }
569
- return finalPropBaseName;
570
- }
571
- /**
572
- * The shortest name is stripped of the default namespace. All other namespaced elements are returned as full-qualified names.
573
- */
574
- getShortestName(skipDefaultSchema = true) {
575
- const defaultSchema = this.#platform.getDefaultSchemaName();
576
- if (!this.schema ||
577
- this.name.startsWith(defaultSchema + '.') ||
578
- (this.schema === defaultSchema && skipDefaultSchema)) {
579
- return this.name;
580
- }
581
- return `${this.schema}.${this.name}`;
582
- }
583
- getForeignKeys() {
584
- return this.#foreignKeys;
585
- }
586
- hasColumn(columnName) {
587
- return columnName in this.#columns;
588
- }
589
- getIndex(indexName) {
590
- return this.#indexes.find(i => i.keyName === indexName);
591
- }
592
- hasIndex(indexName) {
593
- return !!this.getIndex(indexName);
594
- }
595
- getCheck(checkName) {
596
- return this.#checks.find(i => i.name === checkName);
597
- }
598
- hasCheck(checkName) {
599
- return !!this.getCheck(checkName);
600
- }
601
- getPrimaryKey() {
602
- return this.#indexes.find(i => i.primary);
603
- }
604
- hasPrimaryKey() {
605
- return !!this.getPrimaryKey();
606
- }
607
- getForeignKeyDeclaration(fk, namingStrategy, schemaHelper, fkIndex, nullable, propNameBase, fksOnColumnProps) {
608
- const prop = this.getPropertyName(namingStrategy, propNameBase, fk);
609
- const kind = fkIndex?.unique && !fkIndex.primary ? this.getReferenceKind(fk, fkIndex) : this.getReferenceKind(fk);
610
- const runtimeType = this.getPropertyTypeForForeignKey(namingStrategy, fk);
611
- const fkOptions = {};
612
- fkOptions.fieldNames = fk.columnNames;
613
- fkOptions.referencedTableName = fk.referencedTableName;
614
- fkOptions.referencedColumnNames = fk.referencedColumnNames;
615
- fkOptions.updateRule = fk.updateRule?.toLowerCase();
616
- fkOptions.deleteRule = fk.deleteRule?.toLowerCase();
617
- fkOptions.deferMode = fk.deferMode;
618
- fkOptions.columnTypes = fk.columnNames.map(c => this.getColumn(c).type);
619
- const columnOptions = {};
620
- if (fk.columnNames.length === 1) {
621
- const column = this.getColumn(fk.columnNames[0]);
622
- const defaultRaw = this.getPropertyDefaultValue(schemaHelper, column, column.type, true);
623
- const defaultTs = this.getPropertyDefaultValue(schemaHelper, column, column.type);
624
- columnOptions.default = defaultRaw !== defaultTs || defaultRaw === '' ? defaultTs : undefined;
625
- columnOptions.defaultRaw = column.nullable && defaultRaw === 'null' ? undefined : defaultRaw;
626
- columnOptions.optional = typeof column.generated !== 'undefined' || defaultRaw !== 'null';
627
- columnOptions.generated = column.generated;
628
- columnOptions.nullable = column.nullable;
629
- columnOptions.primary = column.primary;
630
- columnOptions.length = column.length;
631
- columnOptions.precision = column.precision;
632
- columnOptions.scale = column.scale;
633
- columnOptions.extra = column.extra;
634
- columnOptions.comment = column.comment;
635
- columnOptions.enum = !!column.enumItems?.length;
636
- columnOptions.items = column.enumItems;
637
- }
638
- return {
639
- name: prop,
640
- type: runtimeType,
641
- runtimeType,
642
- kind,
643
- ...columnOptions,
644
- nullable,
645
- primary: fkIndex?.primary || !fk.columnNames.some(columnName => !this.getPrimaryKey()?.columnNames.includes(columnName)),
646
- index: !fkIndex?.unique ? fkIndex?.keyName : undefined,
647
- unique: fkIndex?.unique && !fkIndex.primary ? fkIndex.keyName : undefined,
648
- ...fkOptions,
649
- };
650
- }
651
- getPropertyDeclaration(column, namingStrategy, schemaHelper, compositeFkIndexes, compositeFkUniques, columnFks, fk) {
652
- const prop = this.getPropertyName(namingStrategy, column.name, fk);
653
- const persist = !(column.name in columnFks && typeof fk === 'undefined');
654
- const index = compositeFkIndexes[prop] ||
655
- this.#indexes.find(idx => idx.columnNames[0] === column.name && !idx.composite && !idx.unique && !idx.primary);
656
- const unique = compositeFkUniques[prop] ||
657
- this.#indexes.find(idx => idx.columnNames[0] === column.name && !idx.composite && idx.unique && !idx.primary);
658
- const kind = this.getReferenceKind(fk, unique);
659
- const runtimeType = this.getPropertyTypeForColumn(namingStrategy, column, fk);
660
- const type = fk
661
- ? runtimeType
662
- : (Utils.keys(t).find(k => {
663
- const typeInCoreMap = this.#platform.getMappedType(k);
664
- return ((typeInCoreMap !== Type.getType(UnknownType) || k === 'unknown') && typeInCoreMap === column.mappedType);
665
- }) ?? runtimeType);
666
- const ignoreSchemaChanges = type === 'unknown' && column.length ? (column.extra ? ['type', 'extra'] : ['type']) : undefined;
667
- const defaultRaw = this.getPropertyDefaultValue(schemaHelper, column, runtimeType, true);
668
- const defaultParsed = this.getPropertyDefaultValue(schemaHelper, column, runtimeType);
669
- const defaultTs = defaultRaw !== defaultParsed || defaultParsed === '' ? defaultParsed : undefined;
670
- const fkOptions = {};
671
- if (fk) {
672
- fkOptions.fieldNames = fk.columnNames;
673
- fkOptions.referencedTableName = fk.referencedTableName;
674
- fkOptions.referencedColumnNames = fk.referencedColumnNames;
675
- fkOptions.updateRule = fk.updateRule?.toLowerCase();
676
- fkOptions.deleteRule = fk.deleteRule?.toLowerCase();
677
- fkOptions.deferMode = fk.deferMode;
678
- fkOptions.columnTypes = fk.columnNames.map(col => this.getColumn(col).type);
679
- }
680
- const ret = {
681
- name: prop,
682
- type,
683
- runtimeType,
684
- kind,
685
- ignoreSchemaChanges,
686
- generated: column.generated,
687
- optional: defaultRaw !== 'null' || defaultTs != null || typeof column.generated !== 'undefined',
688
- columnType: column.type,
689
- default: defaultTs,
690
- defaultRaw: column.nullable && defaultRaw === 'null' ? undefined : defaultRaw,
691
- nullable: column.nullable,
692
- primary: column.primary && persist,
693
- autoincrement: column.autoincrement,
694
- fieldName: column.name,
695
- unsigned: column.unsigned,
696
- length: column.length,
697
- precision: column.precision,
698
- scale: column.scale,
699
- extra: column.extra,
700
- comment: column.comment,
701
- index: index ? index.keyName : undefined,
702
- unique: unique ? unique.keyName : undefined,
703
- enum: !!column.enumItems?.length,
704
- items: column.enumItems,
705
- persist,
706
- ...fkOptions,
707
- };
708
- const nativeEnumName = Object.keys(this.nativeEnums).find(name => name === column.type);
709
- if (nativeEnumName) {
710
- ret.nativeEnumName = nativeEnumName;
711
- }
712
- return ret;
713
- }
714
- getReferenceKind(fk, unique) {
715
- if (fk && unique) {
716
- return ReferenceKind.ONE_TO_ONE;
717
- }
718
- if (fk) {
719
- return ReferenceKind.MANY_TO_ONE;
720
- }
721
- return ReferenceKind.SCALAR;
722
- }
723
- getPropertyName(namingStrategy, baseName, fk) {
724
- let field = baseName;
725
- if (fk) {
726
- const idx = fk.columnNames.indexOf(baseName);
727
- let replacedFieldName = field.replace(new RegExp(`_${fk.referencedColumnNames[idx]}$`), '');
728
- if (replacedFieldName === field) {
729
- replacedFieldName = field.replace(new RegExp(`_${namingStrategy.referenceColumnName()}$`), '');
432
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName });
730
433
  }
731
- field = replacedFieldName;
732
- }
733
- if (field.startsWith('_')) {
734
- return field;
735
- }
736
- return namingStrategy.columnNameToProperty(field);
737
- }
738
- getPropertyTypeForForeignKey(namingStrategy, fk) {
739
- const parts = fk.referencedTableName.split('.', 2);
740
- return namingStrategy.getEntityName(...parts.reverse());
741
- }
742
- getPropertyTypeForColumn(namingStrategy, column, fk) {
743
- if (fk) {
744
- return this.getPropertyTypeForForeignKey(namingStrategy, fk);
745
- }
746
- const enumMode = this.#platform.getConfig().get('entityGenerator').enumMode;
747
- // If this column is using an enum.
748
- if (column.enumItems?.length) {
749
- const name = column.nativeEnumName ?? column.name;
750
- const tableName = column.nativeEnumName ? undefined : this.name;
751
- if (enumMode === 'ts-enum') {
752
- // We will create a new enum name for this type and set it as the property type as well.
753
- return namingStrategy.getEnumClassName(name, tableName, this.schema);
754
- }
755
- // With other enum strategies, we need to use the type name.
756
- return namingStrategy.getEnumTypeName(name, tableName, this.schema);
757
- }
758
- return column.mappedType?.runtimeType ?? 'unknown';
759
- }
760
- getPropertyDefaultValue(schemaHelper, column, propType, raw = false) {
761
- const defaultValue = column.default ?? 'null';
762
- const val = schemaHelper.normalizeDefaultValue(defaultValue, column.length);
763
- if (val === 'null') {
764
- return raw ? 'null' : column.nullable ? null : undefined;
765
- }
766
- if (propType === 'boolean' && !raw) {
767
- return !['0', 'false', 'f', 'n', 'no', 'off'].includes('' + column.default);
768
- }
769
- if (propType === 'number' && !raw) {
770
- return +defaultValue;
771
- }
772
- // unquote string defaults if `raw = false`
773
- const match = /^'(.*)'$/.exec('' + val);
774
- if (!raw && match) {
775
- return match[1];
776
- }
777
- return '' + val;
778
- }
779
- processIndexExpression(indexName, expression, meta) {
780
- if (expression instanceof Function) {
781
- const qualifiedName = this.schema ? `${this.schema}.${this.name}` : this.name;
782
- const table = {
783
- name: this.name,
784
- schema: this.schema,
785
- qualifiedName,
786
- toString: () => qualifiedName,
434
+ } else {
435
+ fksOnColumnProps.set(columnName, currentFk);
436
+ if (fkIndex) {
437
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName: columnName });
438
+ }
439
+ }
440
+ continue;
441
+ }
442
+ // If the first nullable column's name with FK is different from the name without FK,
443
+ // name a standalone prop after the column, but treat the column prop itself as not having FK.
444
+ const columnName = nullableColumnsInFk[0];
445
+ const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName);
446
+ standaloneFksBasedOnColumnNames.set(baseName, currentFk);
447
+ fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
448
+ if (fkIndex) {
449
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName });
450
+ }
451
+ continue;
452
+ }
453
+ // FK is not unambiguously mappable to a column. Pick another name for a standalone FK prop.
454
+ const baseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks);
455
+ fksOnStandaloneProps.set(baseName, { fkIndex, currentFk });
456
+ if (fkIndex) {
457
+ fkIndexes.set(fkIndex, { fk: currentFk, baseName });
458
+ }
459
+ }
460
+ const columnsInFks = Object.keys(columnFks);
461
+ const skippingHandlers = {
462
+ // Never generate scalar props for composite keys,
463
+ // i.e. always skip columns if they are covered by foreign keys.
464
+ never: column => columnsInFks.includes(column.name) && !fksOnColumnProps.has(column.name),
465
+ // Always generate scalar props for composite keys,
466
+ // i.e. do not skip columns, even if they are covered by foreign keys.
467
+ always: column => false,
468
+ // Smart scalar props generation.
469
+ // Skips columns if they are covered by foreign keys.
470
+ // But also does not skip if the column is not nullable, and yet all involved FKs are nullable,
471
+ // or if one or more FKs involved has multiple nullable columns.
472
+ smart: column => {
473
+ return (
474
+ columnsInFks.includes(column.name) &&
475
+ !fksOnColumnProps.has(column.name) &&
476
+ (column.nullable
477
+ ? columnFks[column.name].some(
478
+ fk =>
479
+ !fk.columnNames.some(
480
+ fkColumnName => fkColumnName !== column.name && this.getColumn(fkColumnName)?.nullable,
481
+ ),
482
+ )
483
+ : columnFks[column.name].some(fk => !nullableForeignKeys.has(fk)))
484
+ );
485
+ },
486
+ };
487
+ const skippedColumnNames = this.getColumns()
488
+ .filter(skippingHandlers[scalarPropertiesForRelations])
489
+ .map(column => column.name);
490
+ // Check standalone FKs named after columns for potential conflicts among themselves.
491
+ // This typically happens when two standalone FKs named after a column resolve to the same prop name
492
+ // because the respective columns include the referenced table in the name.
493
+ // Depending on naming strategy and actual names, it may also originate from other scenarios.
494
+ // We do our best to de-duplicate them here.
495
+ const safePropNames = new Set();
496
+ const unsafePropNames = new Map();
497
+ for (const [unsafeBaseName, currentFk] of standaloneFksBasedOnColumnNames) {
498
+ const propName = this.getPropertyName(namingStrategy, unsafeBaseName, currentFk);
499
+ if (safePropNames.has(propName)) {
500
+ if (!unsafePropNames.has(propName)) {
501
+ unsafePropNames.set(propName, []);
502
+ }
503
+ unsafePropNames.get(propName).push({ unsafeBaseName, currentFk });
504
+ continue;
505
+ }
506
+ safePropNames.add(propName);
507
+ }
508
+ for (const [unsafePropName, affectedBaseNames] of unsafePropNames) {
509
+ safePropNames.delete(unsafePropName);
510
+ for (const { unsafeBaseName, currentFk } of affectedBaseNames) {
511
+ const newBaseName = this.getSafeBaseNameForFkProp(namingStrategy, currentFk, fks);
512
+ fksOnStandaloneProps.delete(unsafeBaseName);
513
+ let fkIndex;
514
+ for (const [indexDef, fkIndexDesc] of fkIndexes) {
515
+ if (fkIndexDesc.fk !== currentFk) {
516
+ continue;
517
+ }
518
+ fkIndexDesc.baseName = newBaseName;
519
+ fkIndex = indexDef;
520
+ break;
521
+ }
522
+ fksOnStandaloneProps.set(newBaseName, { fkIndex, currentFk });
523
+ }
524
+ }
525
+ return { fksOnColumnProps, fksOnStandaloneProps, columnFks, fkIndexes, nullableForeignKeys, skippedColumnNames };
526
+ }
527
+ findFkIndex(currentFk) {
528
+ const fkColumnsLength = currentFk.columnNames.length;
529
+ const possibleIndexes = this.#indexes.filter(index => {
530
+ return (
531
+ index.columnNames.length === fkColumnsLength &&
532
+ !currentFk.columnNames.some((columnName, i) => index.columnNames[i] !== columnName)
533
+ );
534
+ });
535
+ possibleIndexes.sort((a, b) => {
536
+ if (a.primary !== b.primary) {
537
+ return a.primary ? -1 : 1;
538
+ }
539
+ if (a.unique !== b.unique) {
540
+ return a.unique ? -1 : 1;
541
+ }
542
+ return a.keyName.localeCompare(b.keyName);
543
+ });
544
+ return possibleIndexes.at(0);
545
+ }
546
+ getIndexProperties(index, columnFks, fksOnColumnProps, fksOnStandaloneProps, namingStrategy) {
547
+ const propBaseNames = new Set();
548
+ const columnNames = index.columnNames;
549
+ const l = columnNames.length;
550
+ if (columnNames.some(col => !col)) {
551
+ return;
552
+ }
553
+ for (let i = 0; i < l; ++i) {
554
+ const columnName = columnNames[i];
555
+ // The column is not involved with FKs.
556
+ if (!(columnName in columnFks)) {
557
+ // If there is no such column, the "name" is actually an expression.
558
+ if (!this.hasColumn(columnName)) {
559
+ return;
560
+ }
561
+ // It has a prop named after it.
562
+ // Add it and move on.
563
+ propBaseNames.add(columnName);
564
+ continue;
565
+ }
566
+ // If the prop named after the column has a FK and the FK's columns are a subset of this index,
567
+ // include this prop and move on.
568
+ const columnPropFk = fksOnColumnProps.get(columnName);
569
+ if (columnPropFk && !columnPropFk.columnNames.some(fkColumnName => !columnNames.includes(fkColumnName))) {
570
+ propBaseNames.add(columnName);
571
+ continue;
572
+ }
573
+ // If there is at least one standalone FK featuring this column,
574
+ // and all of its columns are a subset of this index,
575
+ // include that FK, and consider mapping of this column to a prop a success.
576
+ let propAdded = false;
577
+ for (const [propName, { currentFk: fk }] of fksOnStandaloneProps) {
578
+ if (!columnFks[columnName].includes(fk)) {
579
+ continue;
580
+ }
581
+ if (!fk.columnNames.some(fkColumnName => !columnNames.includes(fkColumnName))) {
582
+ propBaseNames.add(propName);
583
+ propAdded = true;
584
+ }
585
+ }
586
+ if (propAdded) {
587
+ continue;
588
+ }
589
+ // If we have reached this point, it means the column is not mappable to a prop name.
590
+ // Break the whole prop creation.
591
+ return;
592
+ }
593
+ return Array.from(propBaseNames).map(baseName =>
594
+ this.getPropertyName(namingStrategy, baseName, fksOnColumnProps.get(baseName)),
595
+ );
596
+ }
597
+ getSafeBaseNameForFkProp(namingStrategy, currentFk, fks, columnName) {
598
+ if (
599
+ columnName &&
600
+ this.getPropertyName(namingStrategy, columnName, currentFk) !== this.getPropertyName(namingStrategy, columnName)
601
+ ) {
602
+ // The eligible scalar column name is different from the name of the FK prop of the same column.
603
+ // Both can be safely rendered.
604
+ // Use the column name as a base for the FK prop.
605
+ return columnName;
606
+ }
607
+ // Strip schema prefix from referenced table name (e.g., "public.fr_usuario" -> "fr_usuario")
608
+ const getTableName = fullName => {
609
+ const parts = fullName.split('.');
610
+ return parts[parts.length - 1];
611
+ };
612
+ const referencedTableName = getTableName(currentFk.referencedTableName);
613
+ // Check for conflicts using stripped table names (handles cross-schema FKs to same-named tables)
614
+ const hasConflictingFk = fks.some(
615
+ fk => fk !== currentFk && getTableName(fk.referencedTableName) === referencedTableName,
616
+ );
617
+ if (!hasConflictingFk && !this.getColumn(referencedTableName)) {
618
+ // FK is the only one in this table that references a table with this name.
619
+ // The name of the referenced table is not shared with a column in this table,
620
+ // so it is safe to output prop name based on the referenced entity.
621
+ return referencedTableName;
622
+ }
623
+ // Any ambiguous FK is rendered with a name based on the FK constraint name
624
+ let finalPropBaseName = currentFk.constraintName;
625
+ while (this.getColumn(finalPropBaseName)) {
626
+ // In the unlikely event that the FK constraint name is shared by a column name, generate a name by
627
+ // continuously prefixing with "fk_", until a non-existent column is hit.
628
+ // The worst case scenario is a very long name with several repeated "fk_"
629
+ // that is not really a valid DB identifier but a valid JS variable name.
630
+ finalPropBaseName = `fk_${finalPropBaseName}`;
631
+ }
632
+ return finalPropBaseName;
633
+ }
634
+ /**
635
+ * The shortest name is stripped of the default namespace. All other namespaced elements are returned as full-qualified names.
636
+ */
637
+ getShortestName(skipDefaultSchema = true) {
638
+ const defaultSchema = this.#platform.getDefaultSchemaName();
639
+ if (
640
+ !this.schema ||
641
+ this.name.startsWith(defaultSchema + '.') ||
642
+ (this.schema === defaultSchema && skipDefaultSchema)
643
+ ) {
644
+ return this.name;
645
+ }
646
+ return `${this.schema}.${this.name}`;
647
+ }
648
+ getForeignKeys() {
649
+ return this.#foreignKeys;
650
+ }
651
+ hasColumn(columnName) {
652
+ return columnName in this.#columns;
653
+ }
654
+ getIndex(indexName) {
655
+ return this.#indexes.find(i => i.keyName === indexName);
656
+ }
657
+ hasIndex(indexName) {
658
+ return !!this.getIndex(indexName);
659
+ }
660
+ getCheck(checkName) {
661
+ return this.#checks.find(i => i.name === checkName);
662
+ }
663
+ hasCheck(checkName) {
664
+ return !!this.getCheck(checkName);
665
+ }
666
+ getPrimaryKey() {
667
+ return this.#indexes.find(i => i.primary);
668
+ }
669
+ hasPrimaryKey() {
670
+ return !!this.getPrimaryKey();
671
+ }
672
+ getForeignKeyDeclaration(fk, namingStrategy, schemaHelper, fkIndex, nullable, propNameBase, fksOnColumnProps) {
673
+ const prop = this.getPropertyName(namingStrategy, propNameBase, fk);
674
+ const kind = fkIndex?.unique && !fkIndex.primary ? this.getReferenceKind(fk, fkIndex) : this.getReferenceKind(fk);
675
+ const runtimeType = this.getPropertyTypeForForeignKey(namingStrategy, fk);
676
+ const fkOptions = {};
677
+ fkOptions.fieldNames = fk.columnNames;
678
+ fkOptions.referencedTableName = fk.referencedTableName;
679
+ fkOptions.referencedColumnNames = fk.referencedColumnNames;
680
+ fkOptions.updateRule = fk.updateRule?.toLowerCase();
681
+ fkOptions.deleteRule = fk.deleteRule?.toLowerCase();
682
+ fkOptions.deferMode = fk.deferMode;
683
+ fkOptions.columnTypes = fk.columnNames.map(c => this.getColumn(c).type);
684
+ const columnOptions = {};
685
+ if (fk.columnNames.length === 1) {
686
+ const column = this.getColumn(fk.columnNames[0]);
687
+ const defaultRaw = this.getPropertyDefaultValue(schemaHelper, column, column.type, true);
688
+ const defaultTs = this.getPropertyDefaultValue(schemaHelper, column, column.type);
689
+ columnOptions.default = defaultRaw !== defaultTs || defaultRaw === '' ? defaultTs : undefined;
690
+ columnOptions.defaultRaw = column.nullable && defaultRaw === 'null' ? undefined : defaultRaw;
691
+ columnOptions.optional = typeof column.generated !== 'undefined' || defaultRaw !== 'null';
692
+ columnOptions.generated = column.generated;
693
+ columnOptions.nullable = column.nullable;
694
+ columnOptions.primary = column.primary;
695
+ columnOptions.length = column.length;
696
+ columnOptions.precision = column.precision;
697
+ columnOptions.scale = column.scale;
698
+ columnOptions.extra = column.extra;
699
+ columnOptions.comment = column.comment;
700
+ columnOptions.enum = !!column.enumItems?.length;
701
+ columnOptions.items = column.enumItems;
702
+ }
703
+ return {
704
+ name: prop,
705
+ type: runtimeType,
706
+ runtimeType,
707
+ kind,
708
+ ...columnOptions,
709
+ nullable,
710
+ primary:
711
+ fkIndex?.primary || !fk.columnNames.some(columnName => !this.getPrimaryKey()?.columnNames.includes(columnName)),
712
+ index: !fkIndex?.unique ? fkIndex?.keyName : undefined,
713
+ unique: fkIndex?.unique && !fkIndex.primary ? fkIndex.keyName : undefined,
714
+ ...fkOptions,
715
+ };
716
+ }
717
+ getPropertyDeclaration(column, namingStrategy, schemaHelper, compositeFkIndexes, compositeFkUniques, columnFks, fk) {
718
+ const prop = this.getPropertyName(namingStrategy, column.name, fk);
719
+ const persist = !(column.name in columnFks && typeof fk === 'undefined');
720
+ const index =
721
+ compositeFkIndexes[prop] ||
722
+ this.#indexes.find(idx => idx.columnNames[0] === column.name && !idx.composite && !idx.unique && !idx.primary);
723
+ const unique =
724
+ compositeFkUniques[prop] ||
725
+ this.#indexes.find(idx => idx.columnNames[0] === column.name && !idx.composite && idx.unique && !idx.primary);
726
+ const kind = this.getReferenceKind(fk, unique);
727
+ const runtimeType = this.getPropertyTypeForColumn(namingStrategy, column, fk);
728
+ const type = fk
729
+ ? runtimeType
730
+ : (Utils.keys(t).find(k => {
731
+ const typeInCoreMap = this.#platform.getMappedType(k);
732
+ return (
733
+ (typeInCoreMap !== Type.getType(UnknownType) || k === 'unknown') && typeInCoreMap === column.mappedType
734
+ );
735
+ }) ?? runtimeType);
736
+ const ignoreSchemaChanges =
737
+ type === 'unknown' && column.length ? (column.extra ? ['type', 'extra'] : ['type']) : undefined;
738
+ const defaultRaw = this.getPropertyDefaultValue(schemaHelper, column, runtimeType, true);
739
+ const defaultParsed = this.getPropertyDefaultValue(schemaHelper, column, runtimeType);
740
+ const defaultTs = defaultRaw !== defaultParsed || defaultParsed === '' ? defaultParsed : undefined;
741
+ const fkOptions = {};
742
+ if (fk) {
743
+ fkOptions.fieldNames = fk.columnNames;
744
+ fkOptions.referencedTableName = fk.referencedTableName;
745
+ fkOptions.referencedColumnNames = fk.referencedColumnNames;
746
+ fkOptions.updateRule = fk.updateRule?.toLowerCase();
747
+ fkOptions.deleteRule = fk.deleteRule?.toLowerCase();
748
+ fkOptions.deferMode = fk.deferMode;
749
+ fkOptions.columnTypes = fk.columnNames.map(col => this.getColumn(col).type);
750
+ }
751
+ const ret = {
752
+ name: prop,
753
+ type,
754
+ runtimeType,
755
+ kind,
756
+ ignoreSchemaChanges,
757
+ generated: column.generated,
758
+ optional: defaultRaw !== 'null' || defaultTs != null || typeof column.generated !== 'undefined',
759
+ columnType: column.type,
760
+ default: defaultTs,
761
+ defaultRaw: column.nullable && defaultRaw === 'null' ? undefined : defaultRaw,
762
+ nullable: column.nullable,
763
+ primary: column.primary && persist,
764
+ autoincrement: column.autoincrement,
765
+ fieldName: column.name,
766
+ unsigned: column.unsigned,
767
+ length: column.length,
768
+ precision: column.precision,
769
+ scale: column.scale,
770
+ extra: column.extra,
771
+ comment: column.comment,
772
+ index: index ? index.keyName : undefined,
773
+ unique: unique ? unique.keyName : undefined,
774
+ enum: !!column.enumItems?.length,
775
+ items: column.enumItems,
776
+ persist,
777
+ ...fkOptions,
778
+ };
779
+ const nativeEnumName = Object.keys(this.nativeEnums).find(name => name === column.type);
780
+ if (nativeEnumName) {
781
+ ret.nativeEnumName = nativeEnumName;
782
+ }
783
+ return ret;
784
+ }
785
+ getReferenceKind(fk, unique) {
786
+ if (fk && unique) {
787
+ return ReferenceKind.ONE_TO_ONE;
788
+ }
789
+ if (fk) {
790
+ return ReferenceKind.MANY_TO_ONE;
791
+ }
792
+ return ReferenceKind.SCALAR;
793
+ }
794
+ getPropertyName(namingStrategy, baseName, fk) {
795
+ let field = baseName;
796
+ if (fk) {
797
+ const idx = fk.columnNames.indexOf(baseName);
798
+ let replacedFieldName = field.replace(new RegExp(`_${fk.referencedColumnNames[idx]}$`), '');
799
+ if (replacedFieldName === field) {
800
+ replacedFieldName = field.replace(new RegExp(`_${namingStrategy.referenceColumnName()}$`), '');
801
+ }
802
+ field = replacedFieldName;
803
+ }
804
+ if (field.startsWith('_')) {
805
+ return field;
806
+ }
807
+ return namingStrategy.columnNameToProperty(field);
808
+ }
809
+ getPropertyTypeForForeignKey(namingStrategy, fk) {
810
+ const parts = fk.referencedTableName.split('.', 2);
811
+ return namingStrategy.getEntityName(...parts.reverse());
812
+ }
813
+ getPropertyTypeForColumn(namingStrategy, column, fk) {
814
+ if (fk) {
815
+ return this.getPropertyTypeForForeignKey(namingStrategy, fk);
816
+ }
817
+ const enumMode = this.#platform.getConfig().get('entityGenerator').enumMode;
818
+ // If this column is using an enum.
819
+ if (column.enumItems?.length) {
820
+ const name = column.nativeEnumName ?? column.name;
821
+ const tableName = column.nativeEnumName ? undefined : this.name;
822
+ if (enumMode === 'ts-enum') {
823
+ // We will create a new enum name for this type and set it as the property type as well.
824
+ return namingStrategy.getEnumClassName(name, tableName, this.schema);
825
+ }
826
+ // With other enum strategies, we need to use the type name.
827
+ return namingStrategy.getEnumTypeName(name, tableName, this.schema);
828
+ }
829
+ return column.mappedType?.runtimeType ?? 'unknown';
830
+ }
831
+ getPropertyDefaultValue(schemaHelper, column, propType, raw = false) {
832
+ const defaultValue = column.default ?? 'null';
833
+ const val = schemaHelper.normalizeDefaultValue(defaultValue, column.length);
834
+ if (val === 'null') {
835
+ return raw ? 'null' : column.nullable ? null : undefined;
836
+ }
837
+ if (propType === 'boolean' && !raw) {
838
+ return !['0', 'false', 'f', 'n', 'no', 'off'].includes('' + column.default);
839
+ }
840
+ if (propType === 'number' && !raw) {
841
+ return +defaultValue;
842
+ }
843
+ // unquote string defaults if `raw = false`
844
+ const match = /^'(.*)'$/.exec('' + val);
845
+ if (!raw && match) {
846
+ return match[1];
847
+ }
848
+ return '' + val;
849
+ }
850
+ processIndexExpression(indexName, expression, meta) {
851
+ if (expression instanceof Function) {
852
+ const qualifiedName = this.schema ? `${this.schema}.${this.name}` : this.name;
853
+ const table = {
854
+ name: this.name,
855
+ schema: this.schema,
856
+ qualifiedName,
857
+ toString: () => qualifiedName,
858
+ };
859
+ const columns = meta.createSchemaColumnMappingObject();
860
+ const exp = expression(columns, table, indexName);
861
+ return exp instanceof RawQueryFragment ? this.#platform.formatQuery(exp.sql, exp.params) : exp;
862
+ }
863
+ return expression;
864
+ }
865
+ addIndex(meta, index, type) {
866
+ // If columns are specified but properties are not, derive properties from column names
867
+ if (
868
+ index.columns?.length &&
869
+ !index.expression &&
870
+ (!index.properties || Utils.asArray(index.properties).length === 0)
871
+ ) {
872
+ index = { ...index, properties: index.columns.map(c => c.name) };
873
+ }
874
+ const properties = Utils.unique(
875
+ Utils.flatten(
876
+ Utils.asArray(index.properties).map(prop => {
877
+ const parts = prop.split('.');
878
+ const root = parts[0];
879
+ if (meta.properties[prop]) {
880
+ if (meta.properties[prop].embeddedPath) {
881
+ return [meta.properties[prop].embeddedPath.join('.')];
882
+ }
883
+ return meta.properties[prop].fieldNames;
884
+ }
885
+ const rootProp = meta.properties[root];
886
+ // inline embedded property index, we need to find the field name of the child property
887
+ if (rootProp?.embeddable && !rootProp.object && parts.length > 1) {
888
+ const expand = (p, i) => {
889
+ if (parts.length === i) {
890
+ return p.fieldNames[0];
891
+ }
892
+ return expand(p.embeddedProps[parts[i]], i + 1);
787
893
  };
788
- const columns = meta.createSchemaColumnMappingObject();
789
- const exp = expression(columns, table, indexName);
790
- return exp instanceof RawQueryFragment ? this.#platform.formatQuery(exp.sql, exp.params) : exp;
791
- }
792
- return expression;
793
- }
794
- addIndex(meta, index, type) {
795
- // If columns are specified but properties are not, derive properties from column names
796
- if (index.columns?.length &&
797
- !index.expression &&
798
- (!index.properties || Utils.asArray(index.properties).length === 0)) {
799
- index = { ...index, properties: index.columns.map(c => c.name) };
800
- }
801
- const properties = Utils.unique(Utils.flatten(Utils.asArray(index.properties).map(prop => {
802
- const parts = prop.split('.');
803
- const root = parts[0];
804
- if (meta.properties[prop]) {
805
- if (meta.properties[prop].embeddedPath) {
806
- return [meta.properties[prop].embeddedPath.join('.')];
807
- }
894
+ return [expand(rootProp, 1)];
895
+ }
896
+ // json index, we need to rename the column only
897
+ if (rootProp) {
898
+ return [prop.replace(root, rootProp.fieldNames[0])];
899
+ }
900
+ /* v8 ignore next */
901
+ return [prop];
902
+ }),
903
+ ),
904
+ );
905
+ if (properties.length === 0 && !index.expression) {
906
+ return;
907
+ }
908
+ const name = this.getIndexName(index.name, properties, type);
909
+ // Process include columns (map property names to field names)
910
+ const includeColumns = index.include
911
+ ? Utils.unique(
912
+ Utils.flatten(
913
+ Utils.asArray(index.include).map(prop => {
914
+ if (meta.properties[prop]) {
808
915
  return meta.properties[prop].fieldNames;
809
- }
810
- const rootProp = meta.properties[root];
811
- // inline embedded property index, we need to find the field name of the child property
812
- if (rootProp?.embeddable && !rootProp.object && parts.length > 1) {
813
- const expand = (p, i) => {
814
- if (parts.length === i) {
815
- return p.fieldNames[0];
816
- }
817
- return expand(p.embeddedProps[parts[i]], i + 1);
818
- };
819
- return [expand(rootProp, 1)];
820
- }
821
- // json index, we need to rename the column only
822
- if (rootProp) {
823
- return [prop.replace(root, rootProp.fieldNames[0])];
824
- }
825
- /* v8 ignore next */
826
- return [prop];
827
- })));
828
- if (properties.length === 0 && !index.expression) {
829
- return;
830
- }
831
- const name = this.getIndexName(index.name, properties, type);
832
- // Process include columns (map property names to field names)
833
- const includeColumns = index.include
834
- ? Utils.unique(Utils.flatten(Utils.asArray(index.include).map(prop => {
835
- if (meta.properties[prop]) {
836
- return meta.properties[prop].fieldNames;
837
- }
838
- /* v8 ignore next */
839
- return [prop];
840
- })))
841
- : undefined;
842
- // Process columns with advanced options (map property names to field names)
843
- const columns = index.columns?.map(col => {
844
- const fieldName = meta.properties[col.name]?.fieldNames[0] ?? col.name;
845
- return {
846
- name: fieldName,
847
- sort: col.sort?.toUpperCase(),
848
- nulls: col.nulls?.toUpperCase(),
849
- length: col.length,
850
- collation: col.collation,
851
- };
852
- });
853
- // Validate that column options reference fields in the index properties
854
- if (columns?.length && properties.length > 0) {
855
- for (const col of columns) {
856
- if (!properties.includes(col.name)) {
857
- throw new Error(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
858
- }
859
- }
860
- }
861
- // Validate fillFactor range
862
- if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
863
- throw new Error(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
864
- }
865
- this.#indexes.push({
866
- keyName: name,
867
- columnNames: properties,
868
- composite: properties.length > 1,
869
- // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
870
- constraint: type !== 'index' && !properties.some((d) => d.includes('.')),
871
- primary: type === 'primary',
872
- unique: type !== 'index',
873
- type: index.type,
874
- expression: this.processIndexExpression(name, index.expression, meta),
875
- options: index.options,
876
- deferMode: index.deferMode,
877
- columns,
878
- include: includeColumns,
879
- fillFactor: index.fillFactor,
880
- invisible: index.invisible,
881
- disabled: index.disabled,
882
- clustered: index.clustered,
883
- });
884
- }
885
- addCheck(check) {
886
- this.#checks.push(check);
887
- }
888
- toJSON() {
889
- const columns = this.#columns;
890
- const columnsMapped = Utils.keys(columns).reduce((o, col) => {
891
- const c = columns[col];
892
- const normalized = {
893
- name: c.name,
894
- type: c.type,
895
- unsigned: !!c.unsigned,
896
- autoincrement: !!c.autoincrement,
897
- primary: !!c.primary,
898
- nullable: !!c.nullable,
899
- unique: !!c.unique,
900
- length: c.length ?? null,
901
- precision: c.precision ?? null,
902
- scale: c.scale ?? null,
903
- default: c.default ?? null,
904
- comment: c.comment ?? null,
905
- enumItems: c.enumItems ?? [],
906
- mappedType: Utils.keys(t).find(k => t[k] === c.mappedType.constructor),
907
- };
908
- if (c.generated) {
909
- normalized.generated = c.generated;
910
- }
911
- if (c.nativeEnumName) {
912
- normalized.nativeEnumName = c.nativeEnumName;
913
- }
914
- if (c.extra) {
915
- normalized.extra = c.extra;
916
- }
917
- if (c.ignoreSchemaChanges) {
918
- normalized.ignoreSchemaChanges = c.ignoreSchemaChanges;
919
- }
920
- if (c.defaultConstraint) {
921
- normalized.defaultConstraint = c.defaultConstraint;
922
- }
923
- o[col] = normalized;
924
- return o;
925
- }, {});
926
- return {
927
- name: this.name,
928
- schema: this.schema,
929
- columns: columnsMapped,
930
- indexes: this.#indexes,
931
- checks: this.#checks,
932
- foreignKeys: this.#foreignKeys,
933
- nativeEnums: this.nativeEnums,
934
- comment: this.comment,
935
- };
936
- }
916
+ }
917
+ /* v8 ignore next */
918
+ return [prop];
919
+ }),
920
+ ),
921
+ )
922
+ : undefined;
923
+ // Process columns with advanced options (map property names to field names)
924
+ const columns = index.columns?.map(col => {
925
+ const fieldName = meta.properties[col.name]?.fieldNames[0] ?? col.name;
926
+ return {
927
+ name: fieldName,
928
+ sort: col.sort?.toUpperCase(),
929
+ nulls: col.nulls?.toUpperCase(),
930
+ length: col.length,
931
+ collation: col.collation,
932
+ };
933
+ });
934
+ // Validate that column options reference fields in the index properties
935
+ if (columns?.length && properties.length > 0) {
936
+ for (const col of columns) {
937
+ if (!properties.includes(col.name)) {
938
+ throw new Error(
939
+ `Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`,
940
+ );
941
+ }
942
+ }
943
+ }
944
+ // Validate fillFactor range
945
+ if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
946
+ throw new Error(
947
+ `fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`,
948
+ );
949
+ }
950
+ this.#indexes.push({
951
+ keyName: name,
952
+ columnNames: properties,
953
+ composite: properties.length > 1,
954
+ // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
955
+ constraint: type !== 'index' && !properties.some(d => d.includes('.')),
956
+ primary: type === 'primary',
957
+ unique: type !== 'index',
958
+ type: index.type,
959
+ expression: this.processIndexExpression(name, index.expression, meta),
960
+ options: index.options,
961
+ deferMode: index.deferMode,
962
+ columns,
963
+ include: includeColumns,
964
+ fillFactor: index.fillFactor,
965
+ invisible: index.invisible,
966
+ disabled: index.disabled,
967
+ clustered: index.clustered,
968
+ });
969
+ }
970
+ addCheck(check) {
971
+ this.#checks.push(check);
972
+ }
973
+ toJSON() {
974
+ const columns = this.#columns;
975
+ const columnsMapped = Utils.keys(columns).reduce((o, col) => {
976
+ const c = columns[col];
977
+ const normalized = {
978
+ name: c.name,
979
+ type: c.type,
980
+ unsigned: !!c.unsigned,
981
+ autoincrement: !!c.autoincrement,
982
+ primary: !!c.primary,
983
+ nullable: !!c.nullable,
984
+ unique: !!c.unique,
985
+ length: c.length ?? null,
986
+ precision: c.precision ?? null,
987
+ scale: c.scale ?? null,
988
+ default: c.default ?? null,
989
+ comment: c.comment ?? null,
990
+ enumItems: c.enumItems ?? [],
991
+ mappedType: Utils.keys(t).find(k => t[k] === c.mappedType.constructor),
992
+ };
993
+ if (c.generated) {
994
+ normalized.generated = c.generated;
995
+ }
996
+ if (c.nativeEnumName) {
997
+ normalized.nativeEnumName = c.nativeEnumName;
998
+ }
999
+ if (c.extra) {
1000
+ normalized.extra = c.extra;
1001
+ }
1002
+ if (c.ignoreSchemaChanges) {
1003
+ normalized.ignoreSchemaChanges = c.ignoreSchemaChanges;
1004
+ }
1005
+ if (c.defaultConstraint) {
1006
+ normalized.defaultConstraint = c.defaultConstraint;
1007
+ }
1008
+ o[col] = normalized;
1009
+ return o;
1010
+ }, {});
1011
+ return {
1012
+ name: this.name,
1013
+ schema: this.schema,
1014
+ columns: columnsMapped,
1015
+ indexes: this.#indexes,
1016
+ checks: this.#checks,
1017
+ foreignKeys: this.#foreignKeys,
1018
+ nativeEnums: this.nativeEnums,
1019
+ comment: this.comment,
1020
+ };
1021
+ }
937
1022
  }