@guren/orm 2.2.0 → 2.2.2

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 CHANGED
@@ -21,6 +21,13 @@ declare function applyAccessors<T extends PlainObject>(record: T, accessors?: Ac
21
21
  declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions): PlainObject;
22
22
 
23
23
  type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
24
+ /**
25
+ * Key for the prepared-payload update terminal.
26
+ *
27
+ * Exported for `Model` to call across the module boundary, but deliberately
28
+ * absent from the package entry point, so it is not part of the public API.
29
+ */
30
+ declare const PREPARED_UPDATE: unique symbol;
24
31
  /** Comparison operators supported by the QueryBuilder. */
25
32
  type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
26
33
  /** A single field-level condition. */
@@ -233,6 +240,20 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
233
240
  */
234
241
  forceUpdate(data: PlainObject): Promise<TRecord>;
235
242
  private runBulkUpdate;
243
+ /**
244
+ * Bulk update using a payload the caller has already run through
245
+ * mass-assignment filtering and persistence preparation. This exists so the
246
+ * static `Model.update()` write path can borrow the builder's
247
+ * global-scope-carrying `conditions` without re-preparing the payload —
248
+ * running mutators twice would, for example, double-hash a hashed column.
249
+ *
250
+ * Keyed by a symbol that this package never re-exports, because a named
251
+ * public method here would be a supported way to write arbitrary columns:
252
+ * it skips both `filterFillable` and `prepareBulkPersistencePayload`, so
253
+ * `User.where(…)[name](requestBody)` would bypass mass-assignment protection
254
+ * entirely. `@internal` is only a doc tag — declarations still emit it.
255
+ */
256
+ [PREPARED_UPDATE](payload: PlainObject): Promise<TRecord>;
236
257
  /**
237
258
  * Bulk delete records matching the current conditions.
238
259
  * @returns Number of deleted records (adapter-dependent)
@@ -300,6 +321,15 @@ declare class GlobalScopeRegistry {
300
321
  /** Apply all scopes (or all except excluded) to a query builder. */
301
322
  apply<T extends PlainObject>(builder: QueryBuilder<T>, except?: string[]): QueryBuilder<T>;
302
323
  clear(): void;
324
+ /**
325
+ * Copy this registry's entries into a new one.
326
+ *
327
+ * A subclass that registers its own scope needs a registry of its own, but it
328
+ * must keep the ones it inherited: starting from empty is how a model that
329
+ * mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
330
+ * `softDelete` filter.
331
+ */
332
+ clone(): GlobalScopeRegistry;
303
333
  get size(): number;
304
334
  }
305
335
 
@@ -718,6 +748,22 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
718
748
  static observe(ObserverClass: ModelObserverConstructor): void;
719
749
  /** Clear all registered observers. */
720
750
  static clearObservers(): void;
751
+ /**
752
+ * The registry this class may mutate, creating it on first write.
753
+ *
754
+ * The new registry is seeded from the inherited one: the read paths
755
+ * (`newQuery()`, `hasScopes()`) resolve `globalScopeRegistry` through the
756
+ * prototype chain, so a subclass that started from an empty registry would
757
+ * shadow — and silently drop — every scope it inherited. That is exactly the
758
+ * `class Post extends SoftDeletes(Base)` then `Post.addGlobalScope('tenant')`
759
+ * case, which would otherwise lose the `softDelete` filter.
760
+ *
761
+ * The copy is a snapshot: scopes added to the parent *after* a subclass first
762
+ * registers or removes one do not reach that subclass. Nothing in the
763
+ * framework relies on later propagation — the `SoftDeletes` mixin registers
764
+ * `softDelete` synchronously while building the class, before any user code
765
+ * can touch it.
766
+ */
721
767
  protected static getGlobalScopes(): GlobalScopeRegistry;
722
768
  /**
723
769
  * Register a named global scope.
@@ -731,6 +777,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
731
777
  /**
732
778
  * Start a query excluding specific global scope(s).
733
779
  *
780
+ * Only *named* scopes can be excluded: `defaultScope` is re-applied here
781
+ * whatever this is asked to drop. A mixin whose filter users must be able to
782
+ * opt out of therefore has to register a named scope and nothing else —
783
+ * registering as both makes the filter unremovable, which is how `SoftDeletes`
784
+ * once made `withoutGlobalScope('softDelete')` a no-op.
785
+ *
734
786
  * @example
735
787
  * const all = await User.withoutGlobalScope('active').get()
736
788
  */
