@orieljs/database 0.1.0-alpha.15 → 0.1.0-alpha.16
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 +3 -1
- package/dist/index.d.ts +2027 -1770
- package/dist/index.js +238 -135
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -239,7 +239,7 @@ function rawWithBindings(query, bindings = []) {
|
|
|
239
239
|
|
|
240
240
|
// Query/Builder.ts
|
|
241
241
|
import { sql as sql3 } from "kysely";
|
|
242
|
-
import { Collection as
|
|
242
|
+
import { Collection as Collection2, LazyCollection } from "@orieljs/collections";
|
|
243
243
|
|
|
244
244
|
// Pagination/AbstractPaginator.ts
|
|
245
245
|
import { Collection } from "@orieljs/collections";
|
|
@@ -257,11 +257,12 @@ function buildQuery(values, prefix) {
|
|
|
257
257
|
}
|
|
258
258
|
return parts.join("&");
|
|
259
259
|
}
|
|
260
|
+
var isModelLike = (value) => typeof value === "object" && value !== null && typeof value.getKey === "function" && typeof value.getAttributes === "function";
|
|
260
261
|
var isArrayable = (value) => typeof value === "object" && value !== null && typeof value.toArray === "function";
|
|
261
262
|
var AbstractPaginator = class _AbstractPaginator {
|
|
262
263
|
constructor(items, perPageValue, options, currentPage) {
|
|
263
264
|
this.perPageValue = perPageValue;
|
|
264
|
-
this.collection = new Collection(items);
|
|
265
|
+
this.collection = items instanceof Collection ? items : new Collection(items);
|
|
265
266
|
const path = options.path ?? _AbstractPaginator.resolveCurrentPath();
|
|
266
267
|
this.pathValue = path !== "/" ? path.replace(/\/+$/, "") : path;
|
|
267
268
|
this.queryValues = { ...options.query ?? {} };
|
|
@@ -360,6 +361,7 @@ var AbstractPaginator = class _AbstractPaginator {
|
|
|
360
361
|
items() {
|
|
361
362
|
return this.collection.all();
|
|
362
363
|
}
|
|
364
|
+
/** The items on this page: an Eloquent query's in its models' Eloquent collection, as Laravel's. */
|
|
363
365
|
getCollection() {
|
|
364
366
|
return this.collection;
|
|
365
367
|
}
|
|
@@ -372,7 +374,9 @@ var AbstractPaginator = class _AbstractPaginator {
|
|
|
372
374
|
* `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
|
|
373
375
|
*/
|
|
374
376
|
through(callback) {
|
|
375
|
-
|
|
377
|
+
const mapped = this.collection.all().map(callback);
|
|
378
|
+
const eloquent = typeof this.collection.modelKeys === "function" && mapped.every(isModelLike);
|
|
379
|
+
this.collection = eloquent ? new this.collection.constructor(mapped) : new Collection(mapped);
|
|
376
380
|
return this;
|
|
377
381
|
}
|
|
378
382
|
perPage() {
|
|
@@ -402,7 +406,6 @@ var AbstractPaginator = class _AbstractPaginator {
|
|
|
402
406
|
};
|
|
403
407
|
|
|
404
408
|
// Pagination/CursorPaginator.ts
|
|
405
|
-
import { Collection as Collection2 } from "@orieljs/collections";
|
|
406
409
|
var Cursor = class _Cursor {
|
|
407
410
|
constructor(parameters, pointsToNext = true) {
|
|
408
411
|
this.parameters = parameters;
|
|
@@ -457,7 +460,7 @@ var CursorPaginator = class extends AbstractPaginator {
|
|
|
457
460
|
this.parameters = options.parameters;
|
|
458
461
|
this.hasMore = this.collection.count() > perPage;
|
|
459
462
|
this.collection = this.collection.slice(0, perPage);
|
|
460
|
-
if (cursorValue?.pointsToPreviousItems()) this.collection =
|
|
463
|
+
if (cursorValue?.pointsToPreviousItems()) this.collection = this.collection.reverse();
|
|
461
464
|
}
|
|
462
465
|
cursorValue;
|
|
463
466
|
hasMore;
|
|
@@ -1320,7 +1323,7 @@ var Builder = class _Builder {
|
|
|
1320
1323
|
}
|
|
1321
1324
|
/** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
|
|
1322
1325
|
newCollection(items) {
|
|
1323
|
-
return new
|
|
1326
|
+
return new Collection2(items);
|
|
1324
1327
|
}
|
|
1325
1328
|
/** The raw rows, without a Collection around them. */
|
|
1326
1329
|
async runSelect() {
|
|
@@ -1353,7 +1356,7 @@ var Builder = class _Builder {
|
|
|
1353
1356
|
async pluck(column) {
|
|
1354
1357
|
const rows = await this.clone().select(column).runSelect();
|
|
1355
1358
|
const key = columnKey(column);
|
|
1356
|
-
return new
|
|
1359
|
+
return new Collection2(rows.map((row) => row[key]));
|
|
1357
1360
|
}
|
|
1358
1361
|
async count(column = "*") {
|
|
1359
1362
|
return Number(await this.aggregate("count", column) ?? 0);
|
|
@@ -1453,14 +1456,14 @@ var Builder = class _Builder {
|
|
|
1453
1456
|
const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
|
|
1454
1457
|
const total = await this.clone().count();
|
|
1455
1458
|
const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : [];
|
|
1456
|
-
return new LengthAwarePaginator(items, total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
|
|
1459
|
+
return new LengthAwarePaginator(this.newCollection(items), total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
|
|
1457
1460
|
}
|
|
1458
1461
|
/** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
|
|
1459
1462
|
async simplePaginate(perPage, columns = ["*"], pageName = "page", page) {
|
|
1460
1463
|
const size = perPage ?? this.defaultPerPage();
|
|
1461
1464
|
const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
|
|
1462
1465
|
const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect();
|
|
1463
|
-
return new Paginator(items, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
|
|
1466
|
+
return new Paginator(this.newCollection(items), size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
|
|
1464
1467
|
}
|
|
1465
1468
|
/**
|
|
1466
1469
|
* Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
|
|
@@ -1473,7 +1476,7 @@ var Builder = class _Builder {
|
|
|
1473
1476
|
const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false);
|
|
1474
1477
|
if (current) query.whereCursor(current, orders, 0);
|
|
1475
1478
|
const items = await query.limit(size + 1).runSelect();
|
|
1476
|
-
return new CursorPaginator(items, size, current, {
|
|
1479
|
+
return new CursorPaginator(this.newCollection(items), size, current, {
|
|
1477
1480
|
path: AbstractPaginator.resolveCurrentPath(),
|
|
1478
1481
|
cursorName,
|
|
1479
1482
|
parameters: orders.map((order) => String(order.column))
|
|
@@ -3066,6 +3069,9 @@ var SchemaBuilder = class _SchemaBuilder {
|
|
|
3066
3069
|
};
|
|
3067
3070
|
|
|
3068
3071
|
// Connection.ts
|
|
3072
|
+
function holdsCallbacks(frame) {
|
|
3073
|
+
return frame !== void 0 && frame.ignoresCallbacks !== true;
|
|
3074
|
+
}
|
|
3069
3075
|
var Connection = class {
|
|
3070
3076
|
constructor(name, config) {
|
|
3071
3077
|
this.name = name;
|
|
@@ -3151,24 +3157,108 @@ var Connection = class {
|
|
|
3151
3157
|
try {
|
|
3152
3158
|
result = await this.context.run(frame, () => fn(this));
|
|
3153
3159
|
} catch (error) {
|
|
3154
|
-
|
|
3160
|
+
try {
|
|
3161
|
+
await this.close(frame, "rollback");
|
|
3162
|
+
} finally {
|
|
3163
|
+
await this.rolledBack(frame);
|
|
3164
|
+
}
|
|
3155
3165
|
throw error;
|
|
3156
3166
|
}
|
|
3157
|
-
|
|
3167
|
+
try {
|
|
3168
|
+
await this.close(frame, "commit");
|
|
3169
|
+
} catch (error) {
|
|
3170
|
+
await this.rolledBack(frame);
|
|
3171
|
+
throw error;
|
|
3172
|
+
}
|
|
3173
|
+
await this.committed(frame);
|
|
3158
3174
|
return result;
|
|
3159
3175
|
}
|
|
3176
|
+
/** A committed level hands its callbacks to the transaction(fn) it's nested in, or runs them, outside its context. */
|
|
3177
|
+
async committed(frame) {
|
|
3178
|
+
frame.ended = "commit";
|
|
3179
|
+
if (holdsCallbacks(frame.parent)) {
|
|
3180
|
+
frame.parent.callbacks.push(...frame.callbacks.splice(0));
|
|
3181
|
+
frame.parent.rollbacks.push(...frame.rollbacks.splice(0));
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
3184
|
+
frame.rollbacks.length = 0;
|
|
3185
|
+
for (const callback of frame.callbacks.splice(0)) await this.context.exit(() => callback());
|
|
3186
|
+
}
|
|
3187
|
+
/** A level that rolled back drops its callbacks and runs its onRollBack ones, outside its context. */
|
|
3188
|
+
async rolledBack(frame) {
|
|
3189
|
+
frame.ended = "rollback";
|
|
3190
|
+
frame.callbacks.length = 0;
|
|
3191
|
+
for (const callback of frame.rollbacks.splice(0)) await this.runQuietly(callback);
|
|
3192
|
+
}
|
|
3193
|
+
/** An onRollBack callback's failure must not hide the error that rolled the transaction back. */
|
|
3194
|
+
async runQuietly(callback) {
|
|
3195
|
+
try {
|
|
3196
|
+
await this.context.exit(() => callback());
|
|
3197
|
+
} catch {
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3160
3200
|
/** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */
|
|
3161
3201
|
async beginTransaction() {
|
|
3162
|
-
|
|
3202
|
+
const frame = await this.open();
|
|
3203
|
+
frame.pinned = true;
|
|
3204
|
+
this.pinned.push(frame);
|
|
3163
3205
|
}
|
|
3206
|
+
/**
|
|
3207
|
+
* @internal RefreshDatabase's and DatabaseTransactions': the level beginTransaction() just opened holds no
|
|
3208
|
+
* afterCommit() callbacks, so they run as they would without the test's transaction (Laravel's
|
|
3209
|
+
* callbacksShouldIgnore()), and a test's own transaction(fn) or beginTransaction() runs them at its commit.
|
|
3210
|
+
*/
|
|
3211
|
+
ignoreAfterCommitAtCurrentLevel() {
|
|
3212
|
+
const frame = this.pinned.at(-1);
|
|
3213
|
+
if (frame) frame.ignoresCallbacks = true;
|
|
3214
|
+
}
|
|
3215
|
+
/**
|
|
3216
|
+
* Laravel's DB::afterCommit(): runs the callback once the transaction open here commits, the outermost one when
|
|
3217
|
+
* they're nested, and drops it if that level rolls back: a transaction(fn) open in this async context, or a level
|
|
3218
|
+
* beginTransaction() opened. Outside one, or in only the testing traits' transaction, it runs at once.
|
|
3219
|
+
* `onRollBack` runs instead when the level that holds the callback rolls back. A callback added once its level has
|
|
3220
|
+
* ended (by work nobody awaited) follows it: held by the level it was committed into, run if the commit is done,
|
|
3221
|
+
* dropped if it rolled back.
|
|
3222
|
+
*/
|
|
3223
|
+
async afterCommit(callback, onRollBack) {
|
|
3224
|
+
let frame = this.context.getStore() ?? this.pinned.at(-1);
|
|
3225
|
+
while (frame?.ended === "commit") frame = holdsCallbacks(frame.parent) ? frame.parent : void 0;
|
|
3226
|
+
if (!holdsCallbacks(frame)) {
|
|
3227
|
+
await callback();
|
|
3228
|
+
return;
|
|
3229
|
+
}
|
|
3230
|
+
if (frame.ended === "rollback") {
|
|
3231
|
+
if (onRollBack !== void 0) await this.runQuietly(onRollBack);
|
|
3232
|
+
return;
|
|
3233
|
+
}
|
|
3234
|
+
frame.callbacks.push(callback);
|
|
3235
|
+
if (onRollBack !== void 0) frame.rollbacks.push(onRollBack);
|
|
3236
|
+
}
|
|
3237
|
+
/** @internal Whether a transaction is open here that afterCommit() would wait for. */
|
|
3238
|
+
inTransactionContext() {
|
|
3239
|
+
return holdsCallbacks(this.context.getStore() ?? this.pinned.at(-1));
|
|
3240
|
+
}
|
|
3241
|
+
/** Commits the innermost level opened by beginTransaction(), then runs (or hands up) its afterCommit() callbacks. */
|
|
3164
3242
|
async commit() {
|
|
3165
3243
|
const frame = this.pinned.pop();
|
|
3166
|
-
if (frame)
|
|
3244
|
+
if (!frame) return;
|
|
3245
|
+
try {
|
|
3246
|
+
await this.close(frame, "commit");
|
|
3247
|
+
} catch (error) {
|
|
3248
|
+
await this.rolledBack(frame);
|
|
3249
|
+
throw error;
|
|
3250
|
+
}
|
|
3251
|
+
await this.committed(frame);
|
|
3167
3252
|
}
|
|
3168
|
-
/** Rolls back the innermost level opened by beginTransaction()
|
|
3253
|
+
/** Rolls back the innermost level opened by beginTransaction(), dropping its afterCommit() callbacks. */
|
|
3169
3254
|
async rollBack() {
|
|
3170
3255
|
const frame = this.pinned.pop();
|
|
3171
|
-
if (frame)
|
|
3256
|
+
if (!frame) return;
|
|
3257
|
+
try {
|
|
3258
|
+
await this.close(frame, "rollback");
|
|
3259
|
+
} finally {
|
|
3260
|
+
await this.rolledBack(frame);
|
|
3261
|
+
}
|
|
3172
3262
|
}
|
|
3173
3263
|
transactionLevel() {
|
|
3174
3264
|
return this.current()?.level ?? 0;
|
|
@@ -3198,7 +3288,7 @@ var Connection = class {
|
|
|
3198
3288
|
}
|
|
3199
3289
|
async open() {
|
|
3200
3290
|
const parent = this.current();
|
|
3201
|
-
if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() };
|
|
3291
|
+
if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve(), callbacks: [], rollbacks: [] };
|
|
3202
3292
|
const previous = parent.turn;
|
|
3203
3293
|
let endTurn;
|
|
3204
3294
|
parent.turn = new Promise((resolve) => endTurn = resolve);
|
|
@@ -3211,7 +3301,7 @@ var Connection = class {
|
|
|
3211
3301
|
endTurn();
|
|
3212
3302
|
throw error;
|
|
3213
3303
|
}
|
|
3214
|
-
return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn };
|
|
3304
|
+
return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn, parent, callbacks: [], rollbacks: [] };
|
|
3215
3305
|
}
|
|
3216
3306
|
async close(frame, action) {
|
|
3217
3307
|
try {
|
|
@@ -3352,6 +3442,18 @@ var DatabaseManagerImpl = class {
|
|
|
3352
3442
|
beginTransaction() {
|
|
3353
3443
|
return this.connection().beginTransaction();
|
|
3354
3444
|
}
|
|
3445
|
+
/**
|
|
3446
|
+
* Laravel's DB::afterCommit(): waits for the transaction(fn) open in this async context, on the default connection
|
|
3447
|
+
* first, then on any other opened one; runs at once outside one. It opens no connection: one with a transaction is
|
|
3448
|
+
* open already.
|
|
3449
|
+
*/
|
|
3450
|
+
async afterCommit(callback, onRollBack) {
|
|
3451
|
+
const preferred = this.connections.get(this.getDefaultConnection());
|
|
3452
|
+
const opened = [...preferred === void 0 ? [] : [preferred], ...this.connections.values()];
|
|
3453
|
+
const open = opened.find((connection) => connection.inTransactionContext());
|
|
3454
|
+
if (open === void 0) await callback();
|
|
3455
|
+
else await open.afterCommit(callback, onRollBack);
|
|
3456
|
+
}
|
|
3355
3457
|
commit() {
|
|
3356
3458
|
return this.connection().commit();
|
|
3357
3459
|
}
|
|
@@ -3385,12 +3487,12 @@ var Schema = facade(SchemaBuilderToken);
|
|
|
3385
3487
|
// Eloquent/Model.ts
|
|
3386
3488
|
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
|
|
3387
3489
|
import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
|
|
3388
|
-
import { Collection as
|
|
3490
|
+
import { Collection as Collection9 } from "@orieljs/collections";
|
|
3389
3491
|
import { currentContainer as currentContainer3, inject } from "@orieljs/container";
|
|
3390
|
-
import { Str as Str6 } from "@orieljs/support";
|
|
3492
|
+
import { serializeDate, Str as Str6 } from "@orieljs/support";
|
|
3391
3493
|
|
|
3392
3494
|
// Eloquent/Builder.ts
|
|
3393
|
-
import { Collection as
|
|
3495
|
+
import { Collection as Collection3 } from "@orieljs/collections";
|
|
3394
3496
|
import { Str as Str2 } from "@orieljs/support";
|
|
3395
3497
|
|
|
3396
3498
|
// Eloquent/Relations/constraints.ts
|
|
@@ -3616,11 +3718,6 @@ var Builder2 = class extends Builder {
|
|
|
3616
3718
|
if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
|
|
3617
3719
|
return models;
|
|
3618
3720
|
}
|
|
3619
|
-
// ---------------------------------------------------------------- eager loading
|
|
3620
|
-
/**
|
|
3621
|
-
* Relations to load with the results, one query per relation (and per nesting level):
|
|
3622
|
-
* with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
|
|
3623
|
-
*/
|
|
3624
3721
|
with(...relations) {
|
|
3625
3722
|
for (const spec of relations) {
|
|
3626
3723
|
if (typeof spec === "string") this.addEagerLoad(spec, void 0);
|
|
@@ -3629,7 +3726,6 @@ var Builder2 = class extends Builder {
|
|
|
3629
3726
|
}
|
|
3630
3727
|
return this;
|
|
3631
3728
|
}
|
|
3632
|
-
/** Removes eager loads (including the model's default `with`). */
|
|
3633
3729
|
without(...relations) {
|
|
3634
3730
|
for (const name of relations) {
|
|
3635
3731
|
for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key);
|
|
@@ -3685,40 +3781,24 @@ var Builder2 = class extends Builder {
|
|
|
3685
3781
|
}
|
|
3686
3782
|
return nested;
|
|
3687
3783
|
}
|
|
3688
|
-
// ---------------------------------------------------------------- relation counts and existence
|
|
3689
|
-
/**
|
|
3690
|
-
* Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
|
|
3691
|
-
* withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
|
|
3692
|
-
*/
|
|
3693
3784
|
withCount(...relations) {
|
|
3694
3785
|
return this.withAggregate(relations, "*", "count");
|
|
3695
3786
|
}
|
|
3696
|
-
/** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
|
|
3697
3787
|
withSum(relations, column) {
|
|
3698
3788
|
return this.withAggregate(relations, column, "sum");
|
|
3699
3789
|
}
|
|
3700
|
-
/** Adds `<relation>_avg_<column>`. */
|
|
3701
3790
|
withAvg(relations, column) {
|
|
3702
3791
|
return this.withAggregate(relations, column, "avg");
|
|
3703
3792
|
}
|
|
3704
|
-
/** Adds `<relation>_min_<column>`. */
|
|
3705
3793
|
withMin(relations, column) {
|
|
3706
3794
|
return this.withAggregate(relations, column, "min");
|
|
3707
3795
|
}
|
|
3708
|
-
/** Adds `<relation>_max_<column>`. */
|
|
3709
3796
|
withMax(relations, column) {
|
|
3710
3797
|
return this.withAggregate(relations, column, "max");
|
|
3711
3798
|
}
|
|
3712
|
-
/** Adds a boolean `<relation>_exists`: withExists('comments'). */
|
|
3713
3799
|
withExists(...relations) {
|
|
3714
3800
|
return this.withAggregate(relations, "*", "exists");
|
|
3715
3801
|
}
|
|
3716
|
-
/**
|
|
3717
|
-
* Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
|
|
3718
|
-
* alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
|
|
3719
|
-
* constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
|
|
3720
|
-
* `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
|
|
3721
|
-
*/
|
|
3722
3802
|
withAggregate(relations, column, fn) {
|
|
3723
3803
|
const specs = this.normalizeRelationSpecs([relations].flat());
|
|
3724
3804
|
if (!specs.length) return this;
|
|
@@ -3752,13 +3832,10 @@ var Builder2 = class extends Builder {
|
|
|
3752
3832
|
this.selectCasts = { ...this.selectCasts, ...casts };
|
|
3753
3833
|
return this;
|
|
3754
3834
|
}
|
|
3755
|
-
/**
|
|
3756
|
-
* Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
|
|
3757
|
-
* Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
|
|
3758
|
-
*/
|
|
3759
3835
|
has(relation, operator = ">=", count = 1, boolean = "and", callback) {
|
|
3760
|
-
|
|
3761
|
-
|
|
3836
|
+
const name = relation;
|
|
3837
|
+
if (name.includes(".")) return this.hasNested(name, operator, count, boolean, callback);
|
|
3838
|
+
const instance = this.getRelation(name);
|
|
3762
3839
|
const useExists = (operator === ">=" || operator === "<") && count === 1;
|
|
3763
3840
|
const query = useExists ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this) : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this);
|
|
3764
3841
|
query.wheres.push(...instance.wheres);
|
|
@@ -3776,7 +3853,6 @@ var Builder2 = class extends Builder {
|
|
|
3776
3853
|
orDoesntHave(relation) {
|
|
3777
3854
|
return this.doesntHave(relation, "or");
|
|
3778
3855
|
}
|
|
3779
|
-
/** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
|
|
3780
3856
|
whereHas(relation, callback, operator = ">=", count = 1) {
|
|
3781
3857
|
return this.has(relation, operator, count, "and", callback);
|
|
3782
3858
|
}
|
|
@@ -3824,7 +3900,7 @@ var Builder2 = class extends Builder {
|
|
|
3824
3900
|
const query = this.applyScopes().clone();
|
|
3825
3901
|
const rows = await Builder.prototype.runSelect.call(query.select(column));
|
|
3826
3902
|
const key = column.includes(".") ? column.slice(column.lastIndexOf(".") + 1) : column;
|
|
3827
|
-
return new
|
|
3903
|
+
return new Collection3(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
|
|
3828
3904
|
}
|
|
3829
3905
|
/** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
|
|
3830
3906
|
isMalformedKey(id) {
|
|
@@ -3870,48 +3946,46 @@ var Builder2 = class extends Builder {
|
|
|
3870
3946
|
newModelInstance(attributes = {}) {
|
|
3871
3947
|
return this.model.newInstance(attributes);
|
|
3872
3948
|
}
|
|
3873
|
-
make(attributes
|
|
3874
|
-
return this.newModelInstance(attributes);
|
|
3949
|
+
make(attributes) {
|
|
3950
|
+
return this.newModelInstance(attributes ?? {});
|
|
3875
3951
|
}
|
|
3876
|
-
async create(attributes
|
|
3877
|
-
const model = this.newModelInstance(attributes);
|
|
3952
|
+
async create(attributes) {
|
|
3953
|
+
const model = this.newModelInstance(attributes ?? {});
|
|
3878
3954
|
await model.save();
|
|
3879
3955
|
return model;
|
|
3880
3956
|
}
|
|
3881
|
-
/** Creates without mass assignment protection. Never pass it request input. */
|
|
3882
3957
|
async forceCreate(attributes) {
|
|
3883
3958
|
const model = this.newModelInstance().forceFill(attributes);
|
|
3884
3959
|
await model.save();
|
|
3885
3960
|
return model;
|
|
3886
3961
|
}
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
return await this.clone().where(
|
|
3962
|
+
async firstOrNew(attributes, values) {
|
|
3963
|
+
const where = attributes;
|
|
3964
|
+
return await this.clone().where(where).first() ?? this.newModelInstance({ ...where, ...values ?? {} });
|
|
3890
3965
|
}
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values);
|
|
3966
|
+
async firstOrCreate(attributes, values) {
|
|
3967
|
+
return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values ?? {});
|
|
3894
3968
|
}
|
|
3895
|
-
|
|
3896
|
-
|
|
3969
|
+
async createOrFirst(attributes, values) {
|
|
3970
|
+
const where = attributes;
|
|
3971
|
+
const extra = values ?? {};
|
|
3897
3972
|
try {
|
|
3898
3973
|
const connection = this.connection;
|
|
3899
|
-
const create = () => this.create({ ...
|
|
3974
|
+
const create = () => this.create({ ...where, ...extra });
|
|
3900
3975
|
return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create();
|
|
3901
3976
|
} catch (error) {
|
|
3902
3977
|
if (!isUniqueViolation(error)) throw error;
|
|
3903
|
-
const existing = await this.clone().where(
|
|
3978
|
+
const existing = await this.clone().where(where).first();
|
|
3904
3979
|
if (!existing) throw error;
|
|
3905
3980
|
return existing;
|
|
3906
3981
|
}
|
|
3907
3982
|
}
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
const model = await this.firstOrCreate(attributes,
|
|
3911
|
-
if (!model.wasRecentlyCreated) await model.fill(
|
|
3983
|
+
async updateOrCreate(attributes, values) {
|
|
3984
|
+
const extra = values ?? {};
|
|
3985
|
+
const model = await this.firstOrCreate(attributes, extra);
|
|
3986
|
+
if (!model.wasRecentlyCreated) await model.fill(extra).save();
|
|
3912
3987
|
return model;
|
|
3913
3988
|
}
|
|
3914
|
-
/** Mass update (no model events); sets updated_at when the model uses timestamps. */
|
|
3915
3989
|
async update(values) {
|
|
3916
3990
|
return Builder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values));
|
|
3917
3991
|
}
|
|
@@ -3981,7 +4055,7 @@ var Builder2 = class extends Builder {
|
|
|
3981
4055
|
|
|
3982
4056
|
// Eloquent/casts.ts
|
|
3983
4057
|
import { isDeepStrictEqual } from "util";
|
|
3984
|
-
import { Collection as
|
|
4058
|
+
import { Collection as Collection4 } from "@orieljs/collections";
|
|
3985
4059
|
var JSON_CASTS = /* @__PURE__ */ new Set(["array", "json", "object", "collection"]);
|
|
3986
4060
|
var DATE_CASTS = /* @__PURE__ */ new Set(["date", "datetime", "immutable_date", "immutable_datetime"]);
|
|
3987
4061
|
var PRIMITIVE_CASTS = /* @__PURE__ */ new Set(["int", "integer", "float", "double", "real", "string", "bool", "boolean", "timestamp"]);
|
|
@@ -4043,7 +4117,7 @@ function castGet(model, key, cast, value, attributes, className) {
|
|
|
4043
4117
|
case "object":
|
|
4044
4118
|
return typeof value === "string" ? JSON.parse(value) : structuredClone(value);
|
|
4045
4119
|
case "collection":
|
|
4046
|
-
return new
|
|
4120
|
+
return new Collection4(typeof value === "string" ? JSON.parse(value) : structuredClone(value));
|
|
4047
4121
|
case "date":
|
|
4048
4122
|
case "immutable_date": {
|
|
4049
4123
|
const date = parseDateTime(value);
|
|
@@ -4064,7 +4138,7 @@ function castSet(model, key, cast, value, attributes, className) {
|
|
|
4064
4138
|
if (value === null || value === void 0) return null;
|
|
4065
4139
|
if (isEnum(cast)) return castGet(model, key, cast, value, attributes, className);
|
|
4066
4140
|
if (typeof cast !== "string") return value;
|
|
4067
|
-
if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof
|
|
4141
|
+
if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection4 ? value.all() : value);
|
|
4068
4142
|
if (cast === "date" || cast === "immutable_date") return formatDate(parseDateTime(value));
|
|
4069
4143
|
if (cast === "datetime" || cast === "immutable_datetime") return formatDateTime(parseDateTime(value));
|
|
4070
4144
|
if (cast === "timestamp") return formatDateTime(typeof value === "number" ? new Date(value * 1e3) : parseDateTime(value));
|
|
@@ -4084,7 +4158,7 @@ function isEquivalent(cast, current, original, model, key, className) {
|
|
|
4084
4158
|
if (typeof cast === "string" && (JSON_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast.startsWith("decimal:"))) {
|
|
4085
4159
|
const a = read(current);
|
|
4086
4160
|
const b = read(original);
|
|
4087
|
-
return isDeepStrictEqual(a instanceof
|
|
4161
|
+
return isDeepStrictEqual(a instanceof Collection4 ? a.all() : a, b instanceof Collection4 ? b.all() : b);
|
|
4088
4162
|
}
|
|
4089
4163
|
if (isEnum(cast)) return String(current) === String(original);
|
|
4090
4164
|
}
|
|
@@ -4093,19 +4167,19 @@ function isEquivalent(cast, current, original, model, key, className) {
|
|
|
4093
4167
|
}
|
|
4094
4168
|
|
|
4095
4169
|
// Eloquent/Collection.ts
|
|
4096
|
-
import { Collection as
|
|
4170
|
+
import { Collection as Collection5 } from "@orieljs/collections";
|
|
4097
4171
|
var dictionaryKey = (key) => String(key);
|
|
4098
4172
|
var isModel = (value) => typeof value === "object" && value !== null && typeof value.getKey === "function" && typeof value.relationLoaded === "function";
|
|
4099
4173
|
function uniqueByKey(models) {
|
|
4100
4174
|
return [...new Map(models.map((model) => [dictionaryKey(model.getKey()), model])).values()];
|
|
4101
4175
|
}
|
|
4102
4176
|
function relatedModels(value) {
|
|
4103
|
-
if (value instanceof
|
|
4177
|
+
if (value instanceof Collection5) return value.all().filter(isModel);
|
|
4104
4178
|
return isModel(value) ? [value] : [];
|
|
4105
4179
|
}
|
|
4106
|
-
var EloquentCollection = class extends
|
|
4180
|
+
var EloquentCollection = class extends Collection5 {
|
|
4107
4181
|
find(key, defaultValue) {
|
|
4108
|
-
const value = isModel(key) ? key.getKey() : key instanceof
|
|
4182
|
+
const value = isModel(key) ? key.getKey() : key instanceof Collection5 ? key.all() : key;
|
|
4109
4183
|
if (Array.isArray(value)) {
|
|
4110
4184
|
const wanted = new Set(value.map(dictionaryKey));
|
|
4111
4185
|
return this.filter((model) => wanted.has(dictionaryKey(model.getKey())));
|
|
@@ -4113,7 +4187,7 @@ var EloquentCollection = class extends Collection6 {
|
|
|
4113
4187
|
return this.first((model) => dictionaryKey(model.getKey()) === dictionaryKey(value), defaultValue);
|
|
4114
4188
|
}
|
|
4115
4189
|
findOrFail(key) {
|
|
4116
|
-
const value = key instanceof
|
|
4190
|
+
const value = key instanceof Collection5 ? key.all() : key;
|
|
4117
4191
|
if (Array.isArray(value)) {
|
|
4118
4192
|
const found = this.find(value);
|
|
4119
4193
|
const keys = [...new Map(value.map((id) => [dictionaryKey(id), id])).values()];
|
|
@@ -4137,40 +4211,33 @@ var EloquentCollection = class extends Collection6 {
|
|
|
4137
4211
|
}
|
|
4138
4212
|
/** The same models in a plain Collection. */
|
|
4139
4213
|
toBase() {
|
|
4140
|
-
return new
|
|
4214
|
+
return new Collection5(this.items);
|
|
4141
4215
|
}
|
|
4142
4216
|
contains(...args) {
|
|
4143
|
-
if (args.length > 1 || typeof args[0] === "function") return Reflect.apply(
|
|
4217
|
+
if (args.length > 1 || typeof args[0] === "function") return Reflect.apply(Collection5.prototype.contains, this, args);
|
|
4144
4218
|
const [key] = args;
|
|
4145
4219
|
if (isModel(key)) return this.items.some((model) => model.is(key));
|
|
4146
4220
|
return this.items.some((model) => dictionaryKey(model.getKey()) === dictionaryKey(key));
|
|
4147
4221
|
}
|
|
4148
4222
|
containsStrict(...args) {
|
|
4149
|
-
return Reflect.apply(
|
|
4223
|
+
return Reflect.apply(Collection5.prototype.contains, this, args);
|
|
4150
4224
|
}
|
|
4151
4225
|
doesntContainStrict(...args) {
|
|
4152
|
-
return !Reflect.apply(
|
|
4226
|
+
return !Reflect.apply(Collection5.prototype.contains, this, args);
|
|
4153
4227
|
}
|
|
4154
|
-
/** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
|
|
4155
4228
|
async load(...relations) {
|
|
4156
4229
|
const first = this.first();
|
|
4157
4230
|
if (!first || !relations.length) return this;
|
|
4158
4231
|
await first.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(this.items);
|
|
4159
4232
|
return this;
|
|
4160
4233
|
}
|
|
4161
|
-
/** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
|
|
4162
4234
|
async loadMissing(...relations) {
|
|
4163
|
-
await loadMissingOn(this.items, relations);
|
|
4235
|
+
await loadMissingOn(this.items, [...relations]);
|
|
4164
4236
|
return this;
|
|
4165
4237
|
}
|
|
4166
|
-
/** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
|
|
4167
4238
|
loadCount(...relations) {
|
|
4168
4239
|
return this.loadAggregate(relations, "*", "count");
|
|
4169
4240
|
}
|
|
4170
|
-
/**
|
|
4171
|
-
* Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
|
|
4172
|
-
* The values become clean attributes (with their casts: loadExists() gives booleans).
|
|
4173
|
-
*/
|
|
4174
4241
|
async loadAggregate(relations, column, fn) {
|
|
4175
4242
|
const first = this.first();
|
|
4176
4243
|
if (!first || ![relations].flat().length) return this;
|
|
@@ -4186,7 +4253,6 @@ var EloquentCollection = class extends Collection6 {
|
|
|
4186
4253
|
}
|
|
4187
4254
|
return this;
|
|
4188
4255
|
}
|
|
4189
|
-
/** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
|
|
4190
4256
|
loadSum(relations, column) {
|
|
4191
4257
|
return this.loadAggregate(relations, column, "sum");
|
|
4192
4258
|
}
|
|
@@ -4199,7 +4265,6 @@ var EloquentCollection = class extends Collection6 {
|
|
|
4199
4265
|
loadMax(relations, column) {
|
|
4200
4266
|
return this.loadAggregate(relations, column, "max");
|
|
4201
4267
|
}
|
|
4202
|
-
/** Adds a boolean <relation>_exists to every model. */
|
|
4203
4268
|
loadExists(...relations) {
|
|
4204
4269
|
return this.loadAggregate(relations, "*", "exists");
|
|
4205
4270
|
}
|
|
@@ -4291,7 +4356,7 @@ async function loadMissingOn(models, paths) {
|
|
|
4291
4356
|
import { existsSync, readdirSync } from "fs";
|
|
4292
4357
|
import { join as join4 } from "path";
|
|
4293
4358
|
import { pathToFileURL } from "url";
|
|
4294
|
-
import { Collection as
|
|
4359
|
+
import { Collection as Collection8 } from "@orieljs/collections";
|
|
4295
4360
|
import { Str as Str5 } from "@orieljs/support";
|
|
4296
4361
|
|
|
4297
4362
|
// Eloquent/Relations/BelongsTo.ts
|
|
@@ -4342,7 +4407,7 @@ function resolveMorphClass(type) {
|
|
|
4342
4407
|
|
|
4343
4408
|
// Eloquent/Relations/Relation.ts
|
|
4344
4409
|
var selfAliases = 0;
|
|
4345
|
-
var Relation = class extends Builder2 {
|
|
4410
|
+
var Relation = class _Relation extends Builder2 {
|
|
4346
4411
|
constructor(related, parent) {
|
|
4347
4412
|
super(related);
|
|
4348
4413
|
this.parent = parent;
|
|
@@ -4374,11 +4439,15 @@ var Relation = class extends Builder2 {
|
|
|
4374
4439
|
aliasSelfTable(query) {
|
|
4375
4440
|
const table = query.getModel().getTable();
|
|
4376
4441
|
if (table !== this.parent.getTable()) return void 0;
|
|
4377
|
-
const alias =
|
|
4442
|
+
const alias = _Relation.reserveAlias();
|
|
4378
4443
|
query.from(`${table} as ${alias}`);
|
|
4379
4444
|
query.getModel().setTable(alias);
|
|
4380
4445
|
return alias;
|
|
4381
4446
|
}
|
|
4447
|
+
/** A new `oriel_reserved_<n>` alias, for a table a query reads twice. */
|
|
4448
|
+
static reserveAlias() {
|
|
4449
|
+
return `oriel_reserved_${selfAliases++}`;
|
|
4450
|
+
}
|
|
4382
4451
|
/**
|
|
4383
4452
|
* @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
|
|
4384
4453
|
* on the relations that know the column holding the parent's key.
|
|
@@ -4485,7 +4554,7 @@ var BelongsTo = class extends Relation {
|
|
|
4485
4554
|
};
|
|
4486
4555
|
|
|
4487
4556
|
// Eloquent/Relations/BelongsToMany.ts
|
|
4488
|
-
import { Collection as
|
|
4557
|
+
import { Collection as Collection6 } from "@orieljs/collections";
|
|
4489
4558
|
var BelongsToMany = class extends Relation {
|
|
4490
4559
|
constructor(related, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
|
|
4491
4560
|
super(related, parent);
|
|
@@ -4642,9 +4711,8 @@ var BelongsToMany = class extends Relation {
|
|
|
4642
4711
|
if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp());
|
|
4643
4712
|
return this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey()).where(this.relatedPivotKey, "=", this.idOf(id)).update(values);
|
|
4644
4713
|
}
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
const model = this.model.newInstance(attributes);
|
|
4714
|
+
async create(attributes, pivotAttributes = {}) {
|
|
4715
|
+
const model = this.model.newInstance(attributes ?? {});
|
|
4648
4716
|
await model.save();
|
|
4649
4717
|
await this.attach(model, pivotAttributes);
|
|
4650
4718
|
return model;
|
|
@@ -4693,7 +4761,7 @@ var BelongsToMany = class extends Relation {
|
|
|
4693
4761
|
/** ids → Map(id → extra pivot attributes). Models become their related key. */
|
|
4694
4762
|
parseIds(ids) {
|
|
4695
4763
|
const parsed = /* @__PURE__ */ new Map();
|
|
4696
|
-
if (ids instanceof
|
|
4764
|
+
if (ids instanceof Collection6) ids = ids.all();
|
|
4697
4765
|
if (Array.isArray(ids)) {
|
|
4698
4766
|
for (const id of ids) parsed.set(this.idOf(id), {});
|
|
4699
4767
|
} else if (ids !== null && typeof ids === "object" && !this.isModel(ids)) {
|
|
@@ -4851,10 +4919,11 @@ var HasOneOrMany = class extends Relation {
|
|
|
4851
4919
|
for (const model of models) saved.push(await this.save(model));
|
|
4852
4920
|
return saved;
|
|
4853
4921
|
}
|
|
4922
|
+
/** One related model per record, in the related model's Eloquent collection. */
|
|
4854
4923
|
async createMany(records) {
|
|
4855
4924
|
const created = [];
|
|
4856
4925
|
for (const record of records) created.push(await this.create(record));
|
|
4857
|
-
return created;
|
|
4926
|
+
return this.getRelated().newCollection(created);
|
|
4858
4927
|
}
|
|
4859
4928
|
eagerPartitionColumn() {
|
|
4860
4929
|
return this.foreignKey;
|
|
@@ -4872,7 +4941,7 @@ var HasOneOrMany = class extends Relation {
|
|
|
4872
4941
|
};
|
|
4873
4942
|
|
|
4874
4943
|
// Eloquent/Relations/MorphTo.ts
|
|
4875
|
-
import { Collection as
|
|
4944
|
+
import { Collection as Collection7 } from "@orieljs/collections";
|
|
4876
4945
|
var MorphTo = class extends BelongsTo {
|
|
4877
4946
|
/**
|
|
4878
4947
|
* @param related an instance of the current type's class (the child's own class when the type is empty)
|
|
@@ -4934,7 +5003,7 @@ var MorphTo = class extends BelongsTo {
|
|
|
4934
5003
|
results.push(result);
|
|
4935
5004
|
}
|
|
4936
5005
|
}
|
|
4937
|
-
return new
|
|
5006
|
+
return new Collection7(results);
|
|
4938
5007
|
}
|
|
4939
5008
|
match(models, results, relation) {
|
|
4940
5009
|
for (const result of results) {
|
|
@@ -5053,12 +5122,16 @@ var Factory = class _Factory {
|
|
|
5053
5122
|
async createOne(attributes = {}) {
|
|
5054
5123
|
return await this.newInstance({ countValue: void 0 }).create(attributes);
|
|
5055
5124
|
}
|
|
5056
|
-
/** One model per record (or `count` models). */
|
|
5125
|
+
/** One model per record (or `count` models), in the model's Eloquent collection. */
|
|
5057
5126
|
async createMany(records) {
|
|
5058
5127
|
const list3 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
|
|
5059
5128
|
const created = [];
|
|
5060
5129
|
for (const record of list3) created.push(await this.createOne(record));
|
|
5061
|
-
return
|
|
5130
|
+
return this.collect(created);
|
|
5131
|
+
}
|
|
5132
|
+
/** The models in their own Eloquent collection (the model's newCollection()). */
|
|
5133
|
+
collect(models) {
|
|
5134
|
+
return new this.model().newCollection(models);
|
|
5062
5135
|
}
|
|
5063
5136
|
newInstance(changes) {
|
|
5064
5137
|
const copy = Object.create(Object.getPrototypeOf(this));
|
|
@@ -5109,7 +5182,7 @@ var Factory = class _Factory {
|
|
|
5109
5182
|
const relation = this.relationOn(model, relationship);
|
|
5110
5183
|
if (relation instanceof BelongsToMany) {
|
|
5111
5184
|
const related = await factory.create();
|
|
5112
|
-
await relation.attach(related instanceof
|
|
5185
|
+
await relation.attach(related instanceof Collection8 ? related.all() : related, pivot);
|
|
5113
5186
|
} else if (relation instanceof HasOneOrMany) {
|
|
5114
5187
|
const foreign = { [relation.getForeignKeyName()]: relation.getParentKey() };
|
|
5115
5188
|
if (relation.morph) foreign[relation.getMorphType()] = relation.getMorphClass();
|
|
@@ -5123,7 +5196,7 @@ var Factory = class _Factory {
|
|
|
5123
5196
|
return model.getRelationInstance(relationship);
|
|
5124
5197
|
}
|
|
5125
5198
|
result(models) {
|
|
5126
|
-
return this.countValue === void 0 ? models[0] :
|
|
5199
|
+
return this.countValue === void 0 ? models[0] : this.collect(models);
|
|
5127
5200
|
}
|
|
5128
5201
|
};
|
|
5129
5202
|
async function discoverFactories(path) {
|
|
@@ -5202,7 +5275,7 @@ var HasMany = class extends HasOneOrMany {
|
|
|
5202
5275
|
|
|
5203
5276
|
// Eloquent/Relations/HasManyThrough.ts
|
|
5204
5277
|
var THROUGH_KEY = "laravel_through_key";
|
|
5205
|
-
var HasManyThrough = class extends Relation {
|
|
5278
|
+
var HasManyThrough = class _HasManyThrough extends Relation {
|
|
5206
5279
|
/**
|
|
5207
5280
|
* @param firstKey on the through table, pointing at the far parent ('users.country_id')
|
|
5208
5281
|
* @param secondKey on the related table, pointing at the through model ('posts.user_id')
|
|
@@ -5216,9 +5289,10 @@ var HasManyThrough = class extends Relation {
|
|
|
5216
5289
|
this.secondKey = secondKey;
|
|
5217
5290
|
this.localKey = localKey;
|
|
5218
5291
|
this.secondLocalKey = secondLocalKey;
|
|
5219
|
-
this.
|
|
5292
|
+
this.throughAlias = throughParent.getTable() === related.getTable() ? _HasManyThrough.reserveAlias() : void 0;
|
|
5293
|
+
this.join(this.throughTable(this.throughAlias), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName());
|
|
5220
5294
|
if (this.throughParent.usesSoftDeletes()) {
|
|
5221
|
-
this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughParent.
|
|
5295
|
+
this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn())));
|
|
5222
5296
|
}
|
|
5223
5297
|
this.init();
|
|
5224
5298
|
}
|
|
@@ -5229,9 +5303,22 @@ var HasManyThrough = class extends Relation {
|
|
|
5229
5303
|
secondLocalKey;
|
|
5230
5304
|
/** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
|
|
5231
5305
|
throughKeys = /* @__PURE__ */ new WeakMap();
|
|
5306
|
+
/**
|
|
5307
|
+
* The through table's alias when it is the related table too (a person's grandchildren, through their children):
|
|
5308
|
+
* every query of the relation reads it under this name, its keys and soft deletes included.
|
|
5309
|
+
*/
|
|
5310
|
+
throughAlias;
|
|
5311
|
+
/** The through table to join: `users`, or `users as <alias>`. */
|
|
5312
|
+
throughTable(alias) {
|
|
5313
|
+
return alias === void 0 ? this.throughParent.getTable() : `${this.throughParent.getTable()} as ${alias}`;
|
|
5314
|
+
}
|
|
5315
|
+
/** A through column, qualified by the through table or by its alias. */
|
|
5316
|
+
throughColumn(column, alias = this.throughAlias) {
|
|
5317
|
+
return alias === void 0 ? this.throughParent.qualifyColumn(column) : `${alias}.${column}`;
|
|
5318
|
+
}
|
|
5232
5319
|
/** users.country_id */
|
|
5233
5320
|
getQualifiedFirstKeyName() {
|
|
5234
|
-
return this.
|
|
5321
|
+
return this.throughColumn(this.firstKey);
|
|
5235
5322
|
}
|
|
5236
5323
|
/** posts.user_id */
|
|
5237
5324
|
getQualifiedForeignKeyName() {
|
|
@@ -5239,7 +5326,7 @@ var HasManyThrough = class extends Relation {
|
|
|
5239
5326
|
}
|
|
5240
5327
|
/** users.id */
|
|
5241
5328
|
getQualifiedParentKeyName() {
|
|
5242
|
-
return this.
|
|
5329
|
+
return this.throughColumn(this.secondLocalKey);
|
|
5243
5330
|
}
|
|
5244
5331
|
/** countries.id */
|
|
5245
5332
|
getQualifiedLocalKeyName() {
|
|
@@ -5264,6 +5351,10 @@ var HasManyThrough = class extends Relation {
|
|
|
5264
5351
|
}
|
|
5265
5352
|
return models;
|
|
5266
5353
|
}
|
|
5354
|
+
/** An eager limit() or offset() applies to each far parent, by the through table's key to it (Laravel 11). */
|
|
5355
|
+
eagerPartitionColumn() {
|
|
5356
|
+
return this.getQualifiedFirstKeyName();
|
|
5357
|
+
}
|
|
5267
5358
|
async getResults() {
|
|
5268
5359
|
const key = this.parent.getAttribute(this.localKey);
|
|
5269
5360
|
return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
|
|
@@ -5286,9 +5377,15 @@ var HasManyThrough = class extends Relation {
|
|
|
5286
5377
|
for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
|
|
5287
5378
|
return models;
|
|
5288
5379
|
}
|
|
5380
|
+
/**
|
|
5381
|
+
* The query of has()/withCount(), as Laravel's ...ForSelfRelation and ...ForThroughSelfRelation: a related table that
|
|
5382
|
+
* is the parent's is read under an alias, and so is a through table that is the parent's (or the related one).
|
|
5383
|
+
*/
|
|
5289
5384
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
5290
|
-
|
|
5291
|
-
|
|
5385
|
+
const related = this.aliasSelfTable(query) ?? query.getModel().getTable();
|
|
5386
|
+
const alias = this.throughAlias ?? (this.throughParent.getTable() === this.parent.getTable() ? _HasManyThrough.reserveAlias() : void 0);
|
|
5387
|
+
query.select(...columns).join(this.throughTable(alias), this.throughColumn(this.secondLocalKey, alias), "=", `${related}.${this.secondKey}`).whereColumn(this.getQualifiedLocalKeyName(), "=", this.throughColumn(this.firstKey, alias));
|
|
5388
|
+
if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn(), alias));
|
|
5292
5389
|
return query;
|
|
5293
5390
|
}
|
|
5294
5391
|
};
|
|
@@ -5414,9 +5511,6 @@ function hasher() {
|
|
|
5414
5511
|
return container.make(Hasher);
|
|
5415
5512
|
}
|
|
5416
5513
|
var serializing = /* @__PURE__ */ new WeakSet();
|
|
5417
|
-
function serializeDate(date) {
|
|
5418
|
-
return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
|
|
5419
|
-
}
|
|
5420
5514
|
var Model = class _Model {
|
|
5421
5515
|
static CREATED_AT = "created_at";
|
|
5422
5516
|
static UPDATED_AT = "updated_at";
|
|
@@ -5510,8 +5604,8 @@ var Model = class _Model {
|
|
|
5510
5604
|
return instance;
|
|
5511
5605
|
}
|
|
5512
5606
|
/** A new, unsaved model filled with attributes (mass assignment rules apply). */
|
|
5513
|
-
static make(attributes
|
|
5514
|
-
return new this().fill(attributes);
|
|
5607
|
+
static make(attributes) {
|
|
5608
|
+
return new this().fill(attributes ?? {});
|
|
5515
5609
|
}
|
|
5516
5610
|
static addGlobalScope(nameOrScope, implementation) {
|
|
5517
5611
|
let name;
|
|
@@ -5804,20 +5898,20 @@ var Model = class _Model {
|
|
|
5804
5898
|
return this.query().lazyById(chunkSize);
|
|
5805
5899
|
}
|
|
5806
5900
|
/** Creates and saves a model (mass assignment rules apply). */
|
|
5807
|
-
static create(attributes
|
|
5808
|
-
return this.query().create(attributes);
|
|
5901
|
+
static create(attributes) {
|
|
5902
|
+
return this.query().create(attributes ?? {});
|
|
5809
5903
|
}
|
|
5810
5904
|
static forceCreate(attributes) {
|
|
5811
5905
|
return this.query().forceCreate(attributes);
|
|
5812
5906
|
}
|
|
5813
|
-
static firstOrNew(attributes, values
|
|
5814
|
-
return this.query().firstOrNew(attributes, values);
|
|
5907
|
+
static firstOrNew(attributes, values) {
|
|
5908
|
+
return this.query().firstOrNew(attributes, values ?? {});
|
|
5815
5909
|
}
|
|
5816
|
-
static firstOrCreate(attributes, values
|
|
5817
|
-
return this.query().firstOrCreate(attributes, values);
|
|
5910
|
+
static firstOrCreate(attributes, values) {
|
|
5911
|
+
return this.query().firstOrCreate(attributes, values ?? {});
|
|
5818
5912
|
}
|
|
5819
|
-
static updateOrCreate(attributes, values
|
|
5820
|
-
return this.query().updateOrCreate(attributes, values);
|
|
5913
|
+
static updateOrCreate(attributes, values) {
|
|
5914
|
+
return this.query().updateOrCreate(attributes, values ?? {});
|
|
5821
5915
|
}
|
|
5822
5916
|
static factory(count, state) {
|
|
5823
5917
|
let factory = Factory.forModel(this);
|
|
@@ -6074,6 +6168,7 @@ var Model = class _Model {
|
|
|
6074
6168
|
if (value === void 0 || value === null || value === "") this.setAttribute(column, this.newUniqueId());
|
|
6075
6169
|
}
|
|
6076
6170
|
}
|
|
6171
|
+
/** The primary key's value: a string, a number or a bigint, or nothing on a model not yet saved. */
|
|
6077
6172
|
getKey() {
|
|
6078
6173
|
return this.getAttribute(this.getKeyName());
|
|
6079
6174
|
}
|
|
@@ -6240,9 +6335,9 @@ var Model = class _Model {
|
|
|
6240
6335
|
this.pendingHashes.clear();
|
|
6241
6336
|
}
|
|
6242
6337
|
/** Fills and saves an existing model. */
|
|
6243
|
-
async update(attributes
|
|
6338
|
+
async update(attributes) {
|
|
6244
6339
|
if (!this.exists) return false;
|
|
6245
|
-
return this.fill(attributes).save();
|
|
6340
|
+
return this.fill(attributes ?? {}).save();
|
|
6246
6341
|
}
|
|
6247
6342
|
/**
|
|
6248
6343
|
* Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
|
|
@@ -6701,7 +6796,7 @@ var Model = class _Model {
|
|
|
6701
6796
|
const key = Str6.snake(name);
|
|
6702
6797
|
if (!this.isArrayableKey(key)) continue;
|
|
6703
6798
|
if (value === null || value === void 0) result[key] = null;
|
|
6704
|
-
else if (value instanceof
|
|
6799
|
+
else if (value instanceof Collection9) result[key] = value.toArray();
|
|
6705
6800
|
else if (typeof value.toArray === "function") result[key] = value.toArray();
|
|
6706
6801
|
else result[key] = value;
|
|
6707
6802
|
}
|
|
@@ -6709,7 +6804,7 @@ var Model = class _Model {
|
|
|
6709
6804
|
}
|
|
6710
6805
|
serializeValue(value) {
|
|
6711
6806
|
if (value instanceof Date) return serializeDate(value);
|
|
6712
|
-
if (value instanceof
|
|
6807
|
+
if (value instanceof Collection9) return value.toArray();
|
|
6713
6808
|
return value;
|
|
6714
6809
|
}
|
|
6715
6810
|
isArrayableKey(key) {
|
|
@@ -7287,14 +7382,22 @@ var TypeGenerator = class {
|
|
|
7287
7382
|
const members = attributes.filter(([column]) => !(column in instance));
|
|
7288
7383
|
const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance));
|
|
7289
7384
|
const statics = scopes(model).filter(([method]) => !(method in Model));
|
|
7290
|
-
const
|
|
7385
|
+
const names = (list3) => list3.map((item) => `'${item}'`).join(" | ");
|
|
7386
|
+
const hidden = instance.getHidden();
|
|
7387
|
+
const visible = instance.getVisible();
|
|
7388
|
+
const appends = instance.getAppends();
|
|
7291
7389
|
const lines = [
|
|
7292
7390
|
`declare module '${this.modulePath(file)}' {`,
|
|
7293
7391
|
` interface ${name} {`,
|
|
7294
7392
|
" $attributes?: {",
|
|
7295
7393
|
...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
|
|
7296
7394
|
" }",
|
|
7297
|
-
|
|
7395
|
+
// The model itself, for its own methods: inside them `this` is a type parameter, and their writes and loads read
|
|
7396
|
+
// the attributes and relations they check from here.
|
|
7397
|
+
` $self?: ${name}`,
|
|
7398
|
+
...hidden.length ? [` $hidden?: ${names(hidden)}`] : [],
|
|
7399
|
+
...visible.length ? [` $visible?: ${names(visible)}`] : [],
|
|
7400
|
+
...appends.length ? [` $appends?: ${names(appends)}`] : [],
|
|
7298
7401
|
...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
|
|
7299
7402
|
...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),
|
|
7300
7403
|
" }"
|