metal-orm 1.0.58 → 1.0.60
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 +34 -31
- package/dist/index.cjs +1583 -901
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +400 -129
- package/dist/index.d.ts +400 -129
- package/dist/index.js +1575 -901
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/ddl/schema-generator.ts +44 -1
- package/src/decorators/bootstrap.ts +183 -146
- package/src/decorators/column-decorator.ts +8 -49
- package/src/decorators/decorator-metadata.ts +10 -46
- package/src/decorators/entity.ts +30 -40
- package/src/decorators/relations.ts +30 -56
- package/src/index.ts +7 -7
- package/src/orm/entity-hydration.ts +72 -0
- package/src/orm/entity-meta.ts +13 -11
- package/src/orm/entity-metadata.ts +240 -238
- package/src/orm/entity-relation-cache.ts +39 -0
- package/src/orm/entity-relations.ts +207 -0
- package/src/orm/entity.ts +124 -410
- package/src/orm/execute.ts +4 -4
- package/src/orm/lazy-batch/belongs-to-many.ts +134 -0
- package/src/orm/lazy-batch/belongs-to.ts +108 -0
- package/src/orm/lazy-batch/has-many.ts +69 -0
- package/src/orm/lazy-batch/has-one.ts +68 -0
- package/src/orm/lazy-batch/shared.ts +125 -0
- package/src/orm/lazy-batch.ts +4 -492
- package/src/orm/relations/many-to-many.ts +2 -1
- package/src/query-builder/relation-cte-builder.ts +63 -0
- package/src/query-builder/relation-filter-utils.ts +159 -0
- package/src/query-builder/relation-include-strategies.ts +177 -0
- package/src/query-builder/relation-join-planner.ts +80 -0
- package/src/query-builder/relation-service.ts +119 -479
- package/src/query-builder/relation-types.ts +41 -10
- package/src/query-builder/select/projection-facet.ts +23 -23
- package/src/query-builder/select/select-operations.ts +145 -0
- package/src/query-builder/select.ts +329 -221
- package/src/schema/relation.ts +22 -18
- package/src/schema/table.ts +22 -9
- package/src/schema/types.ts +14 -12
package/src/orm/lazy-batch.ts
CHANGED
|
@@ -1,493 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { EntityContext } from './entity-context.js';
|
|
6
|
-
import type { QueryResult } from '../core/execution/db-executor.js';
|
|
7
|
-
import { ColumnDef } from '../schema/column-types.js';
|
|
8
|
-
import { findPrimaryKey } from '../query-builder/hydration-planner.js';
|
|
9
|
-
import { RelationIncludeOptions } from '../query-builder/relation-types.js';
|
|
10
|
-
import { buildDefaultPivotColumns } from '../query-builder/relation-utils.js';
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* An array of database rows, each represented as a record of string keys to unknown values.
|
|
14
|
-
*/
|
|
15
|
-
type Rows = Record<string, unknown>[];
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Represents a single tracked entity from the EntityContext for a table.
|
|
19
|
-
*/
|
|
20
|
-
type EntityTracker = ReturnType<EntityContext['getEntitiesForTable']>[number];
|
|
21
|
-
|
|
22
|
-
const hasColumns = (columns?: readonly string[]): columns is readonly string[] =>
|
|
23
|
-
Boolean(columns && columns.length > 0);
|
|
24
|
-
|
|
25
|
-
const buildColumnSelection = (
|
|
26
|
-
table: TableDef,
|
|
27
|
-
columns: string[],
|
|
28
|
-
missingMsg: (col: string) => string
|
|
29
|
-
): Record<string, ColumnDef> => {
|
|
30
|
-
return columns.reduce((acc, column) => {
|
|
31
|
-
const def = table.columns[column];
|
|
32
|
-
if (!def) {
|
|
33
|
-
throw new Error(missingMsg(column));
|
|
34
|
-
}
|
|
35
|
-
acc[column] = def;
|
|
36
|
-
return acc;
|
|
37
|
-
}, {} as Record<string, ColumnDef>);
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
const filterRow = (row: Record<string, unknown>, columns: Set<string>): Record<string, unknown> => {
|
|
41
|
-
const filtered: Record<string, unknown> = {};
|
|
42
|
-
for (const column of columns) {
|
|
43
|
-
if (column in row) {
|
|
44
|
-
filtered[column] = row[column];
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
return filtered;
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
const filterRows = (rows: Rows, columns: Set<string>): Rows => rows.map(row => filterRow(row, columns));
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Extracts rows from query results into a standardized format.
|
|
54
|
-
* @param results - The query results to process.
|
|
55
|
-
* @returns An array of rows as records.
|
|
56
|
-
*/
|
|
57
|
-
const rowsFromResults = (results: QueryResult[]): Rows => {
|
|
58
|
-
const rows: Rows = [];
|
|
59
|
-
for (const result of results) {
|
|
60
|
-
const { columns, values } = result;
|
|
61
|
-
for (const valueRow of values) {
|
|
62
|
-
const row: Record<string, unknown> = {};
|
|
63
|
-
columns.forEach((column, idx) => {
|
|
64
|
-
row[column] = valueRow[idx];
|
|
65
|
-
});
|
|
66
|
-
rows.push(row);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return rows;
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Executes a select query and returns the resulting rows.
|
|
74
|
-
* @param ctx - The entity context for execution.
|
|
75
|
-
* @param qb - The select query builder.
|
|
76
|
-
* @returns A promise resolving to the rows from the query.
|
|
77
|
-
*/
|
|
78
|
-
const executeQuery = async (ctx: EntityContext, qb: SelectQueryBuilder<unknown, TableDef>): Promise<Rows> => {
|
|
79
|
-
const compiled = ctx.dialect.compileSelect(qb.getAST());
|
|
80
|
-
const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
|
|
81
|
-
return rowsFromResults(results);
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Converts a value to a string key, handling null and undefined as empty string.
|
|
86
|
-
* @param value - The value to convert.
|
|
87
|
-
* @returns The string representation of the value.
|
|
88
|
-
*/
|
|
89
|
-
const toKey = (value: unknown): string => (value === null || value === undefined ? '' : String(value));
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Collects unique keys from the root entities based on the specified key property.
|
|
93
|
-
* @param roots - The tracked entities to collect keys from.
|
|
94
|
-
* @param key - The property name to use as the key.
|
|
95
|
-
* @returns A set of unique key values.
|
|
96
|
-
*/
|
|
97
|
-
const collectKeysFromRoots = (roots: EntityTracker[], key: string): Set<unknown> => {
|
|
98
|
-
const collected = new Set<unknown>();
|
|
99
|
-
for (const tracked of roots) {
|
|
100
|
-
const value = tracked.entity[key];
|
|
101
|
-
if (value !== null && value !== undefined) {
|
|
102
|
-
collected.add(value);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
return collected;
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Builds an array of values suitable for an IN list expression from a set of keys.
|
|
110
|
-
* @param keys - The set of keys to convert.
|
|
111
|
-
* @returns An array of string, number, or LiteralNode values.
|
|
112
|
-
*/
|
|
113
|
-
const buildInListValues = (keys: Set<unknown>): (string | number | LiteralNode)[] =>
|
|
114
|
-
Array.from(keys) as (string | number | LiteralNode)[];
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Fetches rows from a table where the specified column matches any of the given keys.
|
|
118
|
-
* @param ctx - The entity context.
|
|
119
|
-
* @param table - The target table.
|
|
120
|
-
* @param column - The column to match against.
|
|
121
|
-
* @param keys - The set of keys to match.
|
|
122
|
-
* @returns A promise resolving to the matching rows.
|
|
123
|
-
*/
|
|
124
|
-
const fetchRowsForKeys = async (
|
|
125
|
-
ctx: EntityContext,
|
|
126
|
-
table: TableDef,
|
|
127
|
-
column: ColumnDef,
|
|
128
|
-
keys: Set<unknown>,
|
|
129
|
-
selection: Record<string, ColumnDef>,
|
|
130
|
-
filter?: ExpressionNode
|
|
131
|
-
): Promise<Rows> => {
|
|
132
|
-
let qb = new SelectQueryBuilder(table).select(selection);
|
|
133
|
-
qb = qb.where(inList(column, buildInListValues(keys)));
|
|
134
|
-
if (filter) {
|
|
135
|
-
qb = qb.where(filter);
|
|
136
|
-
}
|
|
137
|
-
return executeQuery(ctx, qb);
|
|
138
|
-
};
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Groups rows by the value of a key column, allowing multiple rows per key.
|
|
142
|
-
* @param rows - The rows to group.
|
|
143
|
-
* @param keyColumn - The column name to group by.
|
|
144
|
-
* @returns A map from key strings to arrays of rows.
|
|
145
|
-
*/
|
|
146
|
-
const groupRowsByMany = (rows: Rows, keyColumn: string): Map<string, Rows> => {
|
|
147
|
-
const grouped = new Map<string, Rows>();
|
|
148
|
-
for (const row of rows) {
|
|
149
|
-
const value = row[keyColumn];
|
|
150
|
-
if (value === null || value === undefined) continue;
|
|
151
|
-
const key = toKey(value);
|
|
152
|
-
const bucket = grouped.get(key) ?? [];
|
|
153
|
-
bucket.push(row);
|
|
154
|
-
grouped.set(key, bucket);
|
|
155
|
-
}
|
|
156
|
-
return grouped;
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Groups rows by the value of a key column, keeping only one row per key.
|
|
161
|
-
* @param rows - The rows to group.
|
|
162
|
-
* @param keyColumn - The column name to group by.
|
|
163
|
-
* @returns A map from key strings to single rows.
|
|
164
|
-
*/
|
|
165
|
-
const groupRowsByUnique = (rows: Rows, keyColumn: string): Map<string, Record<string, unknown>> => {
|
|
166
|
-
const lookup = new Map<string, Record<string, unknown>>();
|
|
167
|
-
for (const row of rows) {
|
|
168
|
-
const value = row[keyColumn];
|
|
169
|
-
if (value === null || value === undefined) continue;
|
|
170
|
-
const key = toKey(value);
|
|
171
|
-
if (!lookup.has(key)) {
|
|
172
|
-
lookup.set(key, row);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return lookup;
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Loads related entities for a has-many relation in batch.
|
|
180
|
-
* @param ctx - The entity context.
|
|
181
|
-
* @param rootTable - The root table of the relation.
|
|
182
|
-
* @param _relationName - The name of the relation (unused).
|
|
183
|
-
* @param relation - The has-many relation definition.
|
|
184
|
-
* @returns A promise resolving to a map of root keys to arrays of related rows.
|
|
185
|
-
*/
|
|
186
|
-
export const loadHasManyRelation = async (
|
|
187
|
-
ctx: EntityContext,
|
|
188
|
-
rootTable: TableDef,
|
|
189
|
-
relationName: string,
|
|
190
|
-
relation: HasManyRelation,
|
|
191
|
-
options?: RelationIncludeOptions
|
|
192
|
-
): Promise<Map<string, Rows>> => {
|
|
193
|
-
const localKey = relation.localKey || findPrimaryKey(rootTable);
|
|
194
|
-
const roots = ctx.getEntitiesForTable(rootTable);
|
|
195
|
-
const keys = collectKeysFromRoots(roots, localKey);
|
|
196
|
-
|
|
197
|
-
if (!keys.size) {
|
|
198
|
-
return new Map();
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
const fkColumn = relation.target.columns[relation.foreignKey];
|
|
202
|
-
if (!fkColumn) return new Map();
|
|
203
|
-
|
|
204
|
-
const requestedColumns = hasColumns(options?.columns) ? [...options!.columns] : undefined;
|
|
205
|
-
const targetPrimaryKey = findPrimaryKey(relation.target);
|
|
206
|
-
const selectedColumns = requestedColumns ? [...requestedColumns] : Object.keys(relation.target.columns);
|
|
207
|
-
if (!selectedColumns.includes(targetPrimaryKey)) {
|
|
208
|
-
selectedColumns.push(targetPrimaryKey);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
const queryColumns = new Set(selectedColumns);
|
|
212
|
-
queryColumns.add(relation.foreignKey);
|
|
213
|
-
|
|
214
|
-
const selection = buildColumnSelection(
|
|
215
|
-
relation.target,
|
|
216
|
-
Array.from(queryColumns),
|
|
217
|
-
column => `Column '${column}' not found on relation '${relationName}'`
|
|
218
|
-
);
|
|
219
|
-
|
|
220
|
-
const rows = await fetchRowsForKeys(ctx, relation.target, fkColumn, keys, selection, options?.filter);
|
|
221
|
-
const grouped = groupRowsByMany(rows, relation.foreignKey);
|
|
222
|
-
|
|
223
|
-
if (!requestedColumns) return grouped;
|
|
224
|
-
|
|
225
|
-
const visibleColumns = new Set(selectedColumns);
|
|
226
|
-
const filtered = new Map<string, Rows>();
|
|
227
|
-
for (const [key, bucket] of grouped.entries()) {
|
|
228
|
-
filtered.set(key, filterRows(bucket, visibleColumns));
|
|
229
|
-
}
|
|
230
|
-
return filtered;
|
|
231
|
-
};
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Loads related entities for a has-one relation in batch.
|
|
235
|
-
* @param ctx - The entity context.
|
|
236
|
-
* @param rootTable - The root table of the relation.
|
|
237
|
-
* @param _relationName - The name of the relation (unused).
|
|
238
|
-
* @param relation - The has-one relation definition.
|
|
239
|
-
* @returns A promise resolving to a map of root keys to single related rows.
|
|
240
|
-
*/
|
|
241
|
-
export const loadHasOneRelation = async (
|
|
242
|
-
ctx: EntityContext,
|
|
243
|
-
rootTable: TableDef,
|
|
244
|
-
relationName: string,
|
|
245
|
-
relation: HasOneRelation,
|
|
246
|
-
options?: RelationIncludeOptions
|
|
247
|
-
): Promise<Map<string, Record<string, unknown>>> => {
|
|
248
|
-
const localKey = relation.localKey || findPrimaryKey(rootTable);
|
|
249
|
-
const roots = ctx.getEntitiesForTable(rootTable);
|
|
250
|
-
const keys = collectKeysFromRoots(roots, localKey);
|
|
251
|
-
|
|
252
|
-
if (!keys.size) {
|
|
253
|
-
return new Map();
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
const fkColumn = relation.target.columns[relation.foreignKey];
|
|
257
|
-
if (!fkColumn) return new Map();
|
|
258
|
-
|
|
259
|
-
const requestedColumns = hasColumns(options?.columns) ? [...options!.columns] : undefined;
|
|
260
|
-
const targetPrimaryKey = findPrimaryKey(relation.target);
|
|
261
|
-
const selectedColumns = requestedColumns ? [...requestedColumns] : Object.keys(relation.target.columns);
|
|
262
|
-
if (!selectedColumns.includes(targetPrimaryKey)) {
|
|
263
|
-
selectedColumns.push(targetPrimaryKey);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
const queryColumns = new Set(selectedColumns);
|
|
267
|
-
queryColumns.add(relation.foreignKey);
|
|
268
|
-
|
|
269
|
-
const selection = buildColumnSelection(
|
|
270
|
-
relation.target,
|
|
271
|
-
Array.from(queryColumns),
|
|
272
|
-
column => `Column '${column}' not found on relation '${relationName}'`
|
|
273
|
-
);
|
|
274
|
-
|
|
275
|
-
const rows = await fetchRowsForKeys(ctx, relation.target, fkColumn, keys, selection, options?.filter);
|
|
276
|
-
const grouped = groupRowsByUnique(rows, relation.foreignKey);
|
|
277
|
-
|
|
278
|
-
if (!requestedColumns) return grouped;
|
|
279
|
-
|
|
280
|
-
const visibleColumns = new Set(selectedColumns);
|
|
281
|
-
const filtered = new Map<string, Record<string, unknown>>();
|
|
282
|
-
for (const [key, row] of grouped.entries()) {
|
|
283
|
-
filtered.set(key, filterRow(row, visibleColumns));
|
|
284
|
-
}
|
|
285
|
-
return filtered;
|
|
286
|
-
};
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Loads related entities for a belongs-to relation in batch.
|
|
290
|
-
* @param ctx - The entity context.
|
|
291
|
-
* @param rootTable - The root table of the relation.
|
|
292
|
-
* @param _relationName - The name of the relation (unused).
|
|
293
|
-
* @param relation - The belongs-to relation definition.
|
|
294
|
-
* @returns A promise resolving to a map of foreign keys to single related rows.
|
|
295
|
-
*/
|
|
296
|
-
export const loadBelongsToRelation = async (
|
|
297
|
-
ctx: EntityContext,
|
|
298
|
-
rootTable: TableDef,
|
|
299
|
-
relationName: string,
|
|
300
|
-
relation: BelongsToRelation,
|
|
301
|
-
options?: RelationIncludeOptions
|
|
302
|
-
): Promise<Map<string, Record<string, unknown>>> => {
|
|
303
|
-
const roots = ctx.getEntitiesForTable(rootTable);
|
|
304
|
-
|
|
305
|
-
const getForeignKeys = (): Set<unknown> => collectKeysFromRoots(roots, relation.foreignKey);
|
|
306
|
-
let foreignKeys = getForeignKeys();
|
|
307
|
-
|
|
308
|
-
if (!foreignKeys.size) {
|
|
309
|
-
const pkName = findPrimaryKey(rootTable);
|
|
310
|
-
const pkColumn = rootTable.columns[pkName];
|
|
311
|
-
const fkColumn = rootTable.columns[relation.foreignKey];
|
|
312
|
-
|
|
313
|
-
if (pkColumn && fkColumn) {
|
|
314
|
-
const missingKeys = new Set<unknown>();
|
|
315
|
-
const entityByPk = new Map<unknown, Record<string, unknown>>();
|
|
316
|
-
|
|
317
|
-
for (const tracked of roots) {
|
|
318
|
-
const entity = tracked.entity as Record<string, unknown>;
|
|
319
|
-
const pkValue = entity[pkName];
|
|
320
|
-
if (pkValue === undefined || pkValue === null) continue;
|
|
321
|
-
const fkValue = entity[relation.foreignKey];
|
|
322
|
-
if (fkValue === undefined || fkValue === null) {
|
|
323
|
-
missingKeys.add(pkValue);
|
|
324
|
-
entityByPk.set(pkValue, entity);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
if (missingKeys.size) {
|
|
329
|
-
const selection = buildColumnSelection(
|
|
330
|
-
rootTable,
|
|
331
|
-
[pkName, relation.foreignKey],
|
|
332
|
-
column => `Column '${column}' not found on table '${rootTable.name}'`
|
|
333
|
-
);
|
|
334
|
-
const keyRows = await fetchRowsForKeys(ctx, rootTable, pkColumn, missingKeys, selection);
|
|
335
|
-
for (const row of keyRows) {
|
|
336
|
-
const pkValue = row[pkName];
|
|
337
|
-
if (pkValue === undefined || pkValue === null) continue;
|
|
338
|
-
const entity = entityByPk.get(pkValue);
|
|
339
|
-
if (!entity) continue;
|
|
340
|
-
const fkValue = row[relation.foreignKey];
|
|
341
|
-
if (fkValue !== undefined && fkValue !== null) {
|
|
342
|
-
entity[relation.foreignKey] = fkValue;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
foreignKeys = getForeignKeys();
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
if (!foreignKeys.size) {
|
|
351
|
-
return new Map();
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
const targetKey = relation.localKey || findPrimaryKey(relation.target);
|
|
355
|
-
const pkColumn = relation.target.columns[targetKey];
|
|
356
|
-
if (!pkColumn) return new Map();
|
|
357
|
-
|
|
358
|
-
const requestedColumns = hasColumns(options?.columns) ? [...options!.columns] : undefined;
|
|
359
|
-
const selectedColumns = requestedColumns ? [...requestedColumns] : Object.keys(relation.target.columns);
|
|
360
|
-
if (!selectedColumns.includes(targetKey)) {
|
|
361
|
-
selectedColumns.push(targetKey);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
const selection = buildColumnSelection(
|
|
365
|
-
relation.target,
|
|
366
|
-
selectedColumns,
|
|
367
|
-
column => `Column '${column}' not found on relation '${relationName}'`
|
|
368
|
-
);
|
|
369
|
-
|
|
370
|
-
const rows = await fetchRowsForKeys(ctx, relation.target, pkColumn, foreignKeys, selection, options?.filter);
|
|
371
|
-
const grouped = groupRowsByUnique(rows, targetKey);
|
|
372
|
-
|
|
373
|
-
if (!requestedColumns) return grouped;
|
|
374
|
-
|
|
375
|
-
const visibleColumns = new Set(selectedColumns);
|
|
376
|
-
const filtered = new Map<string, Record<string, unknown>>();
|
|
377
|
-
for (const [key, row] of grouped.entries()) {
|
|
378
|
-
filtered.set(key, filterRow(row, visibleColumns));
|
|
379
|
-
}
|
|
380
|
-
return filtered;
|
|
381
|
-
};
|
|
382
|
-
|
|
383
|
-
/**
|
|
384
|
-
* Loads related entities for a belongs-to-many relation in batch, including pivot data.
|
|
385
|
-
* @param ctx - The entity context.
|
|
386
|
-
* @param rootTable - The root table of the relation.
|
|
387
|
-
* @param _relationName - The name of the relation (unused).
|
|
388
|
-
* @param relation - The belongs-to-many relation definition.
|
|
389
|
-
* @returns A promise resolving to a map of root keys to arrays of related rows with pivot data.
|
|
390
|
-
*/
|
|
391
|
-
export const loadBelongsToManyRelation = async (
|
|
392
|
-
ctx: EntityContext,
|
|
393
|
-
rootTable: TableDef,
|
|
394
|
-
relationName: string,
|
|
395
|
-
relation: BelongsToManyRelation,
|
|
396
|
-
options?: RelationIncludeOptions
|
|
397
|
-
): Promise<Map<string, Rows>> => {
|
|
398
|
-
const rootKey = relation.localKey || findPrimaryKey(rootTable);
|
|
399
|
-
const roots = ctx.getEntitiesForTable(rootTable);
|
|
400
|
-
const rootIds = collectKeysFromRoots(roots, rootKey);
|
|
401
|
-
|
|
402
|
-
if (!rootIds.size) {
|
|
403
|
-
return new Map();
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
const pivotColumn = relation.pivotTable.columns[relation.pivotForeignKeyToRoot];
|
|
407
|
-
if (!pivotColumn) return new Map();
|
|
408
|
-
|
|
409
|
-
const pivotColumnsRequested = hasColumns(options?.pivot?.columns) ? [...options!.pivot!.columns] : undefined;
|
|
410
|
-
const useIncludeDefaults = options !== undefined;
|
|
411
|
-
let pivotSelectedColumns: string[];
|
|
412
|
-
if (pivotColumnsRequested) {
|
|
413
|
-
pivotSelectedColumns = [...pivotColumnsRequested];
|
|
414
|
-
} else if (useIncludeDefaults) {
|
|
415
|
-
const pivotPk = relation.pivotPrimaryKey || findPrimaryKey(relation.pivotTable);
|
|
416
|
-
pivotSelectedColumns = relation.defaultPivotColumns ?? buildDefaultPivotColumns(relation, pivotPk);
|
|
417
|
-
} else {
|
|
418
|
-
pivotSelectedColumns = Object.keys(relation.pivotTable.columns);
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
const pivotQueryColumns = new Set(pivotSelectedColumns);
|
|
422
|
-
pivotQueryColumns.add(relation.pivotForeignKeyToRoot);
|
|
423
|
-
pivotQueryColumns.add(relation.pivotForeignKeyToTarget);
|
|
424
|
-
|
|
425
|
-
const pivotSelection = buildColumnSelection(
|
|
426
|
-
relation.pivotTable,
|
|
427
|
-
Array.from(pivotQueryColumns),
|
|
428
|
-
column => `Column '${column}' not found on pivot table '${relation.pivotTable.name}'`
|
|
429
|
-
);
|
|
430
|
-
|
|
431
|
-
const pivotRows = await fetchRowsForKeys(ctx, relation.pivotTable, pivotColumn, rootIds, pivotSelection);
|
|
432
|
-
const rootLookup = new Map<string, { targetId: unknown; pivot: Record<string, unknown> }[]>();
|
|
433
|
-
const targetIds = new Set<unknown>();
|
|
434
|
-
const pivotVisibleColumns = new Set(pivotSelectedColumns);
|
|
435
|
-
|
|
436
|
-
for (const pivot of pivotRows) {
|
|
437
|
-
const rootValue = pivot[relation.pivotForeignKeyToRoot];
|
|
438
|
-
const targetValue = pivot[relation.pivotForeignKeyToTarget];
|
|
439
|
-
if (rootValue === null || rootValue === undefined || targetValue === null || targetValue === undefined) {
|
|
440
|
-
continue;
|
|
441
|
-
}
|
|
442
|
-
const bucket = rootLookup.get(toKey(rootValue)) ?? [];
|
|
443
|
-
bucket.push({
|
|
444
|
-
targetId: targetValue,
|
|
445
|
-
pivot: pivotVisibleColumns.size ? filterRow(pivot, pivotVisibleColumns) : {}
|
|
446
|
-
});
|
|
447
|
-
rootLookup.set(toKey(rootValue), bucket);
|
|
448
|
-
targetIds.add(targetValue);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
if (!targetIds.size) {
|
|
452
|
-
return new Map();
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
const targetKey = relation.targetKey || findPrimaryKey(relation.target);
|
|
456
|
-
const targetPkColumn = relation.target.columns[targetKey];
|
|
457
|
-
if (!targetPkColumn) return new Map();
|
|
458
|
-
|
|
459
|
-
const targetRequestedColumns = hasColumns(options?.columns) ? [...options!.columns] : undefined;
|
|
460
|
-
const targetSelectedColumns = targetRequestedColumns
|
|
461
|
-
? [...targetRequestedColumns]
|
|
462
|
-
: Object.keys(relation.target.columns);
|
|
463
|
-
if (!targetSelectedColumns.includes(targetKey)) {
|
|
464
|
-
targetSelectedColumns.push(targetKey);
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
const targetSelection = buildColumnSelection(
|
|
468
|
-
relation.target,
|
|
469
|
-
targetSelectedColumns,
|
|
470
|
-
column => `Column '${column}' not found on relation '${relationName}'`
|
|
471
|
-
);
|
|
472
|
-
|
|
473
|
-
const targetRows = await fetchRowsForKeys(ctx, relation.target, targetPkColumn, targetIds, targetSelection, options?.filter);
|
|
474
|
-
const targetMap = groupRowsByUnique(targetRows, targetKey);
|
|
475
|
-
const targetVisibleColumns = new Set(targetSelectedColumns);
|
|
476
|
-
const result = new Map<string, Rows>();
|
|
477
|
-
|
|
478
|
-
for (const [rootId, entries] of rootLookup.entries()) {
|
|
479
|
-
const bucket: Rows = [];
|
|
480
|
-
for (const entry of entries) {
|
|
481
|
-
const targetRow = targetMap.get(toKey(entry.targetId));
|
|
482
|
-
if (!targetRow) continue;
|
|
483
|
-
bucket.push({
|
|
484
|
-
...(targetRequestedColumns ? filterRow(targetRow, targetVisibleColumns) : targetRow),
|
|
485
|
-
_pivot: entry.pivot
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
result.set(rootId, bucket);
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
return result;
|
|
492
|
-
};
|
|
1
|
+
export { loadHasManyRelation } from './lazy-batch/has-many.js';
|
|
2
|
+
export { loadHasOneRelation } from './lazy-batch/has-one.js';
|
|
3
|
+
export { loadBelongsToRelation } from './lazy-batch/belongs-to.js';
|
|
4
|
+
export { loadBelongsToManyRelation } from './lazy-batch/belongs-to-many.js';
|
|
493
5
|
|
|
@@ -28,7 +28,8 @@ const hideInternal = (obj: object, keys: string[]): void => {
|
|
|
28
28
|
*
|
|
29
29
|
* @template TTarget The type of the target entities in the collection.
|
|
30
30
|
*/
|
|
31
|
-
export class DefaultManyToManyCollection<TTarget
|
|
31
|
+
export class DefaultManyToManyCollection<TTarget, TPivot extends object | undefined = undefined>
|
|
32
|
+
implements ManyToManyCollection<TTarget, TPivot> {
|
|
32
33
|
private loaded = false;
|
|
33
34
|
private items: TTarget[] = [];
|
|
34
35
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { TableDef } from '../schema/table.js';
|
|
2
|
+
import { RelationDef } from '../schema/relation.js';
|
|
3
|
+
import { ColumnNode, ExpressionNode } from '../core/ast/expression.js';
|
|
4
|
+
import { SelectQueryNode, TableNode } from '../core/ast/query.js';
|
|
5
|
+
import { SelectQueryState } from './select-query-state.js';
|
|
6
|
+
import { QueryAstService } from './query-ast-service.js';
|
|
7
|
+
|
|
8
|
+
export class RelationCteBuilder {
|
|
9
|
+
constructor(
|
|
10
|
+
private readonly table: TableDef,
|
|
11
|
+
private readonly createQueryAstService: (table: TableDef, state: SelectQueryState) => QueryAstService
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
createFilteredRelationCte(
|
|
15
|
+
state: SelectQueryState,
|
|
16
|
+
relationName: string,
|
|
17
|
+
relation: RelationDef,
|
|
18
|
+
predicate: ExpressionNode | undefined
|
|
19
|
+
): { state: SelectQueryState; table: TableNode } {
|
|
20
|
+
const cteName = this.generateUniqueCteName(state, relationName);
|
|
21
|
+
if (!predicate) {
|
|
22
|
+
throw new Error('Unable to build filter CTE without predicates.');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const columns: ColumnNode[] = Object.keys(relation.target.columns).map(name => ({
|
|
26
|
+
type: 'Column',
|
|
27
|
+
table: relation.target.name,
|
|
28
|
+
name
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
const cteQuery: SelectQueryNode = {
|
|
32
|
+
type: 'SelectQuery',
|
|
33
|
+
from: { type: 'Table', name: relation.target.name, schema: relation.target.schema },
|
|
34
|
+
columns,
|
|
35
|
+
joins: [],
|
|
36
|
+
where: predicate
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const nextState = this.astService(state).withCte(cteName, cteQuery);
|
|
40
|
+
const tableNode: TableNode = {
|
|
41
|
+
type: 'Table',
|
|
42
|
+
name: cteName,
|
|
43
|
+
alias: relation.target.name
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
return { state: nextState, table: tableNode };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private generateUniqueCteName(state: SelectQueryState, relationName: string): string {
|
|
50
|
+
const existing = new Set((state.ast.ctes ?? []).map(cte => cte.name));
|
|
51
|
+
let candidate = `${relationName}__filtered`;
|
|
52
|
+
let suffix = 1;
|
|
53
|
+
while (existing.has(candidate)) {
|
|
54
|
+
candidate = `${relationName}__filtered_${suffix}`;
|
|
55
|
+
suffix += 1;
|
|
56
|
+
}
|
|
57
|
+
return candidate;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
private astService(state: SelectQueryState): QueryAstService {
|
|
61
|
+
return this.createQueryAstService(this.table, state);
|
|
62
|
+
}
|
|
63
|
+
}
|