@guren/orm 2.7.0 → 2.8.0

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
@@ -324,6 +324,7 @@ interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
324
324
  }
325
325
  /** Interface for ORM adapters that power the Model class; DrizzleAdapter by default. */
326
326
  interface ORMAdapter {
327
+ /** Must not commit before the callback's promise settles: drizzle's bun-sqlite does. */
327
328
  transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
328
329
  findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
329
330
  findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord | null>;
@@ -860,6 +861,7 @@ type DrizzleDatabase = {
860
861
  insert(table: unknown): DrizzleLikeInsert;
861
862
  update?(table: unknown): DrizzleLikeUpdate;
862
863
  delete?(table: unknown): DrizzleLikeDelete;
864
+ run?(query: unknown): Promise<unknown>;
863
865
  transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
864
866
  };
865
867
  declare const DrizzleAdapter: ORMAdapterAdvanced & {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or } from "drizzle-orm";
1
+ import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or, sql } from "drizzle-orm";
2
2
  import { extname, relative, resolve } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { existsSync, readdirSync } from "node:fs";
@@ -138,6 +138,9 @@ function buildDrizzleConditions(table, conditions) {
138
138
  //#endregion
139
139
  //#region src/adapters/drizzle-adapter.ts
140
140
  let database;
141
+ let transactionAwaitsCallback;
142
+ let transactionQueue = Promise.resolve();
143
+ let transactionScope;
141
144
  function ensureDatabase() {
142
145
  if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
143
146
  return database;
@@ -217,9 +220,78 @@ async function resolveWithReturning(query) {
217
220
  row: void 0
218
221
  };
219
222
  }
223
+ const NOOP = () => void 0;
224
+ /**
225
+ * Whether `db.transaction()` awaits its callback before committing: drizzle's
226
+ * bun-sqlite COMMITs on whatever the callback returns, d1 and every pg/mysql
227
+ * driver await it. Probed rather than matched against a driver list, because
228
+ * this adapter takes any drizzle-shaped handle and one a list never named gets
229
+ * the wrong path silently. Costs one empty transaction per configured database.
230
+ */
231
+ async function awaitsItsCallback(db) {
232
+ if (transactionAwaitsCallback === void 0) {
233
+ const probe = db.transaction?.(NOOP);
234
+ transactionAwaitsCallback = isPromiseLike(probe);
235
+ if (isPromiseLike(probe)) await probe.catch(NOOP);
236
+ }
237
+ return transactionAwaitsCallback;
238
+ }
239
+ /**
240
+ * Imported on demand so `node:async_hooks` stays off the module graph of a
241
+ * Workers or Lambda bundle, whose drivers all await their callback and never
242
+ * reach this branch. The promise is what is memoized, not the storage: two
243
+ * concurrent first callers must not end up asking different instances.
244
+ */
245
+ function loadTransactionScope() {
246
+ transactionScope ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
247
+ const store = new AsyncLocalStorage();
248
+ return {
249
+ run: (fn) => store.run(true, fn),
250
+ isInside: () => store.getStore() === true
251
+ };
252
+ });
253
+ return transactionScope;
254
+ }
255
+ /**
256
+ * Serializes what `runExclusively` drives, since one connection takes one
257
+ * transaction. Waiting is only safe for a caller that is not already inside one:
258
+ * that caller would be queued behind itself. Async context is what separates the
259
+ * two, and it is the only thing that can — arrival order cannot tell a nested
260
+ * call from an unrelated concurrent one, and refusing both punishes the second.
261
+ */
262
+ async function runOwnTransaction(db, callback) {
263
+ if (typeof db.run !== "function") throw new Error("DrizzleAdapter: the configured database commits before its transaction callback has awaited anything, and exposes no run() to drive BEGIN/COMMIT with, so transactions on it cannot be made atomic.");
264
+ const scope = await loadTransactionScope();
265
+ if (scope.isInside()) throw new Error("DrizzleAdapter: cannot begin a transaction inside another one. This driver holds a single connection, which takes one transaction at a time, so the inner transaction would wait on the outer one to finish and the outer on the inner.");
266
+ const run = db.run.bind(db);
267
+ const slot = transactionQueue.then(() => runExclusively(db, run, scope, callback));
268
+ transactionQueue = slot.then(NOOP, NOOP);
269
+ return slot;
270
+ }
271
+ /**
272
+ * BEGIN/COMMIT/ROLLBACK driven here so an async callback is honoured on a driver
273
+ * that would otherwise commit before awaiting it. The handle itself is the
274
+ * transaction scope: these drivers hold one connection, so every statement
275
+ * between BEGIN and COMMIT is inside it. Callers reach this one at a time.
276
+ */
277
+ async function runExclusively(db, run, scope, callback) {
278
+ await run(sql.raw("begin"));
279
+ try {
280
+ const result = await scope.run(() => callback(db));
281
+ await run(sql.raw("commit"));
282
+ return result;
283
+ } catch (error) {
284
+ try {
285
+ await run(sql.raw("rollback"));
286
+ } catch {}
287
+ throw error;
288
+ }
289
+ }
220
290
  const DrizzleAdapter = {
221
291
  configure(db) {
222
292
  database = db;
293
+ transactionAwaitsCallback = void 0;
294
+ transactionQueue = Promise.resolve();
223
295
  },
224
296
  getDatabase() {
225
297
  return ensureDatabase();
@@ -339,7 +411,8 @@ const DrizzleAdapter = {
339
411
  async transaction(callback) {
340
412
  const db = ensureDatabase();
341
413
  if (typeof db.transaction !== "function") throw new Error("DrizzleAdapter: configured database does not support transactions.");
342
- return db.transaction(callback);
414
+ if (await awaitsItsCallback(db)) return db.transaction(callback);
415
+ return runOwnTransaction(db, callback);
343
416
  }
344
417
  };
345
418
  //#endregion
@@ -2275,6 +2348,28 @@ function buildMigrationStatus(localMigrations, appliedRows) {
2275
2348
  };
2276
2349
  });
