@guren/orm 1.0.0-rc.9 → 1.0.1
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/drizzle.d.ts +1 -1
- package/dist/drizzle.js +2 -0
- package/dist/index.d.ts +151 -35
- package/dist/index.js +501 -161
- package/package.json +4 -6
package/dist/index.js
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
// src/instance-guard.ts
|
|
2
|
+
var INSTANCE_KEY = /* @__PURE__ */ Symbol.for("guren.orm.loaded");
|
|
3
|
+
var globalScope = globalThis;
|
|
4
|
+
var marker = globalScope[INSTANCE_KEY];
|
|
5
|
+
if (!marker) {
|
|
6
|
+
globalScope[INSTANCE_KEY] = { count: 1, warned: false };
|
|
7
|
+
} else {
|
|
8
|
+
marker.count += 1;
|
|
9
|
+
const quiet = typeof process !== "undefined" && process.env.GUREN_QUIET_DUPLICATE_ORM === "1";
|
|
10
|
+
if (!marker.warned && !quiet) {
|
|
11
|
+
marker.warned = true;
|
|
12
|
+
console.warn(
|
|
13
|
+
`[guren/orm] ${marker.count} copies of @guren/orm are loaded in this process. Adapter configuration and model state are NOT shared between copies, so database access will fail with "database has not been configured" for models imported through the extra copy.
|
|
14
|
+
[guren/orm] This usually means mixed @guren/* versions (check \`bun pm ls | grep @guren\`). Fix it by aligning all @guren/* packages to the same release, e.g. \`bunx guren upgrade\` or updating every @guren/* entry in package.json together, then reinstalling. Set GUREN_QUIET_DUPLICATE_ORM=1 to silence this warning (e.g. monorepo dev where src and dist copies coexist by design).`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
1
19
|
// src/adapters/drizzle-adapter.ts
|
|
2
20
|
import { and as and2, asc, count, desc, eq as eq2, inArray as inArray2, isNull as isNull2 } from "drizzle-orm";
|
|
3
21
|
|
|
@@ -204,6 +222,16 @@ async function resolveMutation(result) {
|
|
|
204
222
|
function isPromiseLike(value) {
|
|
205
223
|
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
206
224
|
}
|
|
225
|
+
async function resolveWithReturning(query) {
|
|
226
|
+
if (query && typeof query === "object" && "returning" in query && typeof query.returning === "function") {
|
|
227
|
+
const rows = await query.returning();
|
|
228
|
+
return {
|
|
229
|
+
usedReturning: true,
|
|
230
|
+
row: Array.isArray(rows) ? rows[0] : rows
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
return { usedReturning: false, row: void 0 };
|
|
234
|
+
}
|
|
207
235
|
var DrizzleAdapter = {
|
|
208
236
|
configure(db) {
|
|
209
237
|
database = db;
|
|
@@ -268,7 +296,10 @@ var DrizzleAdapter = {
|
|
|
268
296
|
},
|
|
269
297
|
async create(table, data, writeOptions) {
|
|
270
298
|
const db = resolveExecutor(writeOptions);
|
|
271
|
-
const
|
|
299
|
+
const query = db.insert(table).values(data);
|
|
300
|
+
const { usedReturning, row } = await resolveWithReturning(query);
|
|
301
|
+
if (usedReturning) return row;
|
|
302
|
+
const result = await resolveMutation(query);
|
|
272
303
|
return result;
|
|
273
304
|
},
|
|
274
305
|
async update(table, where, data, writeOptions) {
|
|
@@ -277,8 +308,10 @@ var DrizzleAdapter = {
|
|
|
277
308
|
throw new Error("DrizzleAdapter: configured database does not support updates.");
|
|
278
309
|
}
|
|
279
310
|
const clause = resolveWhere(table, where);
|
|
280
|
-
const
|
|
281
|
-
const
|
|
311
|
+
const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
|
|
312
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
313
|
+
if (usedReturning) return row;
|
|
314
|
+
const result = await resolveMutation(finalQuery);
|
|
282
315
|
return result;
|
|
283
316
|
},
|
|
284
317
|
async delete(table, where, writeOptions) {
|
|
@@ -287,8 +320,10 @@ var DrizzleAdapter = {
|
|
|
287
320
|
throw new Error("DrizzleAdapter: configured database does not support deletes.");
|
|
288
321
|
}
|
|
289
322
|
const clause = resolveWhere(table, where);
|
|
290
|
-
const
|
|
291
|
-
const
|
|
323
|
+
const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
|
|
324
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
325
|
+
if (usedReturning) return row;
|
|
326
|
+
const result = await resolveMutation(finalQuery);
|
|
292
327
|
return result;
|
|
293
328
|
},
|
|
294
329
|
async findManyAdvanced(table, conditions, options, queryOptions) {
|
|
@@ -350,8 +385,10 @@ var DrizzleAdapter = {
|
|
|
350
385
|
throw new Error("DrizzleAdapter: configured database does not support updates.");
|
|
351
386
|
}
|
|
352
387
|
const clause = buildDrizzleConditions(table, conditions);
|
|
353
|
-
const
|
|
354
|
-
const
|
|
388
|
+
const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
|
|
389
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
390
|
+
if (usedReturning) return row;
|
|
391
|
+
const result = await resolveMutation(finalQuery);
|
|
355
392
|
return result;
|
|
356
393
|
},
|
|
357
394
|
async deleteAdvanced(table, conditions, writeOptions) {
|
|
@@ -360,8 +397,10 @@ var DrizzleAdapter = {
|
|
|
360
397
|
throw new Error("DrizzleAdapter: configured database does not support deletes.");
|
|
361
398
|
}
|
|
362
399
|
const clause = buildDrizzleConditions(table, conditions);
|
|
363
|
-
const
|
|
364
|
-
const
|
|
400
|
+
const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
|
|
401
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
402
|
+
if (usedReturning) return row;
|
|
403
|
+
const result = await resolveMutation(finalQuery);
|
|
365
404
|
return result;
|
|
366
405
|
},
|
|
367
406
|
async transaction(callback) {
|
|
@@ -456,7 +495,7 @@ var ModelNotFoundException = class extends Error {
|
|
|
456
495
|
modelName;
|
|
457
496
|
modelId;
|
|
458
497
|
constructor(modelName, id, key = "id") {
|
|
459
|
-
super(`${modelName} not found for ${key}=${String(id)}`);
|
|
498
|
+
super(id === void 0 ? `${modelName} not found` : `${modelName} not found for ${key}=${String(id)}`);
|
|
460
499
|
this.name = "ModelNotFoundException";
|
|
461
500
|
this.modelName = modelName;
|
|
462
501
|
this.modelId = id;
|
|
@@ -483,14 +522,14 @@ var QueryBuilder = class {
|
|
|
483
522
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
484
523
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
485
524
|
if (val !== void 0) {
|
|
486
|
-
this.addSimpleCondition(key, "=", val);
|
|
525
|
+
this.addSimpleCondition(key, Array.isArray(val) ? "in" : "=", val);
|
|
487
526
|
}
|
|
488
527
|
}
|
|
489
528
|
return this;
|
|
490
529
|
}
|
|
491
530
|
const field = fieldOrConditions;
|
|
492
531
|
if (arguments.length === 2) {
|
|
493
|
-
this.addSimpleCondition(field, "=", operatorOrValue);
|
|
532
|
+
this.addSimpleCondition(field, Array.isArray(operatorOrValue) ? "in" : "=", operatorOrValue);
|
|
494
533
|
} else {
|
|
495
534
|
this.addSimpleCondition(field, operatorOrValue, value);
|
|
496
535
|
}
|
|
@@ -501,13 +540,13 @@ var QueryBuilder = class {
|
|
|
501
540
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
502
541
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
503
542
|
if (val !== void 0) {
|
|
504
|
-
orConditions.push({ type: "simple", field: key, operator: "=", value: val });
|
|
543
|
+
orConditions.push({ type: "simple", field: key, operator: Array.isArray(val) ? "in" : "=", value: val });
|
|
505
544
|
}
|
|
506
545
|
}
|
|
507
546
|
} else {
|
|
508
547
|
const field = fieldOrConditions;
|
|
509
548
|
if (arguments.length === 2) {
|
|
510
|
-
orConditions.push({ type: "simple", field, operator: "=", value: operatorOrValue });
|
|
549
|
+
orConditions.push({ type: "simple", field, operator: Array.isArray(operatorOrValue) ? "in" : "=", value: operatorOrValue });
|
|
511
550
|
} else {
|
|
512
551
|
orConditions.push({ type: "simple", field, operator: operatorOrValue, value });
|
|
513
552
|
}
|
|
@@ -669,12 +708,12 @@ var QueryBuilder = class {
|
|
|
669
708
|
/**
|
|
670
709
|
* Execute the query and return the first matching record, or throw.
|
|
671
710
|
* @returns The first record
|
|
672
|
-
* @throws
|
|
711
|
+
* @throws ModelNotFoundException (404) if no record matches
|
|
673
712
|
*/
|
|
674
713
|
async firstOrFail() {
|
|
675
714
|
const record = await this.first();
|
|
676
715
|
if (record === null) {
|
|
677
|
-
throw new
|
|
716
|
+
throw new ModelNotFoundException(this.modelClass.name);
|
|
678
717
|
}
|
|
679
718
|
return record;
|
|
680
719
|
}
|
|
@@ -693,13 +732,9 @@ var QueryBuilder = class {
|
|
|
693
732
|
const results = await this.executeQuery();
|
|
694
733
|
return results.length;
|
|
695
734
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
* @param perPage - Records per page (default: 15)
|
|
700
|
-
* @returns Paginated result with data and metadata
|
|
701
|
-
*/
|
|
702
|
-
async paginate(page = 1, perPage = DEFAULT_PAGINATION_SIZE) {
|
|
735
|
+
async paginate(pageOrOptions = 1, perPageArg = DEFAULT_PAGINATION_SIZE) {
|
|
736
|
+
const page = typeof pageOrOptions === "object" ? pageOrOptions.page ?? 1 : pageOrOptions;
|
|
737
|
+
const perPage = typeof pageOrOptions === "object" ? pageOrOptions.perPage ?? DEFAULT_PAGINATION_SIZE : perPageArg;
|
|
703
738
|
const sanitizedPage = Number.isFinite(page) && page >= 1 ? Math.floor(page) : 1;
|
|
704
739
|
const sanitizedPerPage = Number.isFinite(perPage) && perPage >= 1 ? Math.floor(perPage) : DEFAULT_PAGINATION_SIZE;
|
|
705
740
|
const total = await this.count();
|
|
@@ -728,20 +763,38 @@ var QueryBuilder = class {
|
|
|
728
763
|
}
|
|
729
764
|
/**
|
|
730
765
|
* Bulk update records matching the current conditions.
|
|
766
|
+
*
|
|
767
|
+
* Mass-assignment protection applies exactly as in `Model.update()`:
|
|
768
|
+
* with a `fillable` allowlist, out-of-allowlist keys throw a
|
|
769
|
+
* MassAssignmentException. Note that bulk updates skip model hooks,
|
|
770
|
+
* observers, mutators, and casts by design.
|
|
771
|
+
*
|
|
731
772
|
* @param data - Data to set on matching records
|
|
732
773
|
* @returns The updated record (adapter-dependent)
|
|
733
774
|
*/
|
|
734
775
|
async update(data) {
|
|
776
|
+
return this.runBulkUpdate(data, true);
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Bulk update bypassing mass-assignment protection. Use for trusted,
|
|
780
|
+
* server-side-assembled data — never for raw request input.
|
|
781
|
+
*/
|
|
782
|
+
async forceUpdate(data) {
|
|
783
|
+
return this.runBulkUpdate(data, false);
|
|
784
|
+
}
|
|
785
|
+
async runBulkUpdate(data, applyFillable) {
|
|
735
786
|
if (!this.adapter.update) {
|
|
736
787
|
throw new Error("Configured adapter does not support update operations.");
|
|
737
788
|
}
|
|
789
|
+
const model = this.modelClass;
|
|
790
|
+
const payload = applyFillable ? model.filterFillable(data) : { ...data };
|
|
738
791
|
const advancedAdapter = this.adapter;
|
|
739
792
|
if (typeof advancedAdapter.updateAdvanced === "function") {
|
|
740
|
-
return advancedAdapter.updateAdvanced(this.table, this.conditions,
|
|
793
|
+
return advancedAdapter.updateAdvanced(this.table, this.conditions, payload, { trx: this.options.trx });
|
|
741
794
|
}
|
|
742
795
|
const simpleWhere = this.toSimpleWhereClause();
|
|
743
796
|
if (simpleWhere) {
|
|
744
|
-
return this.adapter.update(this.table, simpleWhere,
|
|
797
|
+
return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
|
|
745
798
|
}
|
|
746
799
|
throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
|
|
747
800
|
}
|
|
@@ -844,70 +897,20 @@ var QueryBuilder = class {
|
|
|
844
897
|
}
|
|
845
898
|
/**
|
|
846
899
|
* Load eager relations onto fetched results.
|
|
847
|
-
* Supports dot notation for nested relations
|
|
900
|
+
* Supports dot notation for nested relations at any depth
|
|
901
|
+
* (e.g., 'posts.comments.author') — the full path is delegated to
|
|
902
|
+
* Model.loadRelationInto, which recurses through the relation chain.
|
|
848
903
|
*/
|
|
849
904
|
loadEagerRelations = async (results) => {
|
|
850
905
|
if (this.eagerLoad.length === 0 || results.length === 0) return results;
|
|
851
906
|
const copies = results.map((r) => ({ ...r }));
|
|
852
907
|
const model = this.modelClass;
|
|
853
908
|
for (const relation of this.eagerLoad) {
|
|
854
|
-
|
|
855
|
-
const topLevel = parts[0];
|
|
856
|
-
await model.loadRelationInto(copies, topLevel);
|
|
857
|
-
if (parts.length > 1) {
|
|
858
|
-
const nestedName = parts.slice(1).join(".");
|
|
859
|
-
const nestedRecords = [];
|
|
860
|
-
for (const record of copies) {
|
|
861
|
-
const related = record[topLevel];
|
|
862
|
-
if (Array.isArray(related)) {
|
|
863
|
-
nestedRecords.push(...related);
|
|
864
|
-
} else if (related && typeof related === "object") {
|
|
865
|
-
nestedRecords.push(related);
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
if (nestedRecords.length > 0) {
|
|
869
|
-
const topDef = model.getRelationDefinition(topLevel);
|
|
870
|
-
if (topDef) {
|
|
871
|
-
const relatedModel = await resolveRelatedModel(topDef.related);
|
|
872
|
-
if (relatedModel) {
|
|
873
|
-
const nestedModel = relatedModel;
|
|
874
|
-
const nestedParts = parts.slice(1);
|
|
875
|
-
await nestedModel.loadRelationInto(nestedRecords, nestedParts[0]);
|
|
876
|
-
if (nestedParts.length > 1) {
|
|
877
|
-
for (let i = 1; i < nestedParts.length; i++) {
|
|
878
|
-
const subRecords = [];
|
|
879
|
-
for (const nr of nestedRecords) {
|
|
880
|
-
const sub = nr[nestedParts[i - 1]];
|
|
881
|
-
if (Array.isArray(sub)) subRecords.push(...sub);
|
|
882
|
-
else if (sub && typeof sub === "object") subRecords.push(sub);
|
|
883
|
-
}
|
|
884
|
-
if (subRecords.length === 0) break;
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
}
|
|
909
|
+
await model.loadRelationInto(copies, relation);
|
|
891
910
|
}
|
|
892
911
|
return copies;
|
|
893
912
|
};
|
|
894
913
|
};
|
|
895
|
-
async function resolveRelatedModel(reference) {
|
|
896
|
-
if (typeof reference === "function" && "prototype" in reference) {
|
|
897
|
-
try {
|
|
898
|
-
if (reference.resolveTable) return reference;
|
|
899
|
-
} catch {
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
if (typeof reference === "function") {
|
|
903
|
-
try {
|
|
904
|
-
return await reference();
|
|
905
|
-
} catch {
|
|
906
|
-
return null;
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
return null;
|
|
910
|
-
}
|
|
911
914
|
|
|
912
915
|
// src/serialization.ts
|
|
913
916
|
function serializeRecord(record, options) {
|
|
@@ -936,6 +939,21 @@ function serializeRecords(records, options) {
|
|
|
936
939
|
return records.map((r) => serializeRecord(r, options));
|
|
937
940
|
}
|
|
938
941
|
|
|
942
|
+
// src/MassAssignmentException.ts
|
|
943
|
+
var MassAssignmentException = class extends Error {
|
|
944
|
+
model;
|
|
945
|
+
fields;
|
|
946
|
+
constructor(model, fields) {
|
|
947
|
+
const list = fields.map((field) => `"${field}"`).join(", ");
|
|
948
|
+
super(
|
|
949
|
+
`${model}: mass assignment blocked for field(s) ${list} \u2014 not listed in ${model}.fillable. Add them to fillable, use ${model}.forceCreate()/forceUpdate() for trusted server-side data, or set \`static strictFillable = false\` to restore silent discarding.`
|
|
950
|
+
);
|
|
951
|
+
this.name = "MassAssignmentException";
|
|
952
|
+
this.model = model;
|
|
953
|
+
this.fields = fields;
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
|
|
939
957
|
// src/Model.ts
|
|
940
958
|
var DEFAULT_PAGINATION_SIZE = 15;
|
|
941
959
|
var Model = class _Model {
|
|
@@ -1004,7 +1022,12 @@ var Model = class _Model {
|
|
|
1004
1022
|
static casts;
|
|
1005
1023
|
/**
|
|
1006
1024
|
* Whitelist of fields allowed for mass assignment.
|
|
1007
|
-
* If set,
|
|
1025
|
+
* If set, `create()` and `update()` accept only these fields — input
|
|
1026
|
+
* containing any other key throws a MassAssignmentException so bugs
|
|
1027
|
+
* (and injection attempts) surface immediately instead of being
|
|
1028
|
+
* silently discarded. Use `forceCreate()` / `forceUpdate()` for
|
|
1029
|
+
* trusted server-side data, or set `strictFillable = false` to
|
|
1030
|
+
* restore silent discarding.
|
|
1008
1031
|
*
|
|
1009
1032
|
* @example
|
|
1010
1033
|
* class User extends Model<UserRecord> {
|
|
@@ -1012,6 +1035,12 @@ var Model = class _Model {
|
|
|
1012
1035
|
* }
|
|
1013
1036
|
*/
|
|
1014
1037
|
static fillable;
|
|
1038
|
+
/**
|
|
1039
|
+
* When `fillable` is set, controls what happens to input fields outside
|
|
1040
|
+
* the allowlist: `true` (default) throws a MassAssignmentException,
|
|
1041
|
+
* `false` silently discards them (pre-1.0 behavior).
|
|
1042
|
+
*/
|
|
1043
|
+
static strictFillable;
|
|
1015
1044
|
/**
|
|
1016
1045
|
* Blacklist of fields excluded from mass assignment.
|
|
1017
1046
|
* Defaults to `['id']`. Ignored if `fillable` is set.
|
|
@@ -1314,6 +1343,12 @@ var Model = class _Model {
|
|
|
1314
1343
|
static filterFillable(data) {
|
|
1315
1344
|
const fillableFields = this.fillable;
|
|
1316
1345
|
if (fillableFields) {
|
|
1346
|
+
if (this.strictFillable !== false) {
|
|
1347
|
+
const blocked = Object.keys(data).filter((key) => !fillableFields.includes(key));
|
|
1348
|
+
if (blocked.length > 0) {
|
|
1349
|
+
throw new MassAssignmentException(this.name, blocked);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1317
1352
|
const filtered2 = {};
|
|
1318
1353
|
for (const key of fillableFields) {
|
|
1319
1354
|
if (key in data) {
|
|
@@ -1906,8 +1941,26 @@ var Model = class _Model {
|
|
|
1906
1941
|
* })
|
|
1907
1942
|
*/
|
|
1908
1943
|
static async create(data, writeOptions) {
|
|
1944
|
+
return this.runCreate(data, writeOptions, true);
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* Create a record bypassing mass-assignment protection. Use for trusted,
|
|
1948
|
+
* server-side-assembled data (OAuth account linking, seeders, system
|
|
1949
|
+
* records) — never for raw request input.
|
|
1950
|
+
*
|
|
1951
|
+
* @example
|
|
1952
|
+
* const user = await User.forceCreate({
|
|
1953
|
+
* name: profile.name,
|
|
1954
|
+
* email: profile.email,
|
|
1955
|
+
* passwordHash: `oauth:${provider}:${profile.id}`,
|
|
1956
|
+
* })
|
|
1957
|
+
*/
|
|
1958
|
+
static async forceCreate(data, writeOptions) {
|
|
1959
|
+
return this.runCreate(data, writeOptions, false);
|
|
1960
|
+
}
|
|
1961
|
+
static async runCreate(data, writeOptions, applyFillable) {
|
|
1909
1962
|
const table = this.resolveTable();
|
|
1910
|
-
const filtered = this.filterFillable(data);
|
|
1963
|
+
const filtered = applyFillable ? this.filterFillable(data) : { ...data };
|
|
1911
1964
|
const payload = await this.preparePersistencePayload(filtered);
|
|
1912
1965
|
const hooks = this.hooks;
|
|
1913
1966
|
const observers = this.observers;
|
|
@@ -1954,12 +2007,22 @@ var Model = class _Model {
|
|
|
1954
2007
|
* await User.update({ id: 1 }, { name: 'Jane Doe' })
|
|
1955
2008
|
*/
|
|
1956
2009
|
static async update(where, data, writeOptions) {
|
|
2010
|
+
return this.runUpdate(where, data, writeOptions, true);
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
2013
|
+
* Update records bypassing mass-assignment protection. Use for trusted,
|
|
2014
|
+
* server-side-assembled data — never for raw request input.
|
|
2015
|
+
*/
|
|
2016
|
+
static async forceUpdate(where, data, writeOptions) {
|
|
2017
|
+
return this.runUpdate(where, data, writeOptions, false);
|
|
2018
|
+
}
|
|
2019
|
+
static async runUpdate(where, data, writeOptions, applyFillable) {
|
|
1957
2020
|
const table = this.resolveTable();
|
|
1958
2021
|
const adapter = this.getAdapter();
|
|
1959
2022
|
if (!adapter.update) {
|
|
1960
2023
|
throw new Error("Configured adapter does not support update operations.");
|
|
1961
2024
|
}
|
|
1962
|
-
const filtered = this.filterFillable(data);
|
|
2025
|
+
const filtered = applyFillable ? this.filterFillable(data) : { ...data };
|
|
1963
2026
|
const payload = await this.preparePersistencePayload(filtered);
|
|
1964
2027
|
const hooks = this.hooks;
|
|
1965
2028
|
const observers = this.observers;
|
|
@@ -2080,35 +2143,141 @@ var Model = class _Model {
|
|
|
2080
2143
|
}
|
|
2081
2144
|
return copies;
|
|
2082
2145
|
}
|
|
2083
|
-
|
|
2084
|
-
|
|
2146
|
+
static async withCount(relations, where) {
|
|
2147
|
+
const records = where ? await this.where(where) : await this.all();
|
|
2148
|
+
if (!records.length) {
|
|
2149
|
+
return records;
|
|
2150
|
+
}
|
|
2151
|
+
const relationList = normalizeRelations(relations);
|
|
2152
|
+
const copies = records.map((record) => ({ ...record }));
|
|
2153
|
+
for (const relationName of relationList) {
|
|
2154
|
+
await this.loadRelationCountInto(copies, relationName);
|
|
2155
|
+
}
|
|
2156
|
+
return copies;
|
|
2157
|
+
}
|
|
2158
|
+
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
2159
|
+
static async loadRelationCountInto(records, relationName) {
|
|
2160
|
+
if (relationName.includes(".")) {
|
|
2161
|
+
throw new Error(`${this.name}: withCount does not support nested relation "${relationName}".`);
|
|
2162
|
+
}
|
|
2085
2163
|
const definition = this.getRelationDefinition(relationName);
|
|
2086
2164
|
if (!definition) {
|
|
2087
2165
|
throw new Error(`${this.name}: unknown relation "${relationName}".`);
|
|
2088
2166
|
}
|
|
2167
|
+
const countField = `${relationName}Count`;
|
|
2089
2168
|
switch (definition.type) {
|
|
2090
2169
|
case "hasMany":
|
|
2091
|
-
|
|
2170
|
+
case "hasOne": {
|
|
2171
|
+
const related = await resolveModelReference(definition.related);
|
|
2172
|
+
const { foreignKey, localKey } = definition;
|
|
2173
|
+
const values = Array.from(
|
|
2174
|
+
new Set(records.map((record) => record[localKey]).filter((value) => value != null))
|
|
2175
|
+
);
|
|
2176
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2177
|
+
if (values.length > 0) {
|
|
2178
|
+
const relatedRecords = await related.where({ [foreignKey]: values });
|
|
2179
|
+
for (const item of relatedRecords) {
|
|
2180
|
+
const key = item[foreignKey];
|
|
2181
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
for (const record of records) {
|
|
2185
|
+
record[countField] = counts.get(record[localKey]) ?? 0;
|
|
2186
|
+
}
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
case "morphMany": {
|
|
2190
|
+
const withRelation = records.map((record) => ({ ...record }));
|
|
2191
|
+
await this.loadRelationInto(withRelation, relationName);
|
|
2192
|
+
for (const [index, record] of records.entries()) {
|
|
2193
|
+
const value = withRelation[index]?.[relationName];
|
|
2194
|
+
record[countField] = Array.isArray(value) ? value.length : 0;
|
|
2195
|
+
}
|
|
2092
2196
|
return;
|
|
2197
|
+
}
|
|
2198
|
+
case "belongsTo": {
|
|
2199
|
+
const related = await resolveModelReference(definition.related);
|
|
2200
|
+
const { foreignKey, ownerKey } = definition;
|
|
2201
|
+
const values = Array.from(
|
|
2202
|
+
new Set(records.map((record) => record[foreignKey]).filter((value) => value != null))
|
|
2203
|
+
);
|
|
2204
|
+
const ownerKeys = /* @__PURE__ */ new Set();
|
|
2205
|
+
if (values.length > 0) {
|
|
2206
|
+
const owners = await related.where({ [ownerKey]: values });
|
|
2207
|
+
for (const owner of owners) {
|
|
2208
|
+
ownerKeys.add(owner[ownerKey]);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
for (const record of records) {
|
|
2212
|
+
const key = record[foreignKey];
|
|
2213
|
+
record[countField] = key != null && ownerKeys.has(key) ? 1 : 0;
|
|
2214
|
+
}
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
default:
|
|
2218
|
+
throw new Error(
|
|
2219
|
+
`${this.name}: withCount does not support ${definition.type} relation "${relationName}".`
|
|
2220
|
+
);
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
/**
|
|
2224
|
+
* @internal Used by QueryBuilder for eager loading.
|
|
2225
|
+
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
2226
|
+
*/
|
|
2227
|
+
static async loadRelationInto(records, relationName) {
|
|
2228
|
+
const [head, ...rest] = relationName.split(".");
|
|
2229
|
+
const definition = this.getRelationDefinition(head);
|
|
2230
|
+
if (!definition) {
|
|
2231
|
+
throw new Error(`${this.name}: unknown relation "${head}".`);
|
|
2232
|
+
}
|
|
2233
|
+
switch (definition.type) {
|
|
2234
|
+
case "hasMany":
|
|
2235
|
+
await this.loadHasMany(records, definition);
|
|
2236
|
+
break;
|
|
2093
2237
|
case "hasOne":
|
|
2094
2238
|
await this.loadHasOne(records, definition);
|
|
2095
|
-
|
|
2239
|
+
break;
|
|
2096
2240
|
case "belongsTo":
|
|
2097
2241
|
await this.loadBelongsTo(records, definition);
|
|
2098
|
-
|
|
2242
|
+
break;
|
|
2099
2243
|
case "belongsToMany":
|
|
2100
2244
|
await this.loadBelongsToMany(records, definition);
|
|
2101
|
-
|
|
2245
|
+
break;
|
|
2102
2246
|
case "hasManyThrough":
|
|
2103
2247
|
await this.loadHasManyThrough(records, definition);
|
|
2104
|
-
|
|
2248
|
+
break;
|
|
2105
2249
|
case "morphMany":
|
|
2106
2250
|
await this.loadMorphMany(records, definition);
|
|
2107
|
-
|
|
2251
|
+
break;
|
|
2108
2252
|
case "morphTo":
|
|
2109
2253
|
await this.loadMorphTo(records, definition);
|
|
2110
|
-
|
|
2254
|
+
break;
|
|
2255
|
+
}
|
|
2256
|
+
if (rest.length === 0) {
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
if (definition.type === "morphTo") {
|
|
2260
|
+
throw new Error(
|
|
2261
|
+
`${this.name}: nested eager loading through morphTo relation "${head}" is not supported.`
|
|
2262
|
+
);
|
|
2111
2263
|
}
|
|
2264
|
+
const children = [];
|
|
2265
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2266
|
+
for (const record of records) {
|
|
2267
|
+
const value = record[head];
|
|
2268
|
+
const items = Array.isArray(value) ? value : value != null ? [value] : [];
|
|
2269
|
+
for (const item of items) {
|
|
2270
|
+
if (item && typeof item === "object" && !seen.has(item)) {
|
|
2271
|
+
seen.add(item);
|
|
2272
|
+
children.push(item);
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
if (children.length === 0) {
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
const related = await resolveModelReference(definition.related);
|
|
2280
|
+
await related.loadRelationInto(children, rest.join("."));
|
|
2112
2281
|
}
|
|
2113
2282
|
static async loadHasMany(records, definition) {
|
|
2114
2283
|
const { foreignKey, localKey, name } = definition;
|
|
@@ -2422,16 +2591,64 @@ function SoftDeletes(Base) {
|
|
|
2422
2591
|
}
|
|
2423
2592
|
|
|
2424
2593
|
// src/postgres.ts
|
|
2425
|
-
import {
|
|
2426
|
-
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
2427
|
-
import { existsSync, readdirSync } from "fs";
|
|
2428
|
-
import { resolve as resolve2 } from "path";
|
|
2594
|
+
import { resolve as resolve3 } from "path";
|
|
2429
2595
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2430
|
-
|
|
2596
|
+
|
|
2597
|
+
// src/migration-utils.ts
|
|
2598
|
+
import { existsSync, readdirSync } from "fs";
|
|
2599
|
+
import { resolve } from "path";
|
|
2600
|
+
function hasDrizzleMigrations(migrationsFolder) {
|
|
2601
|
+
if (!existsSync(migrationsFolder)) {
|
|
2602
|
+
return false;
|
|
2603
|
+
}
|
|
2604
|
+
const entries = readdirSync(migrationsFolder, { withFileTypes: true });
|
|
2605
|
+
return entries.some(
|
|
2606
|
+
(entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))
|
|
2607
|
+
);
|
|
2608
|
+
}
|
|
2609
|
+
function warnIgnoredFlatSqlMigrations(migrationsFolder) {
|
|
2610
|
+
if (!existsSync(migrationsFolder)) {
|
|
2611
|
+
return;
|
|
2612
|
+
}
|
|
2613
|
+
const flatSqlFiles = readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name);
|
|
2614
|
+
if (flatSqlFiles.length > 0) {
|
|
2615
|
+
console.warn(
|
|
2616
|
+
`[guren/orm] Ignoring ${flatSqlFiles.length} loose .sql file(s) in ${migrationsFolder}: ${flatSqlFiles.join(", ")}.
|
|
2617
|
+
[guren/orm] Migrations must be generated with drizzle-kit (\`bun run db:make\`), which creates one folder per migration.`
|
|
2618
|
+
);
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
function listLocalMigrations(migrationsFolder) {
|
|
2622
|
+
if (!existsSync(migrationsFolder)) {
|
|
2623
|
+
return [];
|
|
2624
|
+
}
|
|
2625
|
+
return readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))).map((entry) => ({ name: entry.name })).sort((a, b) => a.name.localeCompare(b.name));
|
|
2626
|
+
}
|
|
2627
|
+
function buildMigrationStatus(localMigrations, appliedRows) {
|
|
2628
|
+
const appliedByName = /* @__PURE__ */ new Map();
|
|
2629
|
+
for (const row of appliedRows) {
|
|
2630
|
+
if (row.name) {
|
|
2631
|
+
appliedByName.set(row.name, row);
|
|
2632
|
+
}
|
|
2633
|
+
}
|
|
2634
|
+
return localMigrations.map((migration) => {
|
|
2635
|
+
const row = appliedByName.get(migration.name);
|
|
2636
|
+
let appliedAt = null;
|
|
2637
|
+
if (row?.appliedAt) {
|
|
2638
|
+
const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
|
|
2639
|
+
appliedAt = Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
2640
|
+
}
|
|
2641
|
+
return {
|
|
2642
|
+
name: migration.name,
|
|
2643
|
+
applied: row !== void 0,
|
|
2644
|
+
appliedAt
|
|
2645
|
+
};
|
|
2646
|
+
});
|
|
2647
|
+
}
|
|
2431
2648
|
|
|
2432
2649
|
// src/seeder.ts
|
|
2433
2650
|
import { readdir } from "fs/promises";
|
|
2434
|
-
import { extname, resolve } from "path";
|
|
2651
|
+
import { extname, resolve as resolve2 } from "path";
|
|
2435
2652
|
import { fileURLToPath, pathToFileURL } from "url";
|
|
2436
2653
|
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".ts"]);
|
|
2437
2654
|
function normalizeSeeder(candidate) {
|
|
@@ -2476,9 +2693,9 @@ async function loadSeederModule(path) {
|
|
|
2476
2693
|
return void 0;
|
|
2477
2694
|
}
|
|
2478
2695
|
async function loadSeeders(directory) {
|
|
2479
|
-
const root = directory instanceof URL ? fileURLToPath(directory) :
|
|
2696
|
+
const root = directory instanceof URL ? fileURLToPath(directory) : resolve2(directory);
|
|
2480
2697
|
const entries = await readdir(root, { withFileTypes: true });
|
|
2481
|
-
const files = entries.filter((entry) => entry.isFile() && SUPPORTED_EXTENSIONS.has(extname(entry.name))).map((entry) =>
|
|
2698
|
+
const files = entries.filter((entry) => entry.isFile() && SUPPORTED_EXTENSIONS.has(extname(entry.name))).map((entry) => resolve2(root, entry.name)).sort();
|
|
2482
2699
|
const seeders = [];
|
|
2483
2700
|
for (const file of files) {
|
|
2484
2701
|
const handler = await loadSeederModule(file);
|
|
@@ -2499,10 +2716,25 @@ function defineSeeder(handler) {
|
|
|
2499
2716
|
}
|
|
2500
2717
|
|
|
2501
2718
|
// src/postgres.ts
|
|
2719
|
+
async function loadPostgresModules() {
|
|
2720
|
+
try {
|
|
2721
|
+
const [{ drizzle }, { migrate }, postgresModule] = await Promise.all([
|
|
2722
|
+
import("drizzle-orm/postgres-js"),
|
|
2723
|
+
import("drizzle-orm/postgres-js/migrator"),
|
|
2724
|
+
import("postgres")
|
|
2725
|
+
]);
|
|
2726
|
+
return { drizzle, migrate, postgres: postgresModule.default };
|
|
2727
|
+
} catch (error) {
|
|
2728
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2729
|
+
throw new Error(
|
|
2730
|
+
`createPostgresDatabase() requires the "postgres" package. Install it with \`bun add postgres\`. (${reason})`
|
|
2731
|
+
);
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2502
2734
|
function createPostgresDatabase(options) {
|
|
2503
|
-
const {
|
|
2504
|
-
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath2(migrationsFolder) :
|
|
2505
|
-
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath2(seedersFolder) :
|
|
2735
|
+
const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
|
|
2736
|
+
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath2(migrationsFolder) : resolve3(String(migrationsFolder));
|
|
2737
|
+
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath2(seedersFolder) : resolve3(String(seedersFolder));
|
|
2506
2738
|
let migrationsPromise;
|
|
2507
2739
|
let databasePromise;
|
|
2508
2740
|
let client;
|
|
@@ -2520,15 +2752,17 @@ function createPostgresDatabase(options) {
|
|
|
2520
2752
|
}
|
|
2521
2753
|
const promise = (async () => {
|
|
2522
2754
|
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
2755
|
+
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
2523
2756
|
return;
|
|
2524
2757
|
}
|
|
2758
|
+
const { drizzle, migrate, postgres: postgresFactory } = await loadPostgresModules();
|
|
2525
2759
|
const url = resolveConnectionString();
|
|
2526
|
-
const migrationClient =
|
|
2760
|
+
const migrationClient = postgresFactory(url, {
|
|
2527
2761
|
max: 1,
|
|
2528
2762
|
...clientOptions
|
|
2529
2763
|
});
|
|
2530
2764
|
try {
|
|
2531
|
-
const db = drizzle({ client: migrationClient,
|
|
2765
|
+
const db = drizzle({ client: migrationClient, ...relations ? { relations } : {} });
|
|
2532
2766
|
await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
|
|
2533
2767
|
} finally {
|
|
2534
2768
|
await migrationClient.end({ timeout: 0 });
|
|
@@ -2547,12 +2781,13 @@ function createPostgresDatabase(options) {
|
|
|
2547
2781
|
}
|
|
2548
2782
|
const promise = (async () => {
|
|
2549
2783
|
await migrateOnce();
|
|
2784
|
+
const { drizzle, postgres: postgresFactory } = await loadPostgresModules();
|
|
2550
2785
|
const url = resolveConnectionString();
|
|
2551
|
-
client =
|
|
2786
|
+
client = postgresFactory(url, {
|
|
2552
2787
|
max: 1,
|
|
2553
2788
|
...clientOptions
|
|
2554
2789
|
});
|
|
2555
|
-
return drizzle({ client,
|
|
2790
|
+
return drizzle({ client, ...relations ? { relations } : {} });
|
|
2556
2791
|
})();
|
|
2557
2792
|
databasePromise = promise.catch((error) => {
|
|
2558
2793
|
databasePromise = void 0;
|
|
@@ -2579,34 +2814,74 @@ function createPostgresDatabase(options) {
|
|
|
2579
2814
|
const db = await getDatabase();
|
|
2580
2815
|
await runSeeders(db, resolvedSeedersFolder);
|
|
2581
2816
|
}
|
|
2817
|
+
async function withAdminClient(callback) {
|
|
2818
|
+
const { postgres: postgresFactory } = await loadPostgresModules();
|
|
2819
|
+
const adminClient = postgresFactory(resolveConnectionString(), {
|
|
2820
|
+
max: 1,
|
|
2821
|
+
...clientOptions
|
|
2822
|
+
});
|
|
2823
|
+
try {
|
|
2824
|
+
return await callback(adminClient);
|
|
2825
|
+
} finally {
|
|
2826
|
+
await adminClient.end({ timeout: 0 });
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
async function resetDatabase() {
|
|
2830
|
+
await withAdminClient(async (adminClient) => {
|
|
2831
|
+
await adminClient.unsafe("DROP SCHEMA IF EXISTS public CASCADE");
|
|
2832
|
+
await adminClient.unsafe("CREATE SCHEMA public");
|
|
2833
|
+
await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
|
|
2834
|
+
});
|
|
2835
|
+
migrationsPromise = void 0;
|
|
2836
|
+
}
|
|
2837
|
+
async function migrationStatus() {
|
|
2838
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
2839
|
+
if (localMigrations.length === 0) return [];
|
|
2840
|
+
const appliedRows = await withAdminClient(async (adminClient) => {
|
|
2841
|
+
try {
|
|
2842
|
+
const rows = await adminClient.unsafe("SELECT name FROM drizzle.__drizzle_migrations");
|
|
2843
|
+
return rows.map((row) => {
|
|
2844
|
+
const record = row;
|
|
2845
|
+
return { name: record.name, appliedAt: null };
|
|
2846
|
+
});
|
|
2847
|
+
} catch {
|
|
2848
|
+
return [];
|
|
2849
|
+
}
|
|
2850
|
+
});
|
|
2851
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
2852
|
+
}
|
|
2582
2853
|
return {
|
|
2583
2854
|
getDatabase,
|
|
2584
2855
|
migrateDatabase: migrateOnce,
|
|
2585
2856
|
closeDatabase,
|
|
2586
2857
|
configureOrm,
|
|
2587
|
-
seedDatabase
|
|
2858
|
+
seedDatabase,
|
|
2859
|
+
resetDatabase,
|
|
2860
|
+
migrationStatus
|
|
2588
2861
|
};
|
|
2589
2862
|
}
|
|
2590
|
-
function hasDrizzleMigrations(migrationsFolder) {
|
|
2591
|
-
if (!existsSync(migrationsFolder)) {
|
|
2592
|
-
return false;
|
|
2593
|
-
}
|
|
2594
|
-
const entries = readdirSync(migrationsFolder, { withFileTypes: true });
|
|
2595
|
-
return entries.some(
|
|
2596
|
-
(entry) => entry.isDirectory() && existsSync(resolve2(migrationsFolder, entry.name, "migration.sql"))
|
|
2597
|
-
);
|
|
2598
|
-
}
|
|
2599
2863
|
|
|
2600
2864
|
// src/mysql.ts
|
|
2601
|
-
import {
|
|
2602
|
-
import { migrate as migrate2 } from "drizzle-orm/mysql2/migrator";
|
|
2603
|
-
import { existsSync as existsSync2, readdirSync as readdirSync2 } from "fs";
|
|
2604
|
-
import { resolve as resolve3 } from "path";
|
|
2865
|
+
import { resolve as resolve4 } from "path";
|
|
2605
2866
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2867
|
+
async function loadMySqlModules() {
|
|
2868
|
+
try {
|
|
2869
|
+
const [{ drizzle }, { migrate }] = await Promise.all([
|
|
2870
|
+
import("drizzle-orm/mysql2"),
|
|
2871
|
+
import("drizzle-orm/mysql2/migrator")
|
|
2872
|
+
]);
|
|
2873
|
+
return { drizzle, migrate };
|
|
2874
|
+
} catch (error) {
|
|
2875
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2876
|
+
throw new Error(
|
|
2877
|
+
`createMySqlDatabase() requires the "mysql2" package. Install it with \`bun add mysql2\`. (${reason})`
|
|
2878
|
+
);
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2606
2881
|
function createMySqlDatabase(options) {
|
|
2607
|
-
const {
|
|
2608
|
-
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath3(migrationsFolder) :
|
|
2609
|
-
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) :
|
|
2882
|
+
const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
|
|
2883
|
+
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath3(migrationsFolder) : resolve4(String(migrationsFolder));
|
|
2884
|
+
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
|
|
2610
2885
|
let migrationsPromise;
|
|
2611
2886
|
let databasePromise;
|
|
2612
2887
|
let database2;
|
|
@@ -2623,20 +2898,22 @@ function createMySqlDatabase(options) {
|
|
|
2623
2898
|
return migrationsPromise;
|
|
2624
2899
|
}
|
|
2625
2900
|
const promise = (async () => {
|
|
2626
|
-
if (!
|
|
2901
|
+
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
2902
|
+
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
2627
2903
|
return;
|
|
2628
2904
|
}
|
|
2905
|
+
const { drizzle, migrate } = await loadMySqlModules();
|
|
2629
2906
|
const url = resolveConnectionString();
|
|
2630
|
-
const migrationDb =
|
|
2907
|
+
const migrationDb = drizzle({
|
|
2631
2908
|
connection: {
|
|
2632
2909
|
uri: url,
|
|
2633
2910
|
...clientOptions
|
|
2634
2911
|
},
|
|
2635
|
-
|
|
2636
|
-
|
|
2912
|
+
mode: "default",
|
|
2913
|
+
...relations ? { relations } : {}
|
|
2637
2914
|
});
|
|
2638
2915
|
try {
|
|
2639
|
-
await
|
|
2916
|
+
await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
|
|
2640
2917
|
} finally {
|
|
2641
2918
|
await closeClient(migrationDb);
|
|
2642
2919
|
}
|
|
@@ -2654,14 +2931,15 @@ function createMySqlDatabase(options) {
|
|
|
2654
2931
|
}
|
|
2655
2932
|
const promise = (async () => {
|
|
2656
2933
|
await migrateOnce();
|
|
2934
|
+
const { drizzle } = await loadMySqlModules();
|
|
2657
2935
|
const url = resolveConnectionString();
|
|
2658
|
-
const db =
|
|
2936
|
+
const db = drizzle({
|
|
2659
2937
|
connection: {
|
|
2660
2938
|
uri: url,
|
|
2661
2939
|
...clientOptions
|
|
2662
2940
|
},
|
|
2663
|
-
|
|
2664
|
-
|
|
2941
|
+
mode: "default",
|
|
2942
|
+
...relations ? { relations } : {}
|
|
2665
2943
|
});
|
|
2666
2944
|
database2 = db;
|
|
2667
2945
|
return db;
|
|
@@ -2691,12 +2969,62 @@ function createMySqlDatabase(options) {
|
|
|
2691
2969
|
const db = await getDatabase();
|
|
2692
2970
|
await runSeeders(db, resolvedSeedersFolder);
|
|
2693
2971
|
}
|
|
2972
|
+
async function withAdminDb(callback) {
|
|
2973
|
+
const { drizzle } = await loadMySqlModules();
|
|
2974
|
+
const adminDb = drizzle({
|
|
2975
|
+
connection: {
|
|
2976
|
+
uri: resolveConnectionString(),
|
|
2977
|
+
...clientOptions
|
|
2978
|
+
},
|
|
2979
|
+
mode: "default"
|
|
2980
|
+
});
|
|
2981
|
+
try {
|
|
2982
|
+
return await callback(adminDb);
|
|
2983
|
+
} finally {
|
|
2984
|
+
await closeClient(adminDb);
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
async function resetDatabase() {
|
|
2988
|
+
const { sql } = await import("drizzle-orm");
|
|
2989
|
+
await withAdminDb(async (adminDb) => {
|
|
2990
|
+
const [rows] = await adminDb.execute(
|
|
2991
|
+
sql.raw("SELECT table_name AS name FROM information_schema.tables WHERE table_schema = DATABASE()")
|
|
2992
|
+
);
|
|
2993
|
+
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 0"));
|
|
2994
|
+
try {
|
|
2995
|
+
for (const { name } of rows) {
|
|
2996
|
+
await adminDb.execute(sql.raw(`DROP TABLE IF EXISTS \`${name.replaceAll("`", "``")}\``));
|
|
2997
|
+
}
|
|
2998
|
+
} finally {
|
|
2999
|
+
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 1"));
|
|
3000
|
+
}
|
|
3001
|
+
});
|
|
3002
|
+
migrationsPromise = void 0;
|
|
3003
|
+
}
|
|
3004
|
+
async function migrationStatus() {
|
|
3005
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3006
|
+
if (localMigrations.length === 0) return [];
|
|
3007
|
+
const { sql } = await import("drizzle-orm");
|
|
3008
|
+
const appliedRows = await withAdminDb(async (adminDb) => {
|
|
3009
|
+
try {
|
|
3010
|
+
const [rows] = await adminDb.execute(
|
|
3011
|
+
sql.raw("SELECT name, applied_at FROM __drizzle_migrations")
|
|
3012
|
+
);
|
|
3013
|
+
return rows.map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
3014
|
+
} catch {
|
|
3015
|
+
return [];
|
|
3016
|
+
}
|
|
3017
|
+
});
|
|
3018
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
3019
|
+
}
|
|
2694
3020
|
return {
|
|
2695
3021
|
getDatabase,
|
|
2696
3022
|
migrateDatabase: migrateOnce,
|
|
2697
3023
|
closeDatabase,
|
|
2698
3024
|
configureOrm,
|
|
2699
|
-
seedDatabase
|
|
3025
|
+
seedDatabase,
|
|
3026
|
+
resetDatabase,
|
|
3027
|
+
migrationStatus
|
|
2700
3028
|
};
|
|
2701
3029
|
}
|
|
2702
3030
|
async function closeClient(db) {
|
|
@@ -2727,25 +3055,16 @@ async function closeClient(db) {
|
|
|
2727
3055
|
function isPromiseLike2(value) {
|
|
2728
3056
|
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
2729
3057
|
}
|
|
2730
|
-
function hasDrizzleMigrations2(migrationsFolder) {
|
|
2731
|
-
if (!existsSync2(migrationsFolder)) {
|
|
2732
|
-
return false;
|
|
2733
|
-
}
|
|
2734
|
-
const entries = readdirSync2(migrationsFolder, { withFileTypes: true });
|
|
2735
|
-
return entries.some(
|
|
2736
|
-
(entry) => entry.isDirectory() && existsSync2(resolve3(migrationsFolder, entry.name, "migration.sql"))
|
|
2737
|
-
);
|
|
2738
|
-
}
|
|
2739
3058
|
|
|
2740
3059
|
// src/sqlite.ts
|
|
2741
|
-
import {
|
|
2742
|
-
import { resolve as resolve4 } from "path";
|
|
3060
|
+
import { resolve as resolve5 } from "path";
|
|
2743
3061
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2744
3062
|
function createSqliteDatabase(options) {
|
|
2745
|
-
const {
|
|
2746
|
-
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) :
|
|
2747
|
-
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) :
|
|
3063
|
+
const { migrationsFolder, filename, seedersFolder, relations } = options;
|
|
3064
|
+
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
|
|
3065
|
+
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) : resolve5(String(seedersFolder));
|
|
2748
3066
|
let db;
|
|
3067
|
+
let sqliteClient;
|
|
2749
3068
|
let migrationsPromise;
|
|
2750
3069
|
function resolveFilename() {
|
|
2751
3070
|
const value = typeof filename === "function" ? filename() : filename;
|
|
@@ -2757,25 +3076,27 @@ function createSqliteDatabase(options) {
|
|
|
2757
3076
|
const { mkdirSync } = await import("fs");
|
|
2758
3077
|
const { dirname } = await import("path");
|
|
2759
3078
|
try {
|
|
2760
|
-
mkdirSync(dirname(
|
|
3079
|
+
mkdirSync(dirname(resolve5(dbPath)), { recursive: true });
|
|
2761
3080
|
} catch {
|
|
2762
3081
|
}
|
|
2763
3082
|
const { Database } = await import("bun:sqlite");
|
|
2764
3083
|
const sqlite = new Database(dbPath);
|
|
2765
3084
|
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
2766
|
-
|
|
2767
|
-
|
|
3085
|
+
sqliteClient = sqlite;
|
|
3086
|
+
const { drizzle } = await import("drizzle-orm/bun-sqlite");
|
|
3087
|
+
db = drizzle({ client: sqlite, ...relations ? { relations } : {} });
|
|
2768
3088
|
return db;
|
|
2769
3089
|
}
|
|
2770
3090
|
async function migrateOnce() {
|
|
2771
3091
|
if (migrationsPromise) return migrationsPromise;
|
|
2772
3092
|
migrationsPromise = (async () => {
|
|
2773
|
-
if (!
|
|
3093
|
+
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
3094
|
+
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
2774
3095
|
return;
|
|
2775
3096
|
}
|
|
2776
3097
|
const database2 = await ensureDatabase2();
|
|
2777
|
-
const { migrate
|
|
2778
|
-
await
|
|
3098
|
+
const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
|
|
3099
|
+
await migrate(database2, { migrationsFolder: resolvedMigrationsFolder });
|
|
2779
3100
|
})();
|
|
2780
3101
|
migrationsPromise = migrationsPromise.catch((error) => {
|
|
2781
3102
|
migrationsPromise = void 0;
|
|
@@ -2793,6 +3114,33 @@ function createSqliteDatabase(options) {
|
|
|
2793
3114
|
async closeDatabase() {
|
|
2794
3115
|
if (!db) return;
|
|
2795
3116
|
db = void 0;
|
|
3117
|
+
sqliteClient = void 0;
|
|
3118
|
+
},
|
|
3119
|
+
async resetDatabase() {
|
|
3120
|
+
await ensureDatabase2();
|
|
3121
|
+
if (!sqliteClient) return;
|
|
3122
|
+
const tables = sqliteClient.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
|
|
3123
|
+
sqliteClient.exec("PRAGMA foreign_keys = OFF;");
|
|
3124
|
+
try {
|
|
3125
|
+
for (const { name } of tables) {
|
|
3126
|
+
sqliteClient.exec(`DROP TABLE IF EXISTS "${name.replaceAll('"', '""')}"`);
|
|
3127
|
+
}
|
|
3128
|
+
} finally {
|
|
3129
|
+
sqliteClient.exec("PRAGMA foreign_keys = ON;");
|
|
3130
|
+
}
|
|
3131
|
+
migrationsPromise = void 0;
|
|
3132
|
+
},
|
|
3133
|
+
async migrationStatus() {
|
|
3134
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3135
|
+
if (localMigrations.length === 0) return [];
|
|
3136
|
+
await ensureDatabase2();
|
|
3137
|
+
let appliedRows = [];
|
|
3138
|
+
try {
|
|
3139
|
+
const rows = sqliteClient?.query("SELECT name, applied_at FROM __drizzle_migrations").all();
|
|
3140
|
+
appliedRows = (rows ?? []).map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
3141
|
+
} catch {
|
|
3142
|
+
}
|
|
3143
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
2796
3144
|
},
|
|
2797
3145
|
async configureOrm() {
|
|
2798
3146
|
const database2 = await ensureDatabase2();
|
|
@@ -2811,18 +3159,10 @@ function createSqliteDatabase(options) {
|
|
|
2811
3159
|
}
|
|
2812
3160
|
};
|
|
2813
3161
|
}
|
|
2814
|
-
function hasDrizzleMigrations3(migrationsFolder) {
|
|
2815
|
-
if (!existsSync3(migrationsFolder)) {
|
|
2816
|
-
return false;
|
|
2817
|
-
}
|
|
2818
|
-
const entries = readdirSync3(migrationsFolder, { withFileTypes: true });
|
|
2819
|
-
return entries.some(
|
|
2820
|
-
(entry) => entry.isDirectory() && existsSync3(resolve4(migrationsFolder, entry.name, "migration.sql"))
|
|
2821
|
-
);
|
|
2822
|
-
}
|
|
2823
3162
|
export {
|
|
2824
3163
|
DrizzleAdapter,
|
|
2825
3164
|
GlobalScopeRegistry,
|
|
3165
|
+
MassAssignmentException,
|
|
2826
3166
|
Model,
|
|
2827
3167
|
ModelNotFoundException,
|
|
2828
3168
|
QueryBuilder,
|