@mikro-orm/core 7.0.0-dev.66 → 7.0.0-dev.68

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.
@@ -1,118 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import type { EntityDTO, EntityProperty, IPrimaryKey, Primary } from '../typings.js';
3
- import { Reference } from './Reference.js';
4
- export declare class ArrayCollection<T extends object, O extends object> {
5
- readonly owner: O;
6
- protected readonly items: Set<T>;
7
- protected initialized: boolean;
8
- protected dirty: boolean;
9
- protected partial: boolean;
10
- protected snapshot: T[] | undefined;
11
- protected _count?: number;
12
- private _property?;
13
- constructor(owner: O, items?: T[]);
14
- loadCount(): Promise<number>;
15
- getItems(): T[];
16
- toArray<TT extends T>(): EntityDTO<TT>[];
17
- toJSON(): EntityDTO<T>[];
18
- getIdentifiers<U extends IPrimaryKey = Primary<T> & IPrimaryKey>(field?: string | string[]): U[];
19
- add(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): number;
20
- /**
21
- * @internal
22
- */
23
- addWithoutPropagation(entity: T): void;
24
- set(items: Iterable<T | Reference<T>>): void;
25
- private compare;
26
- /**
27
- * @internal
28
- */
29
- hydrate(items: T[], forcePropagate?: boolean, partial?: boolean): void;
30
- /**
31
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
32
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
33
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
34
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
35
- */
36
- remove(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): number;
37
- /**
38
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
39
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
40
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
41
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
42
- */
43
- removeAll(): void;
44
- /**
45
- * @internal
46
- */
47
- removeWithoutPropagation(entity: T): void;
48
- contains(item: T | Reference<T>, check?: boolean): boolean;
49
- /**
50
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
51
- * If end is null it returns all elements from start to the end of the collection.
52
- */
53
- slice(start?: number, end?: number): T[];
54
- /**
55
- * Tests for the existence of an element that satisfies the given predicate.
56
- */
57
- exists(cb: (item: T) => boolean): boolean;
58
- /**
59
- * Returns the first element of this collection that satisfies the predicate.
60
- */
61
- find(cb: (item: T, index: number) => boolean): T | undefined;
62
- /**
63
- * Extracts a subset of the collection items.
64
- */
65
- filter(cb: (item: T, index: number) => boolean): T[];
66
- /**
67
- * Maps the collection items based on your provided mapper function.
68
- */
69
- map<R>(mapper: (item: T, index: number) => R): R[];
70
- /**
71
- * Maps the collection items based on your provided mapper function to a single object.
72
- */
73
- reduce<R>(cb: (obj: R, item: T, index: number) => R, initial?: R): R;
74
- /**
75
- * Maps the collection items to a dictionary, indexed by the key you specify.
76
- * If there are more items with the same key, only the first one will be present.
77
- */
78
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1): Record<T[K1] & PropertyKey, T>;
79
- /**
80
- * Maps the collection items to a dictionary, indexed by the key you specify.
81
- * If there are more items with the same key, only the first one will be present.
82
- */
83
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1, valueKey: K2): Record<T[K1] & PropertyKey, T[K2]>;
84
- count(): number;
85
- isInitialized(fully?: boolean): boolean;
86
- isDirty(): boolean;
87
- isPartial(): boolean;
88
- isEmpty(): boolean;
89
- setDirty(dirty?: boolean): void;
90
- get length(): number;
91
- [Symbol.iterator](): IterableIterator<T>;
92
- /**
93
- * @internal
94
- */
95
- takeSnapshot(forcePropagate?: boolean): void;
96
- /**
97
- * @internal
98
- */
99
- getSnapshot(): T[] | undefined;
100
- /**
101
- * @internal
102
- */
103
- get property(): EntityProperty;
104
- /**
105
- * @internal
106
- */
107
- set property(prop: EntityProperty);
108
- protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
109
- protected propagateToInverseSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
110
- protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
111
- protected shouldPropagateToCollection(collection: ArrayCollection<O, T>, method: 'add' | 'remove' | 'takeSnapshot'): boolean;
112
- protected incrementCount(value: number): void;
113
- /** @ignore */
114
- [inspect.custom](depth?: number): string;
115
- }
116
- export interface ArrayCollection<T, O> {
117
- [k: number]: T;
118
- }
@@ -1,410 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import { Reference } from './Reference.js';
3
- import { helper, wrap } from './wrap.js';
4
- import { MetadataError, ValidationError } from '../errors.js';
5
- import { ReferenceKind } from '../enums.js';
6
- import { Utils } from '../utils/Utils.js';
7
- export class ArrayCollection {
8
- owner;
9
- items = new Set();
10
- initialized = true;
11
- dirty = false;
12
- partial = false; // mark partially loaded collections, propagation is disabled for those
13
- snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
14
- _count;
15
- _property;
16
- constructor(owner, items) {
17
- this.owner = owner;
18
- /* v8 ignore next 5 */
19
- if (items) {
20
- let i = 0;
21
- this.items = new Set(items);
22
- this.items.forEach(item => this[i++] = item);
23
- }
24
- }
25
- async loadCount() {
26
- return this.items.size;
27
- }
28
- getItems() {
29
- return [...this.items];
30
- }
31
- toArray() {
32
- if (this.items.size === 0) {
33
- return [];
34
- }
35
- return this.map(item => wrap(item).toJSON());
36
- }
37
- toJSON() {
38
- return this.toArray();
39
- }
40
- getIdentifiers(field) {
41
- const items = this.getItems();
42
- const targetMeta = this.property.targetMeta;
43
- if (items.length === 0) {
44
- return [];
45
- }
46
- field ??= targetMeta.compositePK ? targetMeta.primaryKeys : (targetMeta.serializedPrimaryKey ?? targetMeta.primaryKeys[0]);
47
- const cb = (i, f) => {
48
- if (Utils.isEntity(i[f], true)) {
49
- return wrap(i[f], true).getPrimaryKey();
50
- }
51
- return i[f];
52
- };
53
- return items.map(i => {
54
- if (Array.isArray(field)) {
55
- return field.map(f => cb(i, f));
56
- }
57
- return cb(i, field);
58
- });
59
- }
60
- add(entity, ...entities) {
61
- entities = Utils.asArray(entity).concat(entities);
62
- let added = 0;
63
- for (const item of entities) {
64
- const entity = Reference.unwrapReference(item);
65
- if (!this.contains(entity, false)) {
66
- this.incrementCount(1);
67
- this[this.items.size] = entity;
68
- this.items.add(entity);
69
- added++;
70
- this.propagate(entity, 'add');
71
- }
72
- }
73
- return added;
74
- }
75
- /**
76
- * @internal
77
- */
78
- addWithoutPropagation(entity) {
79
- if (!this.contains(entity, false)) {
80
- this.incrementCount(1);
81
- this[this.items.size] = entity;
82
- this.items.add(entity);
83
- this.dirty = true;
84
- }
85
- }
86
- set(items) {
87
- if (!this.initialized) {
88
- this.initialized = true;
89
- this.snapshot = undefined;
90
- }
91
- if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
92
- return;
93
- }
94
- this.remove(this.items);
95
- this.add(items);
96
- }
97
- compare(items) {
98
- if (items.length !== this.items.size) {
99
- return false;
100
- }
101
- let idx = 0;
102
- for (const item of this.items) {
103
- if (item !== items[idx++]) {
104
- return false;
105
- }
106
- }
107
- return true;
108
- }
109
- /**
110
- * @internal
111
- */
112
- hydrate(items, forcePropagate, partial) {
113
- for (let i = 0; i < this.items.size; i++) {
114
- delete this[i];
115
- }
116
- this.initialized = true;
117
- this.partial = !!partial;
118
- this.items.clear();
119
- this._count = 0;
120
- this.add(items);
121
- this.takeSnapshot(forcePropagate);
122
- }
123
- /**
124
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
125
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
126
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
127
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
128
- */
129
- remove(entity, ...entities) {
130
- entities = Utils.asArray(entity).concat(entities);
131
- let removed = 0;
132
- for (const item of entities) {
133
- if (!item) {
134
- continue;
135
- }
136
- const entity = Reference.unwrapReference(item);
137
- if (this.items.delete(entity)) {
138
- this.incrementCount(-1);
139
- delete this[this.items.size]; // remove last item
140
- this.propagate(entity, 'remove');
141
- removed++;
142
- }
143
- }
144
- if (removed > 0) {
145
- Object.assign(this, [...this.items]); // reassign array access
146
- }
147
- return removed;
148
- }
149
- /**
150
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
151
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
152
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
153
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
154
- */
155
- removeAll() {
156
- if (!this.initialized) {
157
- this.initialized = true;
158
- this.snapshot = undefined;
159
- }
160
- this.remove(this.items);
161
- this.setDirty();
162
- }
163
- /**
164
- * @internal
165
- */
166
- removeWithoutPropagation(entity) {
167
- if (!this.items.delete(entity)) {
168
- return;
169
- }
170
- this.incrementCount(-1);
171
- delete this[this.items.size];
172
- Object.assign(this, [...this.items]);
173
- this.dirty = true;
174
- }
175
- contains(item, check) {
176
- const entity = Reference.unwrapReference(item);
177
- return this.items.has(entity);
178
- }
179
- /**
180
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
181
- * If end is null it returns all elements from start to the end of the collection.
182
- */
183
- slice(start = 0, end) {
184
- let index = 0;
185
- end ??= this.items.size;
186
- const items = [];
187
- for (const item of this.items) {
188
- if (index === end) {
189
- break;
190
- }
191
- if (index >= start && index < end) {
192
- items.push(item);
193
- }
194
- index++;
195
- }
196
- return items;
197
- }
198
- /**
199
- * Tests for the existence of an element that satisfies the given predicate.
200
- */
201
- exists(cb) {
202
- for (const item of this.items) {
203
- if (cb(item)) {
204
- return true;
205
- }
206
- }
207
- return false;
208
- }
209
- /**
210
- * Returns the first element of this collection that satisfies the predicate.
211
- */
212
- find(cb) {
213
- let index = 0;
214
- for (const item of this.items) {
215
- if (cb(item, index++)) {
216
- return item;
217
- }
218
- }
219
- return undefined;
220
- }
221
- /**
222
- * Extracts a subset of the collection items.
223
- */
224
- filter(cb) {
225
- const items = [];
226
- let index = 0;
227
- for (const item of this.items) {
228
- if (cb(item, index++)) {
229
- items.push(item);
230
- }
231
- }
232
- return items;
233
- }
234
- /**
235
- * Maps the collection items based on your provided mapper function.
236
- */
237
- map(mapper) {
238
- const items = [];
239
- let index = 0;
240
- for (const item of this.items) {
241
- items.push(mapper(item, index++));
242
- }
243
- return items;
244
- }
245
- /**
246
- * Maps the collection items based on your provided mapper function to a single object.
247
- */
248
- reduce(cb, initial = {}) {
249
- let index = 0;
250
- for (const item of this.items) {
251
- initial = cb(initial, item, index++);
252
- }
253
- return initial;
254
- }
255
- /**
256
- * Maps the collection items to a dictionary, indexed by the key you specify.
257
- * If there are more items with the same key, only the first one will be present.
258
- */
259
- indexBy(key, valueKey) {
260
- return this.reduce((obj, item) => {
261
- obj[item[key]] ??= valueKey ? item[valueKey] : item;
262
- return obj;
263
- }, {});
264
- }
265
- count() {
266
- return this.items.size;
267
- }
268
- isInitialized(fully = false) {
269
- if (!this.initialized || !fully) {
270
- return this.initialized;
271
- }
272
- for (const item of this.items) {
273
- if (!helper(item).__initialized) {
274
- return false;
275
- }
276
- }
277
- return true;
278
- }
279
- isDirty() {
280
- return this.dirty;
281
- }
282
- isPartial() {
283
- return this.partial;
284
- }
285
- isEmpty() {
286
- return this.count() === 0;
287
- }
288
- setDirty(dirty = true) {
289
- this.dirty = dirty;
290
- }
291
- get length() {
292
- return this.count();
293
- }
294
- *[Symbol.iterator]() {
295
- for (const item of this.getItems()) {
296
- yield item;
297
- }
298
- }
299
- /**
300
- * @internal
301
- */
302
- takeSnapshot(forcePropagate) {
303
- this.snapshot = [...this.items];
304
- this.setDirty(false);
305
- if (this.property.owner || forcePropagate) {
306
- this.items.forEach(item => {
307
- this.propagate(item, 'takeSnapshot');
308
- });
309
- }
310
- }
311
- /**
312
- * @internal
313
- */
314
- getSnapshot() {
315
- return this.snapshot;
316
- }
317
- /**
318
- * @internal
319
- */
320
- get property() {
321
- if (!this._property) {
322
- const meta = wrap(this.owner, true).__meta;
323
- /* v8 ignore next 3 */
324
- if (!meta) {
325
- throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
326
- }
327
- this._property = meta.relations.find(prop => this.owner[prop.name] === this);
328
- }
329
- return this._property;
330
- }
331
- /**
332
- * @internal
333
- */
334
- set property(prop) {
335
- this._property = prop;
336
- }
337
- propagate(item, method) {
338
- if (this.property.owner && this.property.inversedBy) {
339
- this.propagateToInverseSide(item, method);
340
- }
341
- else if (!this.property.owner && this.property.mappedBy) {
342
- this.propagateToOwningSide(item, method);
343
- }
344
- }
345
- propagateToInverseSide(item, method) {
346
- const collection = item[this.property.inversedBy];
347
- if (this.shouldPropagateToCollection(collection, method)) {
348
- method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
349
- collection[method](this.owner);
350
- }
351
- }
352
- propagateToOwningSide(item, method) {
353
- const mappedBy = this.property.mappedBy;
354
- const collection = item[mappedBy];
355
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
356
- if (this.shouldPropagateToCollection(collection, method)) {
357
- collection[method](this.owner);
358
- }
359
- }
360
- else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
361
- const prop2 = this.property.targetMeta.properties[mappedBy];
362
- const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
363
- const value = method === 'add' ? owner : null;
364
- if (this.property.orphanRemoval && method === 'remove') {
365
- // cache the PK before we propagate, as its value might be needed when flushing
366
- helper(item).__pk = helper(item).getPrimaryKey();
367
- }
368
- if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
369
- if (!this.property.orphanRemoval) {
370
- throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
371
- }
372
- return;
373
- }
374
- // skip if already propagated
375
- if (Reference.unwrapReference(item[mappedBy]) !== value) {
376
- item[mappedBy] = value;
377
- }
378
- }
379
- }
380
- shouldPropagateToCollection(collection, method) {
381
- if (!collection) {
382
- return false;
383
- }
384
- switch (method) {
385
- case 'add':
386
- return !collection.contains(this.owner, false);
387
- case 'remove':
388
- return collection.isInitialized() && collection.contains(this.owner, false);
389
- case 'takeSnapshot':
390
- return collection.isDirty();
391
- }
392
- }
393
- incrementCount(value) {
394
- if (typeof this._count === 'number' && this.initialized) {
395
- this._count += value;
396
- }
397
- }
398
- /** @ignore */
399
- [inspect.custom](depth = 2) {
400
- const object = { ...this };
401
- const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly', 'partial'];
402
- hidden.forEach(k => delete object[k]);
403
- const ret = inspect(object, { depth });
404
- const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
405
- return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
406
- }
407
- }
408
- Object.defineProperties(ArrayCollection.prototype, {
409
- __collection: { value: true, enumerable: false, writable: false },
410
- });