2277
2350
  }
2351
+ /**
2352
+ * Local migrations the tracker has no row for, in the order the migrator will
2353
+ * apply them. Best-effort by contract: the names exist to be logged, and a
2354
+ * tracker this driver cannot read costs the names, not the boot.
2355
+ */
2356
+ async function pendingMigrationNames(migrationsFolder, readApplied) {
2357
+ try {
2358
+ return buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied()).filter((entry) => !entry.applied).map((entry) => entry.name);
2359
+ } catch {
2360
+ return [];
2361
+ }
2362
+ }
2363
+ /**
2364
+ * Names what a run applied, so a migration nobody added on purpose — an orphan
2365
+ * folder a generator left behind on a branch that was deleted, say — does not
2366
+ * reach the database in silence. Silent when the run applied nothing: an
2367
+ * up-to-date database boots on every restart, and a line there is one nobody reads.
2368
+ */
2369
+ function reportAppliedMigrations(applied, migrationsFolder) {
2370
+ if (applied.length === 0) return;
2371
+ console.info(`[guren/orm] Applied ${applied.length} migration(s) from ${migrationsFolder}: ${applied.join(", ")}`);
2372
+ }
2278
2373
  //#endregion
2279
2374
  //#region src/seeder.ts
2280
2375
  const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -2419,7 +2514,26 @@ function createPostgresDatabase(options) {
2419
2514
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
2420
2515
  return resolved;
2421
2516
  }
2517
+ let reapplyingAfterReset = false;
2518
+ /**
2519
+ * Tracker rows over an open client. Only a missing tracker means "nothing
2520
+ * applied": a denied SELECT, a broken schema, or an unreachable server must
2521
+ * not read as all-pending.
2522
+ */
2523
+ async function readAppliedMigrations(client) {
2524
+ try {
2525
+ return (await client.unsafe("SELECT name FROM drizzle.__drizzle_migrations")).map((row) => ({
2526
+ name: row.name,
2527
+ appliedAt: null
2528
+ }));
2529
+ } catch (error) {
2530
+ if (isMissingTrackerTable(error, "postgres")) return [];
2531
+ throw error;
2532
+ }
2533
+ }
2422
2534
  const migrations = singleFlight(async () => {
2535
+ const report = !reapplyingAfterReset;
2536
+ reapplyingAfterReset = false;
2423
2537
  let endpoint;
2424
2538
  try {
2425
2539
  const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
@@ -2432,10 +2546,13 @@ function createPostgresDatabase(options) {
2432
2546
  ...clientOptions
2433
2547
  });
2434
2548
  try {
2435
- await migrate(drizzle({
2549
+ const db = drizzle({
2436
2550
  client: migrationClient,
2437
2551
  ...relations ? { relations } : {}
2438
- }), { migrationsFolder: resolvedMigrationsFolder });
2552
+ });
2553
+ const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(migrationClient)) : [];
2554
+ await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
2555
+ reportAppliedMigrations(pending, resolvedMigrationsFolder);
2439
2556
  } finally {
2440
2557
  await migrationClient.end({ timeout: 0 });
2441
2558
  }
@@ -2507,24 +2624,13 @@ function createPostgresDatabase(options) {
2507
2624
  await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
2508
2625
  });
2509
2626
  migrations.reset();
2627
+ reapplyingAfterReset = true;
2510
2628
  return migrations.get();
2511
2629
  }
2512
2630
  async function migrationStatus() {
2513
2631
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
2514
2632
  if (localMigrations.length === 0) return [];
2515
- return buildMigrationStatus(localMigrations, await withAdminClient(async (adminClient) => {
2516
- try {
2517
- return (await adminClient.unsafe("SELECT name FROM drizzle.__drizzle_migrations")).map((row) => {
2518
- return {
2519
- name: row.name,
2520
- appliedAt: null
2521
- };
2522
- });
2523
- } catch (error) {
2524
- if (isMissingTrackerTable(error, "postgres")) return [];
2525
- throw error;
2526
- }
2527
- }));
2633
+ return buildMigrationStatus(localMigrations, await withAdminClient(readAppliedMigrations));
2528
2634
  }
2529
2635
  return {
2530
2636
  getDatabase: database.get,
@@ -2567,7 +2673,28 @@ function createMySqlDatabase(options) {
2567
2673
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
2568
2674
  return resolved;
2569
2675
  }
2676
+ let reapplyingAfterReset = false;
2677
+ /**
2678
+ * Tracker rows over an open handle. Only a missing tracker means "nothing
2679
+ * applied": a denied SELECT or an unreachable server must not read as
2680
+ * all-pending.
2681
+ */
2682
+ async function readAppliedMigrations(adminDb) {
2683
+ const { sql } = await import("drizzle-orm");
2684
+ try {
2685
+ const [rows] = await adminDb.execute(sql.raw("SELECT name, applied_at FROM __drizzle_migrations"));
2686
+ return rows.map((row) => ({
2687
+ name: row.name,
2688
+ appliedAt: row.applied_at
2689
+ }));
2690
+ } catch (error) {
2691
+ if (isMissingTrackerTable(error, "mysql")) return [];
2692
+ throw error;
2693
+ }
2694
+ }
2570
2695
  const migrations = singleFlight(async () => {
2696
+ const report = !reapplyingAfterReset;
2697
+ reapplyingAfterReset = false;
2571
2698
  let endpoint;
2572
2699
  try {
2573
2700
  const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
@@ -2580,10 +2707,13 @@ function createMySqlDatabase(options) {
2580
2707
  ...clientOptions
2581
2708
  });
2582
2709
  try {
2583
- await migrate(drizzle({
2710
+ const migrationDb = drizzle({
2584
2711
  client: migrationClient,
2585
2712
  ...relations ? { relations } : {}
2586
- }), { migrationsFolder: resolvedMigrationsFolder });
2713
+ });
2714
+ const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(migrationDb)) : [];
2715
+ await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
2716
+ reportAppliedMigrations(pending, resolvedMigrationsFolder);
2587
2717
  } finally {
2588
2718
  await closePool(migrationClient);
2589
2719
  }
@@ -2664,24 +2794,13 @@ function createMySqlDatabase(options) {
2664
2794
  }
2665
2795
  });
2666
2796
  migrations.reset();
2797
+ reapplyingAfterReset = true;
2667
2798
  return migrations.get();
2668
2799
  }
2669
2800
  async function migrationStatus() {
2670
2801
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
2671
2802
  if (localMigrations.length === 0) return [];
2672
- const { sql } = await import("drizzle-orm");
2673
- return buildMigrationStatus(localMigrations, await withAdminDb(async (adminDb) => {
2674
- try {
2675
- const [rows] = await adminDb.execute(sql.raw("SELECT name, applied_at FROM __drizzle_migrations"));
2676
- return rows.map((row) => ({
2677
- name: row.name,
2678
- appliedAt: row.applied_at
2679
- }));
2680
- } catch (error) {
2681
- if (isMissingTrackerTable(error, "mysql")) return [];
2682
- throw error;
2683
- }
2684
- }));
2803
+ return buildMigrationStatus(localMigrations, await withAdminDb(readAppliedMigrations));
2685
2804
  }
2686
2805
  return {
2687
2806
  getDatabase: database.get,
@@ -2804,13 +2923,30 @@ function createSqliteDatabase(options) {
2804
2923
  if (key) releaseActiveConnection(key, closeDatabase);
2805
2924
  }
2806
2925
  }
2926
+ let reapplyingAfterReset = false;
2927
+ /** Tracker rows over the open handle. Only a missing tracker means "nothing applied"; a drifted column must not read as all-pending. */
2928
+ function readAppliedMigrations() {
2929
+ try {
2930
+ return (sqliteClient?.query("SELECT name, applied_at FROM __drizzle_migrations").all() ?? []).map((row) => ({
2931
+ name: row.name,
2932
+ appliedAt: row.applied_at
2933
+ }));
2934
+ } catch (error) {
2935
+ if (!isMissingTrackerTable(error, "sqlite")) throw error;
2936
+ return [];
2937
+ }
2938
+ }
2807
2939
  const migrations = singleFlight(async () => {
2940
+ const report = !reapplyingAfterReset;
2941
+ reapplyingAfterReset = false;
2808
2942
  try {
2809
2943
  const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
2810
2944
  if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
2811
2945
  const db = await database.get();
2946
+ const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, readAppliedMigrations) : [];
2812
2947
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
2813
2948
  await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
2949
+ reportAppliedMigrations(pending, resolvedMigrationsFolder);
2814
2950
  return summary;
2815
2951
  } catch (error) {
2816
2952
  throw migrationFailure(error);
@@ -2837,22 +2973,14 @@ function createSqliteDatabase(options) {
2837
2973
  sqliteClient.exec("PRAGMA foreign_keys = ON;");
2838
2974
  }
2839
2975
  migrations.reset();
2976
+ reapplyingAfterReset = true;
2840
2977
  return migrations.get();
2841
2978
  },
2842
2979
  async migrationStatus() {
2843
2980
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
2844
2981
  if (localMigrations.length === 0) return [];
2845
2982
  await database.get();
2846
- let appliedRows = [];
2847
- try {
2848
- appliedRows = (sqliteClient?.query("SELECT name, applied_at FROM __drizzle_migrations").all() ?? []).map((row) => ({
2849
- name: row.name,
2850
- appliedAt: row.applied_at
2851
- }));
2852
- } catch (error) {
2853
- if (!isMissingTrackerTable(error, "sqlite")) throw error;
2854
- }
2855
- return buildMigrationStatus(localMigrations, appliedRows);
2983
+ return buildMigrationStatus(localMigrations, readAppliedMigrations());
2856
2984
  },
2857
2985
  async configureOrm() {
2858
2986
  const db = await database.get();
@@ -2958,12 +3086,19 @@ function createAwsDataApiDatabase(options) {
2958
3086
  ...relations ? { relations } : {}
2959
3087
  };
2960
3088
  }
3089
+ let reapplyingAfterReset = false;
2961
3090
  const migrations = singleFlight(async () => {
3091
+ const report = !reapplyingAfterReset;
3092
+ reapplyingAfterReset = false;
2962
3093
  try {
2963
3094
  const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
2964
3095
  if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
2965
3096
  const { migrate } = await loadAwsDataApiModules();
2966
- await withAdminDb((db) => migrate(db, { migrationsFolder: resolvedMigrationsFolder }));
3097
+ await withAdminDb(async (db) => {
3098
+ const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(db)) : [];
3099
+ await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
3100
+ reportAppliedMigrations(pending, resolvedMigrationsFolder);
3101
+ });
2967
3102
  return summary;
2968
3103
  } catch (error) {
2969
3104
  const reason = error instanceof Error ? error.message : String(error);
@@ -3017,24 +3152,31 @@ function createAwsDataApiDatabase(options) {
3017
3152
  await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
3018
3153
  });
3019
3154
  migrations.reset();
3155
+ reapplyingAfterReset = true;
3020
3156
  return migrations.get();
3021
3157
  }
3158
+ /**
3159
+ * Tracker rows over an open handle. Only a missing tracker table means
3160
+ * "nothing applied". Anything else (IAM denial, network) must surface:
3161
+ * reporting it as all-pending could prompt a re-run of applied migrations.
3162
+ */
3163
+ async function readAppliedMigrations(adminDb) {
3164
+ const { sql } = await import("drizzle-orm");
3165
+ try {
3166
+ const result = await adminDb.execute(sql.raw("SELECT name FROM drizzle.__drizzle_migrations"));
3167
+ return (Array.isArray(result) ? result : result.rows ?? []).map((row) => ({
3168
+ name: row.name,
3169
+ appliedAt: null
3170
+ }));
3171
+ } catch (error) {
3172
+ if (isMissingTrackerTableError(error)) return [];
3173
+ throw error;
3174
+ }
3175
+ }
3022
3176
  async function migrationStatus() {
3023
3177
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3024
3178
  if (localMigrations.length === 0) return [];
3025
- const { sql } = await import("drizzle-orm");
3026
- return buildMigrationStatus(localMigrations, await withAdminDb(async (adminDb) => {
3027
- try {
3028
- const result = await adminDb.execute(sql.raw("SELECT name FROM drizzle.__drizzle_migrations"));
3029
- return (Array.isArray(result) ? result : result.rows ?? []).map((row) => ({
3030
- name: row.name,
3031
- appliedAt: null
3032
- }));
3033
- } catch (error) {
3034
- if (isMissingTrackerTableError(error)) return [];
3035
- throw error;
3036
- }
3037
- }));
3179
+ return buildMigrationStatus(localMigrations, await withAdminDb(readAppliedMigrations));
3038
3180
  }
3039
3181
  return {
3040
3182
  getDatabase: databaseHandle.get,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/instance-guard.ts",