peta-orm 0.2.4 → 0.2.6

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 (48) hide show
  1. package/README.md +5 -2
  2. package/dist/builder/eager-loader.d.ts.map +1 -1
  3. package/dist/builder/index.d.ts +0 -2
  4. package/dist/builder/index.d.ts.map +1 -1
  5. package/dist/builder/query-builder.d.ts +6 -12
  6. package/dist/builder/query-builder.d.ts.map +1 -1
  7. package/dist/collection/collection.d.ts.map +1 -1
  8. package/dist/collection-wwtv7qmv.js +8 -0
  9. package/dist/columns/arktype-config.d.ts +0 -4
  10. package/dist/columns/arktype-config.d.ts.map +1 -1
  11. package/dist/errors/errors.d.ts +4 -2
  12. package/dist/errors/errors.d.ts.map +1 -1
  13. package/dist/index-4xnrys72.js +56 -0
  14. package/dist/index-ddxdqxz6.js +636 -0
  15. package/dist/{index-bv1vk6ec.js → index-qb301480.js} +1 -1
  16. package/dist/{index-gacxptb4.js → index-sm1xx8gs.js} +10 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +8827 -333
  20. package/dist/migrations/cli.js +2 -2
  21. package/dist/migrations/generator.d.ts.map +1 -1
  22. package/dist/migrations/index.js +2 -2
  23. package/dist/model/model-delete.d.ts +7 -0
  24. package/dist/model/model-delete.d.ts.map +1 -0
  25. package/dist/model/model-hooks.d.ts +10 -0
  26. package/dist/model/model-hooks.d.ts.map +1 -0
  27. package/dist/model/model-relation.d.ts +7 -0
  28. package/dist/model/model-relation.d.ts.map +1 -0
  29. package/dist/model/model-save.d.ts +6 -0
  30. package/dist/model/model-save.d.ts.map +1 -0
  31. package/dist/model/model-scope.d.ts +6 -0
  32. package/dist/model/model-scope.d.ts.map +1 -0
  33. package/dist/model/model-serialize.d.ts +3 -0
  34. package/dist/model/model-serialize.d.ts.map +1 -0
  35. package/dist/model/model-state.d.ts +27 -0
  36. package/dist/model/model-state.d.ts.map +1 -0
  37. package/dist/model/model.d.ts +17 -12
  38. package/dist/model/model.d.ts.map +1 -1
  39. package/dist/{paginator-xrvkmdyk.js → paginator-tmp4hxj5.js} +2 -1
  40. package/dist/peta.d.ts.map +1 -1
  41. package/dist/relations/morph.d.ts +1 -0
  42. package/dist/relations/morph.d.ts.map +1 -1
  43. package/dist/relations/relation.d.ts +1 -0
  44. package/dist/relations/relation.d.ts.map +1 -1
  45. package/package.json +1 -1
  46. package/dist/builder/insert-builder.d.ts +0 -9
  47. package/dist/builder/insert-builder.d.ts.map +0 -1
  48. package/dist/index-676a0j9y.js +0 -9062
@@ -0,0 +1,636 @@
1
+ // @bun
2
+ import {
3
+ __require
4
+ } from "./index-k18nf2r7.js";
5
+
6
+ // src/errors/errors.ts
7
+ class ValidationError extends Error {
8
+ errors;
9
+ constructor(message, errors) {
10
+ super(message);
11
+ this.name = "ValidationError";
12
+ this.errors = errors;
13
+ }
14
+ }
15
+
16
+ class ModelNotFoundError extends Error {
17
+ modelClass;
18
+ id;
19
+ constructor(modelClass, id) {
20
+ const msg = modelClass ? `${modelClass} with id ${id} not found` : "Model not found";
21
+ super(msg);
22
+ this.name = "ModelNotFoundError";
23
+ this.modelClass = modelClass;
24
+ this.id = id;
25
+ }
26
+ }
27
+
28
+ class RelationNotFoundError extends Error {
29
+ modelClass;
30
+ relationName;
31
+ constructor(modelClass, relationName) {
32
+ const msg = modelClass ? `Relation "${relationName}" not found on ${modelClass}` : "Relation not found";
33
+ super(msg);
34
+ this.name = "RelationNotFoundError";
35
+ this.modelClass = modelClass;
36
+ this.relationName = relationName;
37
+ }
38
+ }
39
+
40
+ class ModelNotRegisteredError extends Error {
41
+ modelClass;
42
+ constructor(modelClass) {
43
+ const msg = modelClass ? `${modelClass} is not registered with Peta` : "Model not registered with Peta";
44
+ super(msg);
45
+ this.name = "ModelNotRegisteredError";
46
+ this.modelClass = modelClass;
47
+ }
48
+ }
49
+ var UNIQUE_CODES = new Set([
50
+ "SQLITE_CONSTRAINT_UNIQUE",
51
+ "SQLITE_CONSTRAINT_PRIMARYKEY",
52
+ "23505",
53
+ "ER_DUP_ENTRY"
54
+ ]);
55
+ var FOREIGN_KEY_CODES = new Set([
56
+ "SQLITE_CONSTRAINT_FOREIGNKEY",
57
+ "23503",
58
+ "ER_NO_REFERENCED_ROW_2"
59
+ ]);
60
+
61
+ class DatabaseError extends Error {
62
+ code;
63
+ cause;
64
+ table;
65
+ constructor(code, message, cause, table) {
66
+ super(message);
67
+ this.name = "DatabaseError";
68
+ this.code = code;
69
+ this.cause = cause;
70
+ this.table = table;
71
+ }
72
+ }
73
+ function normalizeError(e, table) {
74
+ if (!e || typeof e !== "object")
75
+ return null;
76
+ const err = e;
77
+ if (typeof err.code === "string") {
78
+ if (UNIQUE_CODES.has(err.code)) {
79
+ const col = typeof err.column === "string" ? ` on ${err.column}` : "";
80
+ return new DatabaseError("UNIQUE_CONSTRAINT", `Unique constraint violation${col}`, e, table);
81
+ }
82
+ if (FOREIGN_KEY_CODES.has(err.code)) {
83
+ return new DatabaseError("FOREIGN_KEY_CONSTRAINT", "Foreign key constraint violation", e, table);
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ // src/builder/delete-builder.ts
90
+ class DeleteBuilder {
91
+ #modelClass;
92
+ #kysely;
93
+ constructor(modelClass, peta, kysely) {
94
+ this.#modelClass = modelClass;
95
+ this.#kysely = kysely ?? peta.kysely;
96
+ }
97
+ async execute(id) {
98
+ try {
99
+ await this.#kysely.deleteFrom(this.#modelClass.table).where("id", "=", id).execute();
100
+ } catch (e) {
101
+ const normalized = normalizeError(e, this.#modelClass.table);
102
+ if (normalized)
103
+ throw normalized;
104
+ throw e;
105
+ }
106
+ }
107
+ }
108
+ // src/builder/eager-loader.ts
109
+ class EagerLoader {
110
+ async load(modelClass, relationData, models, names) {
111
+ for (const name of names) {
112
+ await this.#loadRelation(modelClass, relationData, models, name);
113
+ }
114
+ }
115
+ async loadRelated(models, el, modelClass) {
116
+ const { name, constraints } = el;
117
+ await this.#loadRelation(modelClass, {}, models, name, constraints);
118
+ }
119
+ async#loadRelation(modelClass, relationData, models, name, constraints) {
120
+ const dotIndex = name.indexOf(".");
121
+ if (dotIndex > 0) {
122
+ const primary = name.slice(0, dotIndex);
123
+ const nested = name.slice(dotIndex + 1);
124
+ const relation2 = modelClass.relations[primary];
125
+ if (!relation2)
126
+ throw new RelationNotFoundError(modelClass.table, primary);
127
+ await this.#loadRelation(modelClass, relationData, models, primary, null);
128
+ const allRelated = [];
129
+ for (const m of models) {
130
+ const rel = m.$getRelation(primary);
131
+ if (Array.isArray(rel))
132
+ allRelated.push(...rel);
133
+ }
134
+ if (allRelated.length > 0) {
135
+ await this.#loadRelation(relation2.relatedModelClass, {}, allRelated, nested, null);
136
+ }
137
+ return;
138
+ }
139
+ const relation = modelClass.relations[name];
140
+ if (!relation)
141
+ throw new RelationNotFoundError(modelClass.table, name);
142
+ await relation.loadEager(models, name, constraints);
143
+ }
144
+ }
145
+ // src/builder/query-builder.ts
146
+ var SAFE_COL = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;
147
+
148
+ class ModelQueryBuilder {
149
+ #modelClass;
150
+ #peta;
151
+ #kysely;
152
+ #qb;
153
+ #eagerLoads = [];
154
+ #withTrashed = false;
155
+ #onlyTrashed = false;
156
+ #omitScopes = new Set;
157
+ constructor(modelClass, peta, kysely) {
158
+ this.#modelClass = modelClass;
159
+ this.#peta = peta;
160
+ this.#kysely = kysely ?? peta.kysely;
161
+ this.#qb = this.#kysely.selectFrom(modelClass.table);
162
+ }
163
+ get peta() {
164
+ return this.#peta;
165
+ }
166
+ clone() {
167
+ const qb = new ModelQueryBuilder(this.#modelClass, this.#peta);
168
+ qb.#qb = this.#qb;
169
+ qb.#eagerLoads = [...this.#eagerLoads];
170
+ qb.#withTrashed = this.#withTrashed;
171
+ qb.#onlyTrashed = this.#onlyTrashed;
172
+ qb.#omitScopes = new Set(this.#omitScopes);
173
+ return qb;
174
+ }
175
+ withoutGlobalScope(name) {
176
+ this.#omitScopes.add(name);
177
+ return this;
178
+ }
179
+ when(condition, callback) {
180
+ if (condition)
181
+ return callback(this);
182
+ return this;
183
+ }
184
+ unless(condition, callback) {
185
+ if (!condition)
186
+ return callback(this);
187
+ return this;
188
+ }
189
+ async execute() {
190
+ const scopes = this.#modelClass.getGlobalScopes?.();
191
+ if (scopes) {
192
+ for (const [name, fn] of scopes) {
193
+ if (!this.#omitScopes.has(name)) {
194
+ fn(this);
195
+ }
196
+ }
197
+ }
198
+ if (!this.#withTrashed && "deletedAt" in this.#modelClass.columns) {
199
+ this.#qb = this.#qb.where("deletedAt", "is", null);
200
+ }
201
+ if (this.#onlyTrashed) {
202
+ this.#qb = this.#qb.where("deletedAt", "is not", null);
203
+ }
204
+ const rows = await this.#qb.selectAll().execute();
205
+ const models = rows.map((row) => this.#modelClass.hydrate(row));
206
+ if (this.#eagerLoads.length > 0) {
207
+ const loader = new EagerLoader;
208
+ for (const el of this.#eagerLoads) {
209
+ await loader.loadRelated(models, el, this.#modelClass);
210
+ }
211
+ }
212
+ return models;
213
+ }
214
+ async collect() {
215
+ const items = await this.execute();
216
+ const { Collection: Col } = await import("./collection-wwtv7qmv.js");
217
+ return new Col(items);
218
+ }
219
+ async executeTakeFirst() {
220
+ const rows = await this.execute();
221
+ return rows[0];
222
+ }
223
+ async executeTakeFirstOrThrow() {
224
+ const row = await this.executeTakeFirst();
225
+ if (!row)
226
+ throw new ModelNotFoundError(this.#modelClass.table);
227
+ return row;
228
+ }
229
+ async find(id) {
230
+ return this.clone().where("id", "=", id).executeTakeFirst();
231
+ }
232
+ async findOrFail(id) {
233
+ return this.clone().where("id", "=", id).executeTakeFirstOrThrow();
234
+ }
235
+ async first() {
236
+ return this.clone().limit(1).executeTakeFirst();
237
+ }
238
+ toSQL() {
239
+ const compiled = this.#qb.compile();
240
+ return { sql: compiled.sql, parameters: compiled.parameters };
241
+ }
242
+ async count() {
243
+ const result = await this.#qb.select((eb) => eb.fn.countAll().as("count")).executeTakeFirst();
244
+ return Number(result?.count ?? 0);
245
+ }
246
+ async sum(column) {
247
+ const result = await this.#qb.select((eb) => eb.fn.sum(column).as("sum")).executeTakeFirst();
248
+ return Number(result?.sum ?? 0);
249
+ }
250
+ async avg(column) {
251
+ const result = await this.#qb.select((eb) => eb.fn.avg(column).as("avg")).executeTakeFirst();
252
+ return Number(result?.avg ?? 0);
253
+ }
254
+ async min(column) {
255
+ const result = await this.#qb.select((eb) => eb.fn.min(column).as("min")).executeTakeFirst();
256
+ return Number(result?.min ?? 0);
257
+ }
258
+ async max(column) {
259
+ const result = await this.#qb.select((eb) => eb.fn.max(column).as("max")).executeTakeFirst();
260
+ return Number(result?.max ?? 0);
261
+ }
262
+ async chunk(size, callback) {
263
+ let page = 1;
264
+ while (true) {
265
+ const items = await this.clone().limit(size).offset((page - 1) * size).execute();
266
+ if (items.length === 0)
267
+ break;
268
+ await callback(items);
269
+ if (items.length < size)
270
+ break;
271
+ page++;
272
+ }
273
+ }
274
+ async paginate(page, perPage = 20) {
275
+ page = Math.max(1, Math.floor(page));
276
+ perPage = Math.max(1, Math.min(perPage, 1000));
277
+ const total = await this.clone().count();
278
+ const items = await this.clone().limit(perPage).offset((page - 1) * perPage).execute();
279
+ const { Paginator } = await import("./paginator-tmp4hxj5.js");
280
+ return new Paginator(items, total, perPage, page);
281
+ }
282
+ with(...relations) {
283
+ for (const arg of relations) {
284
+ if (typeof arg === "string") {
285
+ this.#eagerLoads.push({ name: arg, constraints: null });
286
+ } else if (arg && typeof arg === "object") {
287
+ for (const [name, constraints] of Object.entries(arg)) {
288
+ this.#eagerLoads.push({
289
+ name,
290
+ constraints: typeof constraints === "function" ? constraints : null
291
+ });
292
+ }
293
+ }
294
+ }
295
+ return this;
296
+ }
297
+ async updateMany(data) {
298
+ const result = await this.#kysely.updateTable(this.#modelClass.table).set(data).executeTakeFirst();
299
+ return Number(result.numUpdatedRows ?? 0);
300
+ }
301
+ async deleteMany() {
302
+ const result = await this.#kysely.deleteFrom(this.#modelClass.table).executeTakeFirst();
303
+ return Number(result.numDeletedRows ?? 0);
304
+ }
305
+ withTrashed() {
306
+ this.#withTrashed = true;
307
+ return this;
308
+ }
309
+ onlyTrashed() {
310
+ this.#withTrashed = true;
311
+ this.#onlyTrashed = true;
312
+ return this;
313
+ }
314
+ whereIn(column, values) {
315
+ if (values.length === 0) {
316
+ this.#qb = this.#qb.where("1", "=", "0");
317
+ } else {
318
+ this.#qb = this.#qb.where(column, "in", values);
319
+ }
320
+ return this;
321
+ }
322
+ whereInPivot(column, values) {
323
+ if (values.length === 0) {
324
+ this.#qb = this.#qb.where("1", "=", "0");
325
+ } else {
326
+ this.#qb = this.#qb.where(column, "in", values);
327
+ }
328
+ return this;
329
+ }
330
+ has(relationName) {
331
+ return this.#whereExists(relationName, undefined, true);
332
+ }
333
+ whereHas(relationName, _callback) {
334
+ return this.#whereExists(relationName, _callback, true);
335
+ }
336
+ whereDoesntHave(relationName, _callback) {
337
+ return this.#whereExists(relationName, _callback, false);
338
+ }
339
+ #whereExists(relationName, _callback, exists = true) {
340
+ const relation = this.#modelClass.relations[relationName];
341
+ if (!relation) {
342
+ throw new RelationNotFoundError(this.#modelClass.table, relationName);
343
+ }
344
+ const relatedTable = relation.relatedModelClass.table;
345
+ const foreignKey = relation.foreignKey;
346
+ const localKey = relation.localKey;
347
+ const subQb = this.#kysely.selectFrom(`${relatedTable} as ${relatedTable}_exists`).selectAll().whereRef(`${relatedTable}_exists.${foreignKey}`, "=", `${this.#modelClass.table}.${localKey}`);
348
+ this.#qb = this.#qb.where((eb) => exists ? eb.exists(subQb) : eb.not(eb.exists(subQb)));
349
+ return this;
350
+ }
351
+ #col(ref) {
352
+ if (!SAFE_COL.test(ref))
353
+ throw new Error(`Invalid column reference: ${ref}`);
354
+ return ref;
355
+ }
356
+ #safeWhere(column, operator, value) {
357
+ const col = this.#col(column);
358
+ this.#qb = this.#qb.where(col, operator, value);
359
+ }
360
+ where(...args) {
361
+ this.#safeWhere(String(args[0]), args[1], args[2]);
362
+ return this;
363
+ }
364
+ whereRef(col1, operator, col2) {
365
+ this.#qb = this.#qb.whereRef(this.#col(col1), operator, this.#col(col2));
366
+ return this;
367
+ }
368
+ orWhere(...args) {
369
+ this.#safeWhere(String(args[0]), args[1], args[2]);
370
+ return this;
371
+ }
372
+ orderBy(column, direction) {
373
+ const col = this.#col(column);
374
+ if (direction) {
375
+ this.#qb = this.#qb.orderBy(col, direction);
376
+ } else {
377
+ this.#qb = this.#qb.orderBy(col);
378
+ }
379
+ return this;
380
+ }
381
+ limit(n) {
382
+ this.#qb = this.#qb.limit(n);
383
+ return this;
384
+ }
385
+ offset(n) {
386
+ this.#qb = this.#qb.offset(n);
387
+ return this;
388
+ }
389
+ select(...columns) {
390
+ this.#qb = this.#qb.select(columns.map((c) => this.#col(c)));
391
+ return this;
392
+ }
393
+ selectAll(table) {
394
+ if (table) {
395
+ this.#qb = this.#qb.selectAll(this.#col(table));
396
+ } else {
397
+ this.#qb = this.#qb.selectAll();
398
+ }
399
+ return this;
400
+ }
401
+ innerJoin(table, lhs, rhs) {
402
+ this.#qb = this.#qb.innerJoin(table, this.#col(lhs), this.#col(rhs));
403
+ return this;
404
+ }
405
+ leftJoin(table, lhs, rhs) {
406
+ this.#qb = this.#qb.leftJoin(table, this.#col(lhs), this.#col(rhs));
407
+ return this;
408
+ }
409
+ groupBy(...columns) {
410
+ this.#qb = this.#qb.groupBy(columns.map((c) => this.#col(c)));
411
+ return this;
412
+ }
413
+ having(column, operator, value) {
414
+ this.#qb = this.#qb.having(this.#col(column), operator, value);
415
+ return this;
416
+ }
417
+ }
418
+ // src/builder/update-builder.ts
419
+ class UpdateBuilder {
420
+ #modelClass;
421
+ #kysely;
422
+ constructor(modelClass, peta, kysely) {
423
+ this.#modelClass = modelClass;
424
+ this.#kysely = kysely ?? peta.kysely;
425
+ }
426
+ async execute(id, data) {
427
+ const columns = this.#modelClass.columns;
428
+ for (const [key, col] of Object.entries(columns)) {
429
+ const value = data[key];
430
+ if (value !== undefined) {
431
+ try {
432
+ col.assert(value);
433
+ } catch (e) {
434
+ if (e instanceof ValidationError) {
435
+ throw new ValidationError(`${key}: ${e.message}`, e.errors);
436
+ }
437
+ throw e;
438
+ }
439
+ }
440
+ }
441
+ let row;
442
+ try {
443
+ row = await this.#kysely.updateTable(this.#modelClass.table).set(data).where("id", "=", id).returningAll().executeTakeFirst();
444
+ } catch (e) {
445
+ const normalized = normalizeError(e, this.#modelClass.table);
446
+ if (normalized)
447
+ throw normalized;
448
+ throw e;
449
+ }
450
+ if (!row)
451
+ throw new ModelNotFoundError(this.#modelClass.table, id);
452
+ return this.#modelClass.hydrate(row);
453
+ }
454
+ }
455
+ // src/collection/collection.ts
456
+ class Collection {
457
+ #items = [];
458
+ constructor(items = []) {
459
+ this.#items = [...items];
460
+ }
461
+ get length() {
462
+ return this.#items.length;
463
+ }
464
+ [Symbol.iterator]() {
465
+ return this.#items[Symbol.iterator]();
466
+ }
467
+ at(index) {
468
+ return this.#items[index];
469
+ }
470
+ first() {
471
+ return this.#items[0];
472
+ }
473
+ last() {
474
+ return this.#items[this.#items.length - 1];
475
+ }
476
+ all() {
477
+ return [...this.#items];
478
+ }
479
+ findBy(id) {
480
+ return this.#items.find((item) => item.get("id") === id);
481
+ }
482
+ pluck(key) {
483
+ return this.#items.map((item) => item.get(key));
484
+ }
485
+ groupBy(key) {
486
+ const result = {};
487
+ for (const item of this.#items) {
488
+ const k = String(item.get(key));
489
+ if (!result[k])
490
+ result[k] = [];
491
+ result[k].push(item);
492
+ }
493
+ return result;
494
+ }
495
+ keyBy(key) {
496
+ const result = {};
497
+ for (const item of this.#items) {
498
+ const k = String(item.get(key));
499
+ result[k] = item;
500
+ }
501
+ return result;
502
+ }
503
+ toJSON() {
504
+ return this.#items.map((item) => item.$toJSON());
505
+ }
506
+ map(fn) {
507
+ return this.#items.map(fn);
508
+ }
509
+ filter(fn) {
510
+ return new Collection(this.#items.filter(fn));
511
+ }
512
+ reduce(fn, initial) {
513
+ return this.#items.reduce(fn, initial);
514
+ }
515
+ forEach(fn) {
516
+ this.#items.forEach(fn);
517
+ }
518
+ find(fn) {
519
+ return this.#items.find(fn);
520
+ }
521
+ some(fn) {
522
+ return this.#items.some(fn);
523
+ }
524
+ includes(item) {
525
+ return this.#items.includes(item);
526
+ }
527
+ async load(...relations) {
528
+ if (this.#items.length === 0)
529
+ return this;
530
+ const modelClass = this.#items[0].constructor;
531
+ const loader = new EagerLoader;
532
+ await loader.load(modelClass, {}, this.#items, relations);
533
+ return this;
534
+ }
535
+ get(key) {
536
+ return this.#items.map((item) => item.get(key));
537
+ }
538
+ isEmpty() {
539
+ return this.#items.length === 0;
540
+ }
541
+ isNotEmpty() {
542
+ return this.#items.length > 0;
543
+ }
544
+ sum(key) {
545
+ return this.#items.reduce((acc, item) => acc + (Number(item.get(key)) || 0), 0);
546
+ }
547
+ avg(key) {
548
+ if (this.#items.length === 0)
549
+ return 0;
550
+ return this.sum(key) / this.#items.length;
551
+ }
552
+ min(key) {
553
+ const values = this.pluck(key);
554
+ if (values.length === 0)
555
+ return;
556
+ return Math.min(...values.filter((v) => typeof v === "number"));
557
+ }
558
+ max(key) {
559
+ const values = this.pluck(key);
560
+ if (values.length === 0)
561
+ return;
562
+ return Math.max(...values.filter((v) => typeof v === "number"));
563
+ }
564
+ contains(value, key) {
565
+ if (key) {
566
+ return this.#items.some((item) => item.get(key) === value);
567
+ }
568
+ return this.#items.some((item) => item === value);
569
+ }
570
+ unique(key) {
571
+ const seen = new Set;
572
+ return new Collection(this.#items.filter((item) => {
573
+ const val = item.get(key);
574
+ if (seen.has(val))
575
+ return false;
576
+ seen.add(val);
577
+ return true;
578
+ }));
579
+ }
580
+ sortBy(key, direction = "asc") {
581
+ const items = [...this.#items].sort((a, b) => {
582
+ const av = String(a.get(key));
583
+ const bv = String(b.get(key));
584
+ if (av < bv)
585
+ return direction === "asc" ? -1 : 1;
586
+ if (av > bv)
587
+ return direction === "asc" ? 1 : -1;
588
+ return 0;
589
+ });
590
+ return new Collection(items);
591
+ }
592
+ shuffle() {
593
+ const items = [...this.#items];
594
+ for (let i = items.length - 1;i > 0; i--) {
595
+ const j = Math.floor(Math.random() * (i + 1));
596
+ const tmp = items[i];
597
+ items[i] = items[j];
598
+ items[j] = tmp;
599
+ }
600
+ return new Collection(items);
601
+ }
602
+ take(n) {
603
+ return new Collection(this.#items.slice(0, n));
604
+ }
605
+ skip(n) {
606
+ return new Collection(this.#items.slice(n));
607
+ }
608
+ chunk(size) {
609
+ const chunks = [];
610
+ for (let i = 0;i < this.#items.length; i += size) {
611
+ chunks.push(new Collection(this.#items.slice(i, i + size)));
612
+ }
613
+ return chunks;
614
+ }
615
+ each(fn) {
616
+ this.#items.forEach(fn);
617
+ return this;
618
+ }
619
+ diff(other) {
620
+ const ids = new Set(other.pluck("id"));
621
+ return new Collection(this.#items.filter((item) => !ids.has(item.get("id"))));
622
+ }
623
+ intersect(other) {
624
+ const ids = new Set(other.pluck("id"));
625
+ return new Collection(this.#items.filter((item) => ids.has(item.get("id"))));
626
+ }
627
+ push(...items) {
628
+ this.#items.push(...items);
629
+ }
630
+ concat(other) {
631
+ const otherItems = other instanceof Collection ? other.all() : other;
632
+ return new Collection([...this.#items, ...otherItems]);
633
+ }
634
+ }
635
+
636
+ export { ValidationError, ModelNotFoundError, RelationNotFoundError, ModelNotRegisteredError, DatabaseError, normalizeError, DeleteBuilder, EagerLoader, Collection, ModelQueryBuilder, UpdateBuilder };
@@ -31,7 +31,7 @@ import {
31
31
  parseTable,
32
32
  parseValueExpression,
33
33
  preventAwait
34
- } from "./index-gacxptb4.js";
34
+ } from "./index-sm1xx8gs.js";
35
35
  import {
36
36
  __require
37
37
  } from "./index-k18nf2r7.js";
@@ -7473,7 +7473,8 @@ function validateTransactionSettings(settings) {
7473
7473
  // src/peta.ts
7474
7474
  import { resolve } from "path";
7475
7475
  function isModelClass(value) {
7476
- return typeof value === "function" && typeof value.table === "string" && value.table.length > 0 && typeof value.columns === "object" && value.columns !== null;
7476
+ const v = value;
7477
+ return typeof value === "function" && typeof v.table === "string" && v.table.length > 0 && typeof v.columns === "object" && v.columns !== null;
7477
7478
  }
7478
7479
 
7479
7480
  class Peta {
@@ -7570,6 +7571,14 @@ class Relation {
7570
7571
  get relatedModelClass() {
7571
7572
  return resolve2(this.#relatedThunk);
7572
7573
  }
7574
+ async loadEager(models, relationName, constraints) {
7575
+ const qb = this.relatedModelClass.query();
7576
+ this.addEagerConstraints(qb, models);
7577
+ if (constraints)
7578
+ constraints(qb);
7579
+ const results = await qb.execute();
7580
+ this.match(models, results, relationName);
7581
+ }
7573
7582
  }
7574
7583
 
7575
7584
  class HasMany extends Relation {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type { WithArg } from "./builder";
2
- export { DeleteBuilder, EagerLoader, InsertBuilder, ModelQueryBuilder, UpdateBuilder } from "./builder";
2
+ export { DeleteBuilder, EagerLoader, ModelQueryBuilder, UpdateBuilder } from "./builder";
3
3
  export { Collection } from "./collection/collection";
4
4
  export { ArkTypeSchemaConfig } from "./columns/arktype-config";
5
5
  export type { ColumnShape, ColumnValue } from "./columns/column";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACxC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AACvG,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAC9D,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,YAAY,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,EAAE,EAAE,EAAE,MAA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