@@ -1518,8 +1570,6 @@ declare class MassAssignmentException extends Error {
1518
1570
  interface SoftDeletesStatic {
1519
1571
  /** Column name used for tracking soft deletion timestamp. */
1520
1572
  deletedAtColumn: string;
1521
- /** Default scope that excludes soft-deleted records. */
1522
- defaultScope: (q: QueryBuilder<any>) => QueryBuilder<any>;
1523
1573
  /** Start a query that includes soft-deleted records. */
1524
1574
  withTrashed(): QueryBuilder<PlainObject>;
1525
1575
  /** Start a query that returns only soft-deleted records. */
package/dist/index.js CHANGED
@@ -437,7 +437,7 @@ function applyMutators(data, mutators) {
437
437
  }
438
438
 
439
439
  // src/GlobalScopeRegistry.ts
440
- var GlobalScopeRegistry = class {
440
+ var GlobalScopeRegistry = class _GlobalScopeRegistry {
441
441
  scopes = /* @__PURE__ */ new Map();
442
442
  add(name, fn) {
443
443
  this.scopes.set(name, fn);
@@ -462,6 +462,21 @@ var GlobalScopeRegistry = class {
462
462
  clear() {
463
463
  this.scopes.clear();
464
464
  }
465
+ /**
466
+ * Copy this registry's entries into a new one.
467
+ *
468
+ * A subclass that registers its own scope needs a registry of its own, but it
469
+ * must keep the ones it inherited: starting from empty is how a model that
470
+ * mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
471
+ * `softDelete` filter.
472
+ */
473
+ clone() {
474
+ const copy = new _GlobalScopeRegistry();
475
+ for (const [name, fn] of this.scopes) {
476
+ copy.add(name, fn);
477
+ }
478
+ return copy;
479
+ }
465
480
  get size() {
466
481
  return this.scopes.size;
467
482
  }
@@ -503,6 +518,7 @@ var ModelNotFoundException = class extends Error {
503
518
  };
504
519
 
505
520
  // src/QueryBuilder.ts
521
+ var PREPARED_UPDATE = /* @__PURE__ */ Symbol("guren.orm.preparedUpdate");
506
522
  var QueryBuilder = class {
507
523
  conditions = [];
508
524
  options = { orderBy: [] };
@@ -786,12 +802,28 @@ var QueryBuilder = class {
786
802
  return this.runBulkUpdate(data, false);
787
803
  }
788
804
  async runBulkUpdate(data, applyFillable) {
789
- if (!this.adapter.update) {
790
- throw new Error("Configured adapter does not support update operations.");
791
- }
792
805
  const model = this.modelClass;
793
806
  const filtered = applyFillable ? model.filterFillable(data) : { ...data };
794
807
  const payload = await model.prepareBulkPersistencePayload(filtered);
808
+ return this[PREPARED_UPDATE](payload);
809
+ }
810
+ /**
811
+ * Bulk update using a payload the caller has already run through
812
+ * mass-assignment filtering and persistence preparation. This exists so the
813
+ * static `Model.update()` write path can borrow the builder's
814
+ * global-scope-carrying `conditions` without re-preparing the payload —
815
+ * running mutators twice would, for example, double-hash a hashed column.
816
+ *
817
+ * Keyed by a symbol that this package never re-exports, because a named
818
+ * public method here would be a supported way to write arbitrary columns:
819
+ * it skips both `filterFillable` and `prepareBulkPersistencePayload`, so
820
+ * `User.where(…)[name](requestBody)` would bypass mass-assignment protection
821
+ * entirely. `@internal` is only a doc tag — declarations still emit it.
822
+ */
823
+ async [PREPARED_UPDATE](payload) {
824
+ if (!this.adapter.update) {
825
+ throw new Error("Configured adapter does not support update operations.");
826
+ }
795
827
  const advancedAdapter = this.adapter;
796
828
  if (typeof advancedAdapter.updateAdvanced === "function") {
797
829
  return advancedAdapter.updateAdvanced(this.table, this.conditions, payload, { trx: this.options.trx });
@@ -1209,9 +1241,26 @@ var Model = class _Model {
1209
1241
  // Global Scopes
1210
1242
  // ---------------------------------------------------------------------------
1211
1243
  // ---------------------------------------------------------------------------
1244
+ /**
1245
+ * The registry this class may mutate, creating it on first write.
1246
+ *
1247
+ * The new registry is seeded from the inherited one: the read paths
1248
+ * (`newQuery()`, `hasScopes()`) resolve `globalScopeRegistry` through the
1249
+ * prototype chain, so a subclass that started from an empty registry would
1250
+ * shadow — and silently drop — every scope it inherited. That is exactly the
1251
+ * `class Post extends SoftDeletes(Base)` then `Post.addGlobalScope('tenant')`
1252
+ * case, which would otherwise lose the `softDelete` filter.
1253
+ *
1254
+ * The copy is a snapshot: scopes added to the parent *after* a subclass first
1255
+ * registers or removes one do not reach that subclass. Nothing in the
1256
+ * framework relies on later propagation — the `SoftDeletes` mixin registers
1257
+ * `softDelete` synchronously while building the class, before any user code
1258
+ * can touch it.
1259
+ */
1212
1260
  static getGlobalScopes() {
1213
1261
  if (!Object.prototype.hasOwnProperty.call(this, "globalScopeRegistry") || !this.globalScopeRegistry) {
1214
- this.globalScopeRegistry = new GlobalScopeRegistry();
1262
+ const inherited = this.globalScopeRegistry;
1263
+ this.globalScopeRegistry = inherited ? inherited.clone() : new GlobalScopeRegistry();
1215
1264
  }
1216
1265
  return this.globalScopeRegistry;
1217
1266
  }
@@ -1231,6 +1280,12 @@ var Model = class _Model {
1231
1280
  /**
1232
1281
  * Start a query excluding specific global scope(s).
1233
1282
  *
1283
+ * Only *named* scopes can be excluded: `defaultScope` is re-applied here
1284
+ * whatever this is asked to drop. A mixin whose filter users must be able to
1285
+ * opt out of therefore has to register a named scope and nothing else —
1286
+ * registering as both makes the filter unremovable, which is how `SoftDeletes`
1287
+ * once made `withoutGlobalScope('softDelete')` a no-op.
1288
+ *
1234
1289
  * @example
1235
1290
  * const all = await User.withoutGlobalScope('active').get()
1236
1291
  */
@@ -2092,7 +2147,7 @@ var Model = class _Model {
2092
2147
  throw new Error(`${this.name}.update() aborted by observer 'saving'.`);
2093
2148
  }
2094
2149
  }
2095
- const result = await adapter.update(table, where, payload, writeOptions);
2150
+ const result = this.hasScopes() ? await this.newQuery(writeOptions).where(where)[PREPARED_UPDATE](payload) : await adapter.update(table, where, payload, writeOptions);
2096
2151
  if (hooks) {
2097
2152
  const resultData = result;
2098
2153
  await executeHook(hooks, "updated", resultData);
@@ -2137,7 +2192,7 @@ var Model = class _Model {
2137
2192
  throw new Error(`${this.name}.delete() aborted by observer 'deleting'.`);
2138
2193
  }
2139
2194
  }
2140
- const result = await adapter.delete(table, where, writeOptions);
2195
+ const result = this.hasScopes() ? await this.newQuery(writeOptions).where(where).delete() : await adapter.delete(table, where, writeOptions);
2141
2196
  if (hooks) {
2142
2197
  await executeHook(hooks, "deleted", whereData);
2143
2198
  }
@@ -2602,45 +2657,50 @@ function resolveQueryableDatabase(adapter) {
2602
2657
  }
2603
2658
 
2604
2659
  // src/SoftDeletes.ts
2660
+ function scopedQuery(model, where) {
2661
+ return model.newQuery().where(where);
2662
+ }
2663
+ function withoutSoftDeleteScope(model) {
2664
+ return model.withoutGlobalScope("softDelete");
2665
+ }
2666
+ function trashedScopedQuery(model, where) {
2667
+ return withoutSoftDeleteScope(model).where(where);
2668
+ }
2605
2669
  function SoftDeletes(Base) {
2606
2670
  const SoftDeleteModel = class extends Base {
2607
2671
  };
2608
2672
  SoftDeleteModel.deletedAtColumn = "deletedAt";
2609
2673
  const scopeFn = (q) => q.whereNull("deletedAt");
2610
- SoftDeleteModel.defaultScope = scopeFn;
2611
2674
  SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
2612
2675
  SoftDeleteModel.delete = async function(where) {
2613
2676
  const adapter = this.getAdapter();
2614
2677
  if (!adapter.update) {
2615
2678
  throw new Error("Configured adapter does not support update operations (needed for soft delete).");
2616
2679
  }
2617
- const table = this.resolveTable();
2618
2680
  const column = this.deletedAtColumn;
2619
- return adapter.update(table, where, { [column]: /* @__PURE__ */ new Date() });
2681
+ return scopedQuery(this, where)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
2620
2682
  };
2621
2683
  SoftDeleteModel.withTrashed = function() {
2622
- return this.withoutGlobalScopes();
2684
+ return withoutSoftDeleteScope(this);
2623
2685
  };
2624
2686
  SoftDeleteModel.onlyTrashed = function() {
2625
2687
  const column = this.deletedAtColumn;
2626
- return this.withoutGlobalScopes().whereNotNull(column);
2688
+ return withoutSoftDeleteScope(this).whereNotNull(column);
2627
2689
  };
2628
2690
  SoftDeleteModel.restore = async function(where) {
2629
2691
  const adapter = this.getAdapter();
2630
2692
  if (!adapter.update) {
2631
2693
  throw new Error("Configured adapter does not support update operations (needed for restore).");
2632
2694
  }
2633
- const table = this.resolveTable();
2634
2695
  const column = this.deletedAtColumn;
2635
- return adapter.update(table, where, { [column]: null });
2696
+ return trashedScopedQuery(this, where)[PREPARED_UPDATE]({ [column]: null });
2636
2697
  };
2637
2698
  SoftDeleteModel.forceDelete = async function(where) {
2638
2699
  const adapter = this.getAdapter();
2639
2700
  if (!adapter.delete) {
2640
2701
  throw new Error("Configured adapter does not support delete operations.");
2641
2702
  }
2642
- const table = this.resolveTable();
2643
- return adapter.delete(table, where);
2703
+ return trashedScopedQuery(this, where).delete();
2644
2704
  };
2645
2705
  return SoftDeleteModel;
2646
2706
  }
@@ -2992,6 +3052,28 @@ function defineSeeder(handler) {
2992
3052
  return handler;
2993
3053
  }
2994
3054
 
3055
+ // src/single-flight.ts
3056
+ function singleFlight(factory) {
3057
+ let inFlight;
3058
+ function get() {
3059
+ if (inFlight) {
3060
+ return inFlight;
3061
+ }
3062
+ const attempt = factory().catch((error) => {
3063
+ if (inFlight === attempt) {
3064
+ inFlight = void 0;
3065
+ }
3066
+ throw error;
3067
+ });
3068
+ inFlight = attempt;
3069
+ return attempt;
3070
+ }
3071
+ function reset() {
3072
+ inFlight = void 0;
3073
+ }
3074
+ return { get, reset };
3075
+ }
3076
+
2995
3077
  // src/postgres.ts
2996
3078
  async function loadPostgresModules() {
2997
3079
  try {
@@ -3012,8 +3094,6 @@ function createPostgresDatabase(options) {
3012
3094
  const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3013
3095
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath2(migrationsFolder) : resolve3(String(migrationsFolder));
3014
3096
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath2(seedersFolder) : resolve3(String(seedersFolder));
3015
- let migrationsPromise;
3016
- let databasePromise;
3017
3097
  let client;
3018
3098
  let activeKey;
3019
3099
  const callSite = new Error().stack;
@@ -3025,12 +3105,9 @@ function createPostgresDatabase(options) {
3025
3105
  }
3026
3106
  return resolved;
3027
3107
  }
3028
- async function migrateOnce() {
3029
- if (migrationsPromise) {
3030
- return migrationsPromise;
3031
- }
3108
+ const migrations = singleFlight(async () => {
3032
3109
  let endpoint;
3033
- const promise = (async () => {
3110
+ try {
3034
3111
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3035
3112
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3036
3113
  return;
@@ -3048,41 +3125,28 @@ function createPostgresDatabase(options) {
3048
3125
  } finally {
3049
3126
  await migrationClient.end({ timeout: 0 });
3050
3127
  }
3051
- })();
3052
- migrationsPromise = promise.catch((error) => {
3053
- migrationsPromise = void 0;
3128
+ } catch (error) {
3054
3129
  throw migrationFailure(error, endpoint);
3130
+ }
3131
+ });
3132
+ const database2 = singleFlight(async () => {
3133
+ await migrations.get();
3134
+ const { drizzle, postgres: postgresFactory } = await loadPostgresModules();
3135
+ const url = resolveConnectionString();
3136
+ const activeClient = postgresFactory(url, {
3137
+ max: 1,
3138
+ ...clientOptions
3055
3139
  });
3056
- await migrationsPromise;
3057
- }
3058
- async function getDatabase() {
3059
- if (databasePromise) {
3060
- return databasePromise;
3140
+ client = activeClient;
3141
+ activeKey = hotReloadKey("postgres", callSite, url);
3142
+ if (activeKey) {
3143
+ await replaceActiveConnection(activeKey, closeDatabase);
3061
3144
  }
3062
- const promise = (async () => {
3063
- await migrateOnce();
3064
- const { drizzle, postgres: postgresFactory } = await loadPostgresModules();
3065
- const url = resolveConnectionString();
3066
- const activeClient = postgresFactory(url, {
3067
- max: 1,
3068
- ...clientOptions
3069
- });
3070
- client = activeClient;
3071
- activeKey = hotReloadKey("postgres", callSite, url);
3072
- if (activeKey) {
3073
- await replaceActiveConnection(activeKey, closeDatabase);
3074
- }
3075
- return drizzle({
3076
- client: activeClient,
3077
- ...relations ? { relations } : {}
3078
- });
3079
- })();
3080
- databasePromise = promise.catch((error) => {
3081
- databasePromise = void 0;
3082
- throw error;
3145
+ return drizzle({
3146
+ client: activeClient,
3147
+ ...relations ? { relations } : {}
3083
3148
  });
3084
- return databasePromise;
3085
- }
3149
+ });
3086
3150
  async function closeDatabase() {
3087
3151
  if (!client) {
3088
3152
  return;
@@ -3093,21 +3157,21 @@ function createPostgresDatabase(options) {
3093
3157
  await client.end({ timeout: 0 });
3094
3158
  } finally {
3095
3159
  client = void 0;
3096
- databasePromise = void 0;
3160
+ database2.reset();
3097
3161
  if (key) {
3098
3162
  releaseActiveConnection(key, closeDatabase);
3099
3163
  }
3100
3164
  }
3101
3165
  }
3102
3166
  async function configureOrm() {
3103
- const db = await getDatabase();
3167
+ const db = await database2.get();
3104
3168
  DrizzleAdapter.configure(db);
3105
3169
  }
3106
3170
  async function seedDatabase() {
3107
3171
  if (!resolvedSeedersFolder) {
3108
3172
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createPostgresDatabase().');
3109
3173
  }
3110
- const db = await getDatabase();
3174
+ const db = await database2.get();
3111
3175
  try {
3112
3176
  await runSeeders(db, resolvedSeedersFolder);
3113
3177
  } catch (error) {
@@ -3135,7 +3199,7 @@ function createPostgresDatabase(options) {
3135
3199
  await adminClient.unsafe("CREATE SCHEMA public");
3136
3200
  await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
3137
3201
  });
3138
- migrationsPromise = void 0;
3202
+ migrations.reset();
3139
3203
  }
3140
3204
  async function migrationStatus() {
3141
3205
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3155,8 +3219,8 @@ function createPostgresDatabase(options) {
3155
3219
  return buildMigrationStatus(localMigrations, appliedRows);
3156
3220
  }
3157
3221
  return {
3158
- getDatabase,
3159
- migrateDatabase: migrateOnce,
3222
+ getDatabase: database2.get,
3223
+ migrateDatabase: migrations.get,
3160
3224
  closeDatabase,
3161
3225
  configureOrm,
3162
3226
  seedDatabase,
@@ -3187,8 +3251,6 @@ function createMySqlDatabase(options) {
3187
3251
  const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3188
3252
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath3(migrationsFolder) : resolve4(String(migrationsFolder));
3189
3253
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
3190
- let migrationsPromise;
3191
- let databasePromise;
3192
3254
  let client;
3193
3255
  let activeKey;
3194
3256
  const callSite = new Error().stack;
@@ -3200,12 +3262,9 @@ function createMySqlDatabase(options) {
3200
3262
  }
3201
3263
  return resolved;
3202
3264
  }
3203
- async function migrateOnce() {
3204
- if (migrationsPromise) {
3205
- return migrationsPromise;
3206
- }
3265
+ const migrations = singleFlight(async () => {
3207
3266
  let endpoint;
3208
- const promise = (async () => {
3267
+ try {
3209
3268
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3210
3269
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3211
3270
  return;
@@ -3223,38 +3282,25 @@ function createMySqlDatabase(options) {
3223
3282
  } finally {
3224
3283
  await closePool(migrationClient);
3225
3284
  }
3226
- })();
3227
- migrationsPromise = promise.catch((error) => {
3228
- migrationsPromise = void 0;
3285
+ } catch (error) {
3229
3286
  throw migrationFailure(error, endpoint);
3230
- });
3231
- await migrationsPromise;
3232
- }
3233
- async function getDatabase() {
3234
- if (databasePromise) {
3235
- return databasePromise;
3236
3287
  }
3237
- const promise = (async () => {
3238
- await migrateOnce();
3239
- const { drizzle, createPool } = await loadMySqlModules();
3240
- const url = resolveConnectionString();
3241
- const activeClient = createPool({ uri: url, ...clientOptions });
3242
- client = activeClient;
3243
- activeKey = hotReloadKey("mysql", callSite, url);
3244
- if (activeKey) {
3245
- await replaceActiveConnection(activeKey, closeDatabase);
3246
- }
3247
- return drizzle({
3248
- client: activeClient,
3249
- ...relations ? { relations } : {}
3250
- });
3251
- })();
3252
- databasePromise = promise.catch((error) => {
3253
- databasePromise = void 0;
3254
- throw error;
3288
+ });
3289
+ const database2 = singleFlight(async () => {
3290
+ await migrations.get();
3291
+ const { drizzle, createPool } = await loadMySqlModules();
3292
+ const url = resolveConnectionString();
3293
+ const activeClient = createPool({ uri: url, ...clientOptions });
3294
+ client = activeClient;
3295
+ activeKey = hotReloadKey("mysql", callSite, url);
3296
+ if (activeKey) {
3297
+ await replaceActiveConnection(activeKey, closeDatabase);
3298
+ }
3299
+ return drizzle({
3300
+ client: activeClient,
3301
+ ...relations ? { relations } : {}
3255
3302
  });
3256
- return databasePromise;
3257
- }
3303
+ });
3258
3304
  async function closeDatabase() {
3259
3305
  if (!client) {
3260
3306
  return;
@@ -3265,21 +3311,21 @@ function createMySqlDatabase(options) {
3265
3311
  await closePool(client);
3266
3312
  } finally {
3267
3313
  client = void 0;
3268
- databasePromise = void 0;
3314
+ database2.reset();
3269
3315
  if (key) {
3270
3316
  releaseActiveConnection(key, closeDatabase);
3271
3317
  }
3272
3318
  }
3273
3319
  }
3274
3320
  async function configureOrm() {
3275
- const db = await getDatabase();
3321
+ const db = await database2.get();
3276
3322
  DrizzleAdapter.configure(db);
3277
3323
  }
3278
3324
  async function seedDatabase() {
3279
3325
  if (!resolvedSeedersFolder) {
3280
3326
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createMySqlDatabase().');
3281
3327
  }
3282
- const db = await getDatabase();
3328
+ const db = await database2.get();
3283
3329
  try {
3284
3330
  await runSeeders(db, resolvedSeedersFolder);
3285
3331
  } catch (error) {
@@ -3319,7 +3365,7 @@ function createMySqlDatabase(options) {
3319
3365
  await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 1"));
3320
3366
  }
3321
3367
  });
3322
- migrationsPromise = void 0;
3368
+ migrations.reset();
3323
3369
  }
3324
3370
  async function migrationStatus() {
3325
3371
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3339,8 +3385,8 @@ function createMySqlDatabase(options) {
3339
3385
  return buildMigrationStatus(localMigrations, appliedRows);
3340
3386
  }
3341
3387
  return {
3342
- getDatabase,
3343
- migrateDatabase: migrateOnce,
3388
+ getDatabase: database2.get,
3389
+ migrateDatabase: migrations.get,
3344
3390
  closeDatabase,
3345
3391
  configureOrm,
3346
3392
  seedDatabase,
@@ -3364,17 +3410,14 @@ function createSqliteDatabase(options) {
3364
3410
  const { migrationsFolder, filename, seedersFolder, relations } = options;
3365
3411
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
3366
3412
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) : resolve5(String(seedersFolder));
3367
- let db;
3368
3413
  let sqliteClient;
3369
- let migrationsPromise;
3370
3414
  let activeKey;
3371
3415
  const callSite = new Error().stack;
3372
3416
  function resolveFilename() {
3373
3417
  const value = typeof filename === "function" ? filename() : filename;
3374
3418
  return value ?? process.env.DATABASE_URL ?? "./data/guren.db";
3375
3419
  }
3376
- async function ensureDatabase2() {
3377
- if (db) return db;
3420
+ const database2 = singleFlight(async () => {
3378
3421
  const dbPath = resolveFilename();
3379
3422
  const { mkdirSync } = await import("fs");
3380
3423
  const { dirname } = await import("path");
@@ -3383,58 +3426,53 @@ function createSqliteDatabase(options) {
3383
3426
  } catch {
3384
3427
  }
3385
3428
  const { Database } = await import("bun:sqlite");
3429
+ const { drizzle } = await import("drizzle-orm/bun-sqlite");
3386
3430
  const sqlite = new Database(dbPath);
3387
3431
  sqlite.exec("PRAGMA journal_mode = WAL;");
3388
3432
  sqliteClient = sqlite;
3389
- const { drizzle } = await import("drizzle-orm/bun-sqlite");
3390
- const database2 = drizzle({ client: sqlite, ...relations ? { relations } : {} });
3391
- db = database2;
3433
+ const handle = drizzle({ client: sqlite, ...relations ? { relations } : {} });
3392
3434
  activeKey = isInMemory(dbPath) ? void 0 : hotReloadKey("sqlite", callSite, resolve5(dbPath));
3393
3435
  if (activeKey) {
3394
3436
  await replaceActiveConnection(activeKey, closeDatabase);
3395
3437
  }
3396
- return database2;
3397
- }
3438
+ return handle;
3439
+ });
3398
3440
  async function closeDatabase() {
3399
- if (!db) return;
3441
+ if (!sqliteClient) return;
3400
3442
  const key = activeKey;
3401
3443
  activeKey = void 0;
3402
3444
  try {
3403
- sqliteClient?.close();
3445
+ sqliteClient.close();
3404
3446
  } finally {
3405
- db = void 0;
3406
3447
  sqliteClient = void 0;
3448
+ database2.reset();
3407
3449
  if (key) {
3408
3450
  releaseActiveConnection(key, closeDatabase);
3409
3451
  }
3410
3452
  }
3411
3453
  }
3412
- async function migrateOnce() {
3413
- if (migrationsPromise) return migrationsPromise;
3414
- migrationsPromise = (async () => {
3454
+ const migrations = singleFlight(async () => {
3455
+ try {
3415
3456
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3416
3457
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3417
3458
  return;
3418
3459
  }
3419
- const database2 = await ensureDatabase2();
3460
+ const db = await database2.get();
3420
3461
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
3421
- await migrate(database2, { migrationsFolder: resolvedMigrationsFolder });
3422
- })();
3423
- migrationsPromise = migrationsPromise.catch((error) => {
3424
- migrationsPromise = void 0;
3462
+ await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
3463
+ } catch (error) {
3425
3464
  throw migrationFailure(error);
3426
- });
3427
- await migrationsPromise;
3428
- }
3465
+ }
3466
+ });
3429
3467
  return {
3430
3468
  async getDatabase() {
3431
- await migrateOnce();
3432
- return ensureDatabase2();
3469
+ await migrations.get();
3470
+ return database2.get();
3433
3471
  },
3434
- migrateDatabase: migrateOnce,
3472
+ migrateDatabase: migrations.get,
3435
3473
  closeDatabase,
3436
3474
  async resetDatabase() {
3437
- await ensureDatabase2();
3475
+ await database2.get();
3438
3476
  if (!sqliteClient) return;
3439
3477
  const objects = sqliteClient.query(
3440
3478
  "SELECT name, type FROM main.sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'"
@@ -3448,12 +3486,12 @@ function createSqliteDatabase(options) {
3448
3486
  } finally {
3449
3487
  sqliteClient.exec("PRAGMA foreign_keys = ON;");
3450
3488
  }
3451
- migrationsPromise = void 0;
3489
+ migrations.reset();
3452
3490
  },
3453
3491
  async migrationStatus() {
3454
3492
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3455
3493
  if (localMigrations.length === 0) return [];
3456
- await ensureDatabase2();
3494
+ await database2.get();
3457
3495
  let appliedRows = [];
3458
3496
  try {
3459
3497
  const rows = sqliteClient?.query("SELECT name, applied_at FROM __drizzle_migrations").all();
@@ -3463,17 +3501,17 @@ function createSqliteDatabase(options) {
3463
3501
  return buildMigrationStatus(localMigrations, appliedRows);
3464
3502
  },
3465
3503
  async configureOrm() {
3466
- const database2 = await ensureDatabase2();
3467
- await migrateOnce();
3468
- DrizzleAdapter.configure(database2);
3504
+ const db = await database2.get();
3505
+ await migrations.get();
3506
+ DrizzleAdapter.configure(db);
3469
3507
  },
3470
3508
  async seedDatabase() {
3471
3509
  if (!resolvedSeedersFolder) {
3472
3510
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createSqliteDatabase().');
3473
3511
  }
3474
- const database2 = await ensureDatabase2();
3512
+ const db = await database2.get();
3475
3513
  try {
3476
- await runSeeders(database2, resolvedSeedersFolder);
3514
+ await runSeeders(db, resolvedSeedersFolder);
3477
3515
  } catch (error) {
3478
3516
  throw seedFailure(error);
3479
3517
  }
@@ -3487,37 +3525,28 @@ import { fileURLToPath as fileURLToPath5 } from "url";
3487
3525
  function createD1Database(options) {
3488
3526
  const { binding, migrationsFolder, relations } = options;
3489
3527
  const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath5(migrationsFolder)) : migrationsFolder;
3490
- let databasePromise;
3491
- function ensureDatabase2() {
3492
- if (databasePromise) return databasePromise;
3493
- const promise = (async () => {
3494
- const client = binding();
3495
- if (client == null) {
3496
- throw new Error(
3497
- 'createD1Database: the "binding" resolver returned no D1 binding. On Workers this usually means it ran before the first request \u2014 defer access (e.g. binding: () => getWorkersEnv<Env>().DB) and check the d1_databases entry in wrangler.jsonc.'
3498
- );
3499
- }
3500
- const { drizzle } = await import("drizzle-orm/d1");
3501
- return drizzle(client, relations ? { relations } : void 0);
3502
- })();
3503
- databasePromise = promise.catch((error) => {
3504
- databasePromise = void 0;
3505
- throw error;
3506
- });
3507
- return databasePromise;
3508
- }
3528
+ const databaseHandle = singleFlight(async () => {
3529
+ const client = binding();
3530
+ if (client == null) {
3531
+ throw new Error(
3532
+ 'createD1Database: the "binding" resolver returned no D1 binding. On Workers this usually means it ran before the first request \u2014 defer access (e.g. binding: () => getWorkersEnv<Env>().DB) and check the d1_databases entry in wrangler.jsonc.'
3533
+ );
3534
+ }
3535
+ const { drizzle } = await import("drizzle-orm/d1");
3536
+ return drizzle(client, relations ? { relations } : void 0);
3537
+ });
3509
3538
  return {
3510
- getDatabase: ensureDatabase2,
3539
+ getDatabase: databaseHandle.get,
3511
3540
  async migrateDatabase() {
3512
3541
  throw new Error(
3513
3542
  `D1 migrations are not applied at runtime. Run \`wrangler d1 migrations apply <database>\` (local: add --local) with d1_databases[].migrations_dir pointing at ${migrationsHint}.`
3514
3543
  );
3515
3544
  },
3516
3545
  async closeDatabase() {
3517
- databasePromise = void 0;
3546
+ databaseHandle.reset();
3518
3547
  },
3519
3548
  async configureOrm() {
3520
- const database2 = await ensureDatabase2();
3549
+ const database2 = await databaseHandle.get();
3521
3550
  DrizzleAdapter.configure(database2);
3522
3551
  },
3523
3552
  async seedDatabase() {
@@ -3559,8 +3588,6 @@ function createAwsDataApiDatabase(options) {
3559
3588
  const { migrationsFolder, database: database2, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
3560
3589
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath6(migrationsFolder) : resolve6(String(migrationsFolder));
3561
3590
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath6(seedersFolder) : resolve6(String(seedersFolder));
3562
- let migrationsPromise;
3563
- let databasePromise;
3564
3591
  let client;
3565
3592
  let activeKey;
3566
3593
  const callSite = new Error().stack;
@@ -3591,49 +3618,33 @@ function createAwsDataApiDatabase(options) {
3591
3618
  ...relations ? { relations } : {}
3592
3619
  };
3593
3620
  }
3594
- async function migrateOnce() {
3595
- if (migrationsPromise) {
3596
- return migrationsPromise;
3597
- }
3598
- const promise = (async () => {
3621
+ const migrations = singleFlight(async () => {
3622
+ try {
3599
3623
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3600
3624
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3601
3625
  return;
3602
3626
  }
3603
3627
  const { migrate } = await loadAwsDataApiModules();
3604
3628
  await withAdminDb((db) => migrate(db, { migrationsFolder: resolvedMigrationsFolder }));
3605
- })();
3606
- migrationsPromise = promise.catch((error) => {
3607
- migrationsPromise = void 0;
3629
+ } catch (error) {
3608
3630
  const reason = error instanceof Error ? error.message : String(error);
3609
3631
  throw new Error(`Failed to run database migrations: ${reason}`);
3610
- });
3611
- await migrationsPromise;
3612
- }
3613
- async function getDatabase() {
3614
- if (databasePromise) {
3615
- return databasePromise;
3616
- }
3617
- const promise = (async () => {
3618
- if (migrateOnStart) {
3619
- await migrateOnce();
3620
- }
3621
- const { drizzle } = await loadAwsDataApiModules();
3622
- const connection = resolveConnection();
3623
- const db = drizzle(buildDrizzleConfig(connection));
3624
- client = db.$client;
3625
- activeKey = hotReloadKey("aws-data-api", callSite, `${connection.resourceArn}/${connection.database}`);
3626
- if (activeKey) {
3627
- await replaceActiveConnection(activeKey, closeDatabase);
3628
- }
3629
- return db;
3630
- })();
3631
- databasePromise = promise.catch((error) => {
3632
- databasePromise = void 0;
3633
- throw error;
3634
- });
3635
- return databasePromise;
3636
- }
3632
+ }
3633
+ });
3634
+ const databaseHandle = singleFlight(async () => {
3635
+ if (migrateOnStart) {
3636
+ await migrations.get();
3637
+ }
3638
+ const { drizzle } = await loadAwsDataApiModules();
3639
+ const connection = resolveConnection();
3640
+ const db = drizzle(buildDrizzleConfig(connection));
3641
+ client = db.$client;
3642
+ activeKey = hotReloadKey("aws-data-api", callSite, `${connection.resourceArn}/${connection.database}`);
3643
+ if (activeKey) {
3644
+ await replaceActiveConnection(activeKey, closeDatabase);
3645
+ }
3646
+ return db;
3647
+ });
3637
3648
  async function closeDatabase() {
3638
3649
  if (!client) {
3639
3650
  return;
@@ -3644,21 +3655,21 @@ function createAwsDataApiDatabase(options) {
3644
3655
  client.destroy?.();
3645
3656
  } finally {
3646
3657
  client = void 0;
3647
- databasePromise = void 0;
3658
+ databaseHandle.reset();
3648
3659
  if (key) {
3649
3660
  releaseActiveConnection(key, closeDatabase);
3650
3661
  }
3651
3662
  }
3652
3663
  }
3653
3664
  async function configureOrm() {
3654
- const db = await getDatabase();
3665
+ const db = await databaseHandle.get();
3655
3666
  DrizzleAdapter.configure(db);
3656
3667
  }
3657
3668
  async function seedDatabase() {
3658
3669
  if (!resolvedSeedersFolder) {
3659
3670
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createAwsDataApiDatabase().');
3660
3671
  }
3661
- const db = await getDatabase();
3672
+ const db = await databaseHandle.get();
3662
3673
  await runSeeders(db, resolvedSeedersFolder);
3663
3674
  }
3664
3675
  async function withAdminDb(callback) {
@@ -3677,7 +3688,7 @@ function createAwsDataApiDatabase(options) {
3677
3688
  await adminDb.execute(sql.raw("CREATE SCHEMA public"));
3678
3689
  await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
3679
3690
  });
3680
- migrationsPromise = void 0;
3691
+ migrations.reset();
3681
3692
  }
3682
3693
  async function migrationStatus() {
3683
3694
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
@@ -3700,8 +3711,8 @@ function createAwsDataApiDatabase(options) {
3700
3711
  return buildMigrationStatus(localMigrations, appliedRows);
3701
3712
  }
3702
3713
  return {
3703
- getDatabase,
3704
- migrateDatabase: migrateOnce,
3714
+ getDatabase: databaseHandle.get,
3715
+ migrateDatabase: migrations.get,
3705
3716
  closeDatabase,
3706
3717
  configureOrm,
3707
3718
  seedDatabase,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {