@orieljs/database 0.1.0-alpha.13 → 0.1.0-alpha.15
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/dist/index.d.ts +56 -14
- package/dist/index.js +164 -47
- package/dist/index.js.map +1 -1
- package/package.json +15 -7
package/dist/index.js
CHANGED
|
@@ -82,6 +82,7 @@ var LogicError = class extends DatabaseError {
|
|
|
82
82
|
var isBun = () => typeof globalThis.Bun !== "undefined";
|
|
83
83
|
|
|
84
84
|
// Connectors/SqliteDatabase.ts
|
|
85
|
+
import { importOptional } from "@orieljs/support";
|
|
85
86
|
var BunSqliteDatabase = class {
|
|
86
87
|
constructor(database) {
|
|
87
88
|
this.database = database;
|
|
@@ -108,13 +109,16 @@ async function openSqlite(filename) {
|
|
|
108
109
|
/* @vite-ignore */
|
|
109
110
|
specifier
|
|
110
111
|
);
|
|
111
|
-
|
|
112
|
+
const database = new Database2(filename);
|
|
113
|
+
database.prepare("PRAGMA busy_timeout = 5000").run();
|
|
114
|
+
return new BunSqliteDatabase(database);
|
|
112
115
|
}
|
|
113
|
-
const { default: Database } = await import("better-sqlite3");
|
|
116
|
+
const { default: Database } = await importOptional("better-sqlite3", "The sqlite connection", () => import("better-sqlite3"));
|
|
114
117
|
return new Database(filename);
|
|
115
118
|
}
|
|
116
119
|
|
|
117
120
|
// Connectors/dialect.ts
|
|
121
|
+
import { importOptional as importOptional2 } from "@orieljs/support";
|
|
118
122
|
import { CompiledQuery, MysqlDialect, PostgresDialect, SqliteDialect } from "kysely";
|
|
119
123
|
var PG_INT8 = 20;
|
|
120
124
|
var PG_DATE = 1082;
|
|
@@ -173,7 +177,7 @@ function createDialect(config) {
|
|
|
173
177
|
case "pgsql":
|
|
174
178
|
return new PostgresDialect({
|
|
175
179
|
pool: async () => {
|
|
176
|
-
const { default: pg } = await import("pg");
|
|
180
|
+
const { default: pg } = await importOptional2("pg", "The pgsql connection", () => import("pg"));
|
|
177
181
|
return new pg.Pool({
|
|
178
182
|
connectionString: config.url,
|
|
179
183
|
host: config.host,
|
|
@@ -201,7 +205,7 @@ function createDialect(config) {
|
|
|
201
205
|
case "mysql":
|
|
202
206
|
return new MysqlDialect({
|
|
203
207
|
pool: async () => {
|
|
204
|
-
const { createPool } = await import("mysql2");
|
|
208
|
+
const { createPool } = await importOptional2("mysql2", "The mysql connection", () => import("mysql2"));
|
|
205
209
|
return createPool(mysqlPoolOptions(config));
|
|
206
210
|
}
|
|
207
211
|
});
|
|
@@ -736,10 +740,33 @@ var Grammar = class {
|
|
|
736
740
|
columnize(columns) {
|
|
737
741
|
return join(columns.map((column) => this.wrap(column)));
|
|
738
742
|
}
|
|
739
|
-
compileSelect(query) {
|
|
740
|
-
|
|
743
|
+
compileSelect(query, extraColumn) {
|
|
744
|
+
if (query.groupLimit && extraColumn === void 0) return this.compileGroupLimit(query);
|
|
745
|
+
const list3 = query.columns.length ? query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column)) : [sql2.raw("*")];
|
|
746
|
+
const columns = join(extraColumn ? [...list3, extraColumn] : list3);
|
|
741
747
|
return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
|
|
742
748
|
}
|
|
749
|
+
/**
|
|
750
|
+
* Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
|
|
751
|
+
* those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
|
|
752
|
+
*/
|
|
753
|
+
compileGroupLimit(query) {
|
|
754
|
+
const { column, limit, offset } = query.groupLimit;
|
|
755
|
+
const inner = query.clone();
|
|
756
|
+
inner.groupLimit = void 0;
|
|
757
|
+
inner.orders = [];
|
|
758
|
+
const order = this.compileOrders(query);
|
|
759
|
+
const over = order ? sql2`partition by ${this.wrap(column)} ${order}` : sql2`partition by ${this.wrap(column)}`;
|
|
760
|
+
const row = sql2.id(GROUP_ROW);
|
|
761
|
+
const kept = [];
|
|
762
|
+
if (offset !== void 0 && offset > 0) kept.push(sql2`${row} > ${sql2.lit(offset)}`);
|
|
763
|
+
if (limit !== void 0) kept.push(sql2`${row} <= ${sql2.lit((offset ?? 0) + limit)}`);
|
|
764
|
+
return clauses([
|
|
765
|
+
sql2`select * from (${this.compileSelect(inner, sql2`row_number() over (${over}) as ${row}`)}) as ${sql2.id("oriel_table")}`,
|
|
766
|
+
kept.length ? sql2`where ${join(kept, " and ")}` : void 0,
|
|
767
|
+
sql2`order by ${row}`
|
|
768
|
+
]);
|
|
769
|
+
}
|
|
743
770
|
/** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
|
|
744
771
|
compileComponents(query) {
|
|
745
772
|
return clauses([
|
|
@@ -766,7 +793,9 @@ var Grammar = class {
|
|
|
766
793
|
switch (where.type) {
|
|
767
794
|
case "basic": {
|
|
768
795
|
const column = typeof where.column === "object" && !(where.column instanceof Expression) ? sql2`(${this.compileSelect(where.column)})` : this.wrap(where.column);
|
|
769
|
-
|
|
796
|
+
const operator = this.operator(where.operator);
|
|
797
|
+
if (this.driver === "pgsql" && /like/i.test(operator)) return sql2`${column}::text ${sql2.raw(operator)} ${this.parameter(where.value)}`;
|
|
798
|
+
return sql2`${column} ${sql2.raw(operator)} ${this.parameter(where.value)}`;
|
|
770
799
|
}
|
|
771
800
|
case "in": {
|
|
772
801
|
const keyword = sql2.raw(where.not ? "not in" : "in");
|
|
@@ -845,7 +874,10 @@ var Grammar = class {
|
|
|
845
874
|
if (mode === "update") return sql2.raw("for update");
|
|
846
875
|
return sql2.raw(this.driver === "pgsql" ? "for share" : "lock in share mode");
|
|
847
876
|
}
|
|
848
|
-
/**
|
|
877
|
+
/**
|
|
878
|
+
* `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
|
|
879
|
+
* `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
|
|
880
|
+
*/
|
|
849
881
|
compileAggregate(query, fn, column) {
|
|
850
882
|
const inner = query.clone();
|
|
851
883
|
inner.orders = [];
|
|
@@ -853,7 +885,7 @@ var Grammar = class {
|
|
|
853
885
|
inner.offsetValue = void 0;
|
|
854
886
|
inner.lockMode = void 0;
|
|
855
887
|
const target = column === "*" ? sql2.raw("*") : this.wrap(column);
|
|
856
|
-
if (inner.groups.length || inner.distinctRows) {
|
|
888
|
+
if (inner.groups.length || inner.distinctRows || inner.havings.length) {
|
|
857
889
|
if (fn === "count") return sql2`select count(*) as ${sql2.id("aggregate")} from (${this.compileSelect(inner)}) as ${sql2.id("temp_table")}`;
|
|
858
890
|
if (column instanceof Expression) {
|
|
859
891
|
throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`);
|
|
@@ -941,6 +973,7 @@ var Grammar = class {
|
|
|
941
973
|
};
|
|
942
974
|
|
|
943
975
|
// Query/Builder.ts
|
|
976
|
+
var GROUP_ROW = "oriel_row";
|
|
944
977
|
async function* chunksOf(query, chunkSize) {
|
|
945
978
|
for (let page = 1; ; page++) {
|
|
946
979
|
const results = await query.clone().forPage(page, chunkSize).runSelect();
|
|
@@ -1001,6 +1034,8 @@ var Builder = class _Builder {
|
|
|
1001
1034
|
orders = [];
|
|
1002
1035
|
limitValue;
|
|
1003
1036
|
offsetValue;
|
|
1037
|
+
/** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
|
|
1038
|
+
groupLimit;
|
|
1004
1039
|
lockMode;
|
|
1005
1040
|
// ---------------------------------------------------------------- building
|
|
1006
1041
|
from(table) {
|
|
@@ -1289,7 +1324,20 @@ var Builder = class _Builder {
|
|
|
1289
1324
|
}
|
|
1290
1325
|
/** The raw rows, without a Collection around them. */
|
|
1291
1326
|
async runSelect() {
|
|
1292
|
-
|
|
1327
|
+
const rows = (await this.connection.execute(this.grammar.compileSelect(this))).rows;
|
|
1328
|
+
if (this.groupLimit) for (const row of rows) delete row[GROUP_ROW];
|
|
1329
|
+
return rows;
|
|
1330
|
+
}
|
|
1331
|
+
/**
|
|
1332
|
+
* @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
|
|
1333
|
+
* the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
|
|
1334
|
+
*/
|
|
1335
|
+
limitPerGroup(column) {
|
|
1336
|
+
if (this.limitValue === void 0 && this.offsetValue === void 0) return this;
|
|
1337
|
+
this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue };
|
|
1338
|
+
this.limitValue = void 0;
|
|
1339
|
+
this.offsetValue = void 0;
|
|
1340
|
+
return this;
|
|
1293
1341
|
}
|
|
1294
1342
|
async first() {
|
|
1295
1343
|
const rows = await this.clone().limit(1).runSelect();
|
|
@@ -3030,6 +3078,7 @@ var Connection = class {
|
|
|
3030
3078
|
db;
|
|
3031
3079
|
context = new AsyncLocalStorage();
|
|
3032
3080
|
pinned = [];
|
|
3081
|
+
savepoints = 0;
|
|
3033
3082
|
loggingQueries = false;
|
|
3034
3083
|
queryLog = [];
|
|
3035
3084
|
getName() {
|
|
@@ -3149,23 +3198,38 @@ var Connection = class {
|
|
|
3149
3198
|
}
|
|
3150
3199
|
async open() {
|
|
3151
3200
|
const parent = this.current();
|
|
3152
|
-
if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
|
|
3201
|
+
if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() };
|
|
3202
|
+
const previous = parent.turn;
|
|
3203
|
+
let endTurn;
|
|
3204
|
+
parent.turn = new Promise((resolve) => endTurn = resolve);
|
|
3205
|
+
await previous;
|
|
3153
3206
|
const level = parent.level + 1;
|
|
3154
|
-
|
|
3155
|
-
|
|
3207
|
+
const savepoint = `trans${level}_${++this.savepoints}`;
|
|
3208
|
+
try {
|
|
3209
|
+
await sql7.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx);
|
|
3210
|
+
} catch (error) {
|
|
3211
|
+
endTurn();
|
|
3212
|
+
throw error;
|
|
3213
|
+
}
|
|
3214
|
+
return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn };
|
|
3156
3215
|
}
|
|
3157
3216
|
async close(frame, action) {
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3217
|
+
try {
|
|
3218
|
+
if (frame.level === 1) {
|
|
3219
|
+
await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
|
|
3220
|
+
} else if (action === "commit") {
|
|
3221
|
+
await sql7.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
|
|
3222
|
+
} else {
|
|
3223
|
+
await sql7.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
|
|
3224
|
+
}
|
|
3225
|
+
} finally {
|
|
3226
|
+
frame.endTurn?.();
|
|
3164
3227
|
}
|
|
3165
3228
|
}
|
|
3166
3229
|
};
|
|
3167
3230
|
|
|
3168
3231
|
// DatabaseManager.ts
|
|
3232
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
3169
3233
|
var DatabaseManagerImpl = class {
|
|
3170
3234
|
/** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
|
|
3171
3235
|
constructor(config) {
|
|
@@ -3174,6 +3238,8 @@ var DatabaseManagerImpl = class {
|
|
|
3174
3238
|
config;
|
|
3175
3239
|
connections = /* @__PURE__ */ new Map();
|
|
3176
3240
|
defaultName;
|
|
3241
|
+
/** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
|
|
3242
|
+
using = new AsyncLocalStorage2();
|
|
3177
3243
|
settings() {
|
|
3178
3244
|
return typeof this.config === "function" ? this.config() : this.config;
|
|
3179
3245
|
}
|
|
@@ -3190,25 +3256,19 @@ var DatabaseManagerImpl = class {
|
|
|
3190
3256
|
return connection;
|
|
3191
3257
|
}
|
|
3192
3258
|
getDefaultConnection() {
|
|
3193
|
-
return this.defaultName ?? this.settings().default;
|
|
3259
|
+
return this.using.getStore() ?? this.defaultName ?? this.settings().default;
|
|
3194
3260
|
}
|
|
3195
3261
|
/** Overrides config('database.default'); undefined clears the override. */
|
|
3196
3262
|
setDefaultConnection(name) {
|
|
3197
3263
|
this.defaultName = name;
|
|
3198
3264
|
}
|
|
3199
3265
|
/**
|
|
3200
|
-
* Runs `callback` with `name` as the default connection (Laravel's usingConnection()),
|
|
3201
|
-
*
|
|
3266
|
+
* Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
|
|
3267
|
+
* context only: other requests running meanwhile keep their default. Without a name, just runs it.
|
|
3202
3268
|
*/
|
|
3203
3269
|
async usingConnection(name, callback) {
|
|
3204
3270
|
if (!name) return callback();
|
|
3205
|
-
|
|
3206
|
-
this.defaultName = name;
|
|
3207
|
-
try {
|
|
3208
|
-
return await callback();
|
|
3209
|
-
} finally {
|
|
3210
|
-
this.defaultName = previous;
|
|
3211
|
-
}
|
|
3271
|
+
return this.using.run(name, callback);
|
|
3212
3272
|
}
|
|
3213
3273
|
/** The connections opened so far. */
|
|
3214
3274
|
getConnections() {
|
|
@@ -3323,7 +3383,7 @@ var SchemaBuilderToken = token("Database.SchemaBuilder");
|
|
|
3323
3383
|
var Schema = facade(SchemaBuilderToken);
|
|
3324
3384
|
|
|
3325
3385
|
// Eloquent/Model.ts
|
|
3326
|
-
import { AsyncLocalStorage as
|
|
3386
|
+
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
|
|
3327
3387
|
import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
|
|
3328
3388
|
import { Collection as Collection10 } from "@orieljs/collections";
|
|
3329
3389
|
import { currentContainer as currentContainer3, inject } from "@orieljs/container";
|
|
@@ -3553,7 +3613,7 @@ var Builder2 = class extends Builder {
|
|
|
3553
3613
|
if (models.length && this.model.hasModelListeners("retrieved")) {
|
|
3554
3614
|
for (const model of models) await model.fireModelEvent("retrieved", false);
|
|
3555
3615
|
}
|
|
3556
|
-
if (models.length &&
|
|
3616
|
+
if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
|
|
3557
3617
|
return models;
|
|
3558
3618
|
}
|
|
3559
3619
|
// ---------------------------------------------------------------- eager loading
|
|
@@ -3594,6 +3654,7 @@ var Builder2 = class extends Builder {
|
|
|
3594
3654
|
const relation = this.getRelation(name);
|
|
3595
3655
|
relation.addEagerConstraints(models);
|
|
3596
3656
|
constraint?.(relation);
|
|
3657
|
+
relation.limitEagerPerParent();
|
|
3597
3658
|
const nested = this.relationsNestedUnder(name);
|
|
3598
3659
|
if (Object.keys(nested).length) relation.with(nested);
|
|
3599
3660
|
relation.initRelation(models, name);
|
|
@@ -3666,9 +3727,10 @@ var Builder2 = class extends Builder {
|
|
|
3666
3727
|
const [rawName = "", as] = spec.split(/\s+as\s+/i);
|
|
3667
3728
|
const name = rawName.trim();
|
|
3668
3729
|
const relation = this.getRelation(name);
|
|
3669
|
-
const
|
|
3730
|
+
const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this);
|
|
3731
|
+
const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql);
|
|
3670
3732
|
const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
|
|
3671
|
-
|
|
3733
|
+
query.select(expression);
|
|
3672
3734
|
query.wheres.push(...relation.wheres);
|
|
3673
3735
|
if (constraint) query.callScope((q) => constraint(q));
|
|
3674
3736
|
const scoped = query.applyScopes();
|
|
@@ -3768,8 +3830,8 @@ var Builder2 = class extends Builder {
|
|
|
3768
3830
|
isMalformedKey(id) {
|
|
3769
3831
|
return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
|
|
3770
3832
|
}
|
|
3771
|
-
/** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
|
|
3772
3833
|
async find(id) {
|
|
3834
|
+
if (Array.isArray(id)) return this.findMany(id);
|
|
3773
3835
|
if (this.isMalformedKey(id)) return void 0;
|
|
3774
3836
|
return this.clone().whereKey(id).first();
|
|
3775
3837
|
}
|
|
@@ -4279,6 +4341,7 @@ function resolveMorphClass(type) {
|
|
|
4279
4341
|
}
|
|
4280
4342
|
|
|
4281
4343
|
// Eloquent/Relations/Relation.ts
|
|
4344
|
+
var selfAliases = 0;
|
|
4282
4345
|
var Relation = class extends Builder2 {
|
|
4283
4346
|
constructor(related, parent) {
|
|
4284
4347
|
super(related);
|
|
@@ -4302,6 +4365,32 @@ var Relation = class extends Builder2 {
|
|
|
4302
4365
|
getRelated() {
|
|
4303
4366
|
return this.model;
|
|
4304
4367
|
}
|
|
4368
|
+
/**
|
|
4369
|
+
* When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
|
|
4370
|
+
* under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
|
|
4371
|
+
* table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
|
|
4372
|
+
* undefined when the tables differ.
|
|
4373
|
+
*/
|
|
4374
|
+
aliasSelfTable(query) {
|
|
4375
|
+
const table = query.getModel().getTable();
|
|
4376
|
+
if (table !== this.parent.getTable()) return void 0;
|
|
4377
|
+
const alias = `oriel_reserved_${selfAliases++}`;
|
|
4378
|
+
query.from(`${table} as ${alias}`);
|
|
4379
|
+
query.getModel().setTable(alias);
|
|
4380
|
+
return alias;
|
|
4381
|
+
}
|
|
4382
|
+
/**
|
|
4383
|
+
* @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
|
|
4384
|
+
* on the relations that know the column holding the parent's key.
|
|
4385
|
+
*/
|
|
4386
|
+
limitEagerPerParent() {
|
|
4387
|
+
const column = this.eagerPartitionColumn();
|
|
4388
|
+
if (column !== void 0) this.limitPerGroup(column);
|
|
4389
|
+
}
|
|
4390
|
+
/** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
|
|
4391
|
+
eagerPartitionColumn() {
|
|
4392
|
+
return void 0;
|
|
4393
|
+
}
|
|
4305
4394
|
/** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
|
|
4306
4395
|
init() {
|
|
4307
4396
|
if (relationConstraintsEnabled()) this.addConstraints();
|
|
@@ -4386,6 +4475,7 @@ var BelongsTo = class extends Relation {
|
|
|
4386
4475
|
return this.associate(null);
|
|
4387
4476
|
}
|
|
4388
4477
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
4478
|
+
this.aliasSelfTable(query);
|
|
4389
4479
|
return query.select(...columns).whereColumn(this.getQualifiedForeignKeyName(), "=", this.getQualifiedOwnerKeyName());
|
|
4390
4480
|
}
|
|
4391
4481
|
/** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
|
|
@@ -4480,7 +4570,11 @@ var BelongsToMany = class extends Relation {
|
|
|
4480
4570
|
for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
|
|
4481
4571
|
return models;
|
|
4482
4572
|
}
|
|
4573
|
+
eagerPartitionColumn() {
|
|
4574
|
+
return this.qualifyPivotColumn(this.foreignPivotKey);
|
|
4575
|
+
}
|
|
4483
4576
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
4577
|
+
this.aliasSelfTable(query);
|
|
4484
4578
|
return query.select(...columns).join(this.table, this.model.qualifyColumn(this.relatedKey), "=", this.qualifyPivotColumn(this.relatedPivotKey)).whereColumn(this.parent.qualifyColumn(this.parentKey), "=", this.qualifyPivotColumn(this.foreignPivotKey));
|
|
4485
4579
|
}
|
|
4486
4580
|
// ---------------------------------------------------------------- the pivot table
|
|
@@ -4762,9 +4856,17 @@ var HasOneOrMany = class extends Relation {
|
|
|
4762
4856
|
for (const record of records) created.push(await this.create(record));
|
|
4763
4857
|
return created;
|
|
4764
4858
|
}
|
|
4859
|
+
eagerPartitionColumn() {
|
|
4860
|
+
return this.foreignKey;
|
|
4861
|
+
}
|
|
4765
4862
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
4766
|
-
|
|
4767
|
-
|
|
4863
|
+
const alias = this.aliasSelfTable(query);
|
|
4864
|
+
const foreignKey = alias === void 0 ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`;
|
|
4865
|
+
query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", foreignKey);
|
|
4866
|
+
if (this.morph) {
|
|
4867
|
+
const type = alias === void 0 ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf(".") + 1)}`;
|
|
4868
|
+
query.where(type, "=", this.morph.value);
|
|
4869
|
+
}
|
|
4768
4870
|
return query;
|
|
4769
4871
|
}
|
|
4770
4872
|
};
|
|
@@ -4908,7 +5010,11 @@ var Factory = class _Factory {
|
|
|
4908
5010
|
const name = relationship ?? Str5.camel(Str5.plural(new factory.model().constructor.name));
|
|
4909
5011
|
return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
|
|
4910
5012
|
}
|
|
4911
|
-
/**
|
|
5013
|
+
/**
|
|
5014
|
+
* Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
|
|
5015
|
+
* once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
|
|
5016
|
+
* never points at a parent an earlier test rolled back.
|
|
5017
|
+
*/
|
|
4912
5018
|
for(parent, relationship) {
|
|
4913
5019
|
const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
|
|
4914
5020
|
return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str5.camel(cls.name) }] });
|
|
@@ -4922,7 +5028,8 @@ var Factory = class _Factory {
|
|
|
4922
5028
|
/** The attributes only, without a model (a Row, or a Row[] after count()). */
|
|
4923
5029
|
async raw(attributes = {}) {
|
|
4924
5030
|
const rows = [];
|
|
4925
|
-
|
|
5031
|
+
const parents = /* @__PURE__ */ new Map();
|
|
5032
|
+
for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents));
|
|
4926
5033
|
return this.countValue === void 0 ? rows[0] : rows;
|
|
4927
5034
|
}
|
|
4928
5035
|
/** Unsaved models (afterMaking callbacks run). */
|
|
@@ -4960,20 +5067,21 @@ var Factory = class _Factory {
|
|
|
4960
5067
|
}
|
|
4961
5068
|
async makeModels(attributes) {
|
|
4962
5069
|
const models = [];
|
|
5070
|
+
const parents = /* @__PURE__ */ new Map();
|
|
4963
5071
|
for (let index = 0; index < (this.countValue ?? 1); index++) {
|
|
4964
|
-
const model = new this.model().forceFill(await this.attributesFor(attributes, index));
|
|
5072
|
+
const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents));
|
|
4965
5073
|
for (const callback of this.afterMakingCallbacks) await callback(model);
|
|
4966
5074
|
models.push(model);
|
|
4967
5075
|
}
|
|
4968
5076
|
return models;
|
|
4969
5077
|
}
|
|
4970
5078
|
/** definition() + states + overrides + for() parents, with factory and function values expanded. */
|
|
4971
|
-
async attributesFor(overrides, index) {
|
|
5079
|
+
async attributesFor(overrides, index, parents = /* @__PURE__ */ new Map()) {
|
|
4972
5080
|
const context = { index, count: this.countValue ?? 1 };
|
|
4973
5081
|
let attributes = this.definition();
|
|
4974
5082
|
for (const state of this.states) attributes = { ...attributes, ...typeof state === "function" ? state(attributes, context) : state };
|
|
4975
5083
|
attributes = { ...attributes, ...overrides };
|
|
4976
|
-
for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent));
|
|
5084
|
+
for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents));
|
|
4977
5085
|
const expanded = {};
|
|
4978
5086
|
for (const [key, value] of Object.entries(attributes)) {
|
|
4979
5087
|
if (value instanceof _Factory) expanded[key] = (await value.createOne()).getKey();
|
|
@@ -4983,8 +5091,12 @@ var Factory = class _Factory {
|
|
|
4983
5091
|
}
|
|
4984
5092
|
return expanded;
|
|
4985
5093
|
}
|
|
4986
|
-
async parentAttributes(parent) {
|
|
4987
|
-
|
|
5094
|
+
async parentAttributes(parent, parents) {
|
|
5095
|
+
let resolved = parents.get(parent);
|
|
5096
|
+
if (resolved === void 0) {
|
|
5097
|
+
resolved = parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
|
|
5098
|
+
parents.set(parent, resolved);
|
|
5099
|
+
}
|
|
4988
5100
|
const relation = this.relationOn(new this.model(), parent.relationship);
|
|
4989
5101
|
if (relation instanceof MorphTo) {
|
|
4990
5102
|
return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() };
|
|
@@ -5028,7 +5140,7 @@ async function discoverFactories(path) {
|
|
|
5028
5140
|
}
|
|
5029
5141
|
|
|
5030
5142
|
// Eloquent/events.ts
|
|
5031
|
-
import { AsyncLocalStorage as
|
|
5143
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
5032
5144
|
import { EventDispatcher } from "@orieljs/contracts";
|
|
5033
5145
|
import { currentContainer as currentContainer2 } from "@orieljs/container";
|
|
5034
5146
|
var MODEL_EVENTS = [
|
|
@@ -5046,7 +5158,7 @@ var MODEL_EVENTS = [
|
|
|
5046
5158
|
"forceDeleting",
|
|
5047
5159
|
"forceDeleted"
|
|
5048
5160
|
];
|
|
5049
|
-
var muted = new
|
|
5161
|
+
var muted = new AsyncLocalStorage3();
|
|
5050
5162
|
function modelEventName(event, className) {
|
|
5051
5163
|
return `eloquent.${event}: ${className}`;
|
|
5052
5164
|
}
|
|
@@ -5271,7 +5383,7 @@ var prototypes = /* @__PURE__ */ new Map();
|
|
|
5271
5383
|
var unguardedGlobally = { value: false };
|
|
5272
5384
|
var addingDefaultCounts = /* @__PURE__ */ new Set();
|
|
5273
5385
|
var PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5274
|
-
var unguardedScope = new
|
|
5386
|
+
var unguardedScope = new AsyncLocalStorage4();
|
|
5275
5387
|
var globalScopes = /* @__PURE__ */ new Map();
|
|
5276
5388
|
var anonymousScopes = 0;
|
|
5277
5389
|
function installScopeProxies(cls) {
|
|
@@ -6300,8 +6412,11 @@ var Model = class _Model {
|
|
|
6300
6412
|
}
|
|
6301
6413
|
async incrementOrDecrement(column, amount, extra) {
|
|
6302
6414
|
if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra);
|
|
6303
|
-
const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
|
|
6304
6415
|
this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount });
|
|
6416
|
+
if (await this.fireModelEvent("updating") === false) return 0;
|
|
6417
|
+
const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
|
|
6418
|
+
this.syncChanges();
|
|
6419
|
+
await this.fireModelEvent("updated", false);
|
|
6305
6420
|
this.syncOriginalAttributes(column, ...Object.keys(extra));
|
|
6306
6421
|
return affected;
|
|
6307
6422
|
}
|
|
@@ -7172,12 +7287,14 @@ var TypeGenerator = class {
|
|
|
7172
7287
|
const members = attributes.filter(([column]) => !(column in instance));
|
|
7173
7288
|
const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance));
|
|
7174
7289
|
const statics = scopes(model).filter(([method]) => !(method in Model));
|
|
7290
|
+
const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column));
|
|
7175
7291
|
const lines = [
|
|
7176
7292
|
`declare module '${this.modulePath(file)}' {`,
|
|
7177
7293
|
` interface ${name} {`,
|
|
7178
7294
|
" $attributes?: {",
|
|
7179
7295
|
...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
|
|
7180
7296
|
" }",
|
|
7297
|
+
...hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(" | ")}`] : [],
|
|
7181
7298
|
...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
|
|
7182
7299
|
...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),
|
|
7183
7300
|
" }"
|