@guren/orm 2.9.0 → 2.10.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/index.d.ts CHANGED
@@ -961,6 +961,11 @@ interface MigrationStatusEntry {
961
961
  name: string;
962
962
  applied: boolean;
963
963
  appliedAt: Date | null;
964
+ /**
965
+ * True for a tracker row no local folder carries: applied to this database,
966
+ * then deleted from disk (or migrated by another checkout). Absent otherwise.
967
+ */
968
+ orphaned?: boolean;
964
969
  }
965
970
  //#endregion
966
971
  //#region src/seeder.d.ts
package/dist/index.js CHANGED
@@ -3,6 +3,19 @@ import { extname, relative, resolve } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { existsSync, readdirSync } from "node:fs";
5
5
  import { readdir } from "node:fs/promises";
6
+ //#region src/hot-reload-runtime.ts
7
+ /**
8
+ * `bun --hot` re-runs the module graph in-process: module-level state resets
9
+ * while `globalThis` survives, so state parked there has to tell a
10
+ * re-evaluation from a new participant. `bun --watch` restarts the process
11
+ * instead, and this answers for no other in-process re-evaluator (a Vite SSR
12
+ * runner, `vi.resetModules()`). Twin of
13
+ * `packages/server/src/hot-reload/hot-disposables.ts` — keep the two in step.
14
+ */
15
+ function isHotReloadRuntime() {
16
+ return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
17
+ }
18
+ //#endregion
6
19
  //#region src/instance-guard.ts
7
20
  /**
8
21
  * Detects multiple loaded copies of @guren/orm in one process. Model and
@@ -12,20 +25,37 @@ import { readdir } from "node:fs/promises";
12
25
  */
13
26
  const INSTANCE_KEY = Symbol.for("guren.orm.loaded");
14
27
  const globalScope = globalThis;
15
- const marker = globalScope[INSTANCE_KEY];
16
- if (!marker) globalScope[INSTANCE_KEY] = {
17
- count: 1,
18
- warned: false
19
- };
20
- else {
28
+ /** Empty where a bundler shims `import.meta.url` away, which no copy can be told apart by. */
29
+ function moduleIdentity() {
30
+ return import.meta.url || void 0;
31
+ }
32
+ /**
33
+ * Counts this evaluation as a copy unless the same module URL already
34
+ * registered under `bun --hot`, which re-evaluates a file against a surviving
35
+ * `globalThis`. A bundle inlines both copies at one URL, so outside `--hot` a
36
+ * repeat is a duplicate rather than a reload. Any other in-process
37
+ * re-evaluator (a Vite SSR runner, `vi.resetModules()`) still counts.
38
+ */
39
+ function registerOrmInstance(identity) {
40
+ const marker = globalScope[INSTANCE_KEY] ??= {
41
+ count: 0,
42
+ warned: false,
43
+ identities: /* @__PURE__ */ new Set()
44
+ };
45
+ const identities = marker.identities ??= /* @__PURE__ */ new Set();
46
+ if (identity !== void 0) {
47
+ if (identities.has(identity) && isHotReloadRuntime()) return;
48
+ identities.add(identity);
49
+ }
21
50
  marker.count += 1;
22
51
  const quiet = typeof process !== "undefined" && process.env.GUREN_QUIET_DUPLICATE_ORM === "1";
23
- if (!marker.warned && !quiet) {
52
+ if (marker.count > 1 && !marker.warned && !quiet) {
24
53
  marker.warned = true;
25
54
  console.warn(`[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.
26
55
  [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).`);
27
56
  }
28
57
  }
58
+ registerOrmInstance(moduleIdentity());
29
59
  //#endregion
30
60
  //#region src/internal-keys.ts
31
61
  /**
@@ -2250,6 +2280,16 @@ function SoftDeletes(Base) {
2250
2280
  }
2251
2281
  //#endregion
2252
2282
  //#region src/active-connections.ts
2283
+ /**
2284
+ * Closes the database client a previous module evaluation left open.
2285
+ *
2286
+ * `bun --hot` re-runs the module graph in-process: a `create*Database()`
2287
+ * factory's cached client resets but its connection leaks, one per reload.
2288
+ * Bun exposes no `import.meta.hot` under `--hot` (checked on 1.3.14), so the
2289
+ * teardown is parked on `globalThis`, which survives re-evaluation. Handles are
2290
+ * keyed by caller file + target, not line, so two handles built in one file
2291
+ * against one database share a key; give them separate modules.
2292
+ */
2253
2293
  const REGISTRY_KEY = Symbol.for("guren.orm.activeConnections");
2254
2294
  /**
2255
2295
  * Awaiting the teardown is the back-pressure that keeps a burst of reloads from
@@ -2265,10 +2305,6 @@ function getRegistry() {
2265
2305
  scope[REGISTRY_KEY] = registry;
2266
2306
  return registry;
2267
2307
  }
2268
- /** `bun --watch` restarts the process instead, so `--hot` is the only mode that leaks. */
2269
- function isHotReloadRuntime() {
2270
- return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
2271
- }
2272
2308
  /** Both match one character, so neither can backtrack the way `\s*` in a pattern can. */
2273
2309
  const WHITESPACE = /\s/;
2274
2310
  const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
@@ -2550,40 +2586,82 @@ function listLocalMigrations(migrationsFolder) {
2550
2586
  if (!existsSync(migrationsFolder)) return [];
2551
2587
  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));
2552
2588
  }
2589
+ function parseAppliedAt(row) {
2590
+ if (!row?.appliedAt) return null;
2591
+ const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
2592
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
2593
+ }
2553
2594
  /**
2554
2595
  * Joins local migration folders with the migrator's tracker rows. Drizzle
2555
2596
  * decides pending migrations by name membership, so status uses that rule.
2597
+ * The same rule makes the migrator skip a row with no folder, whatever that
2598
+ * row's migration created, so those rows come back too, marked `orphaned`.
2556
2599
  */
2557
2600
  function buildMigrationStatus(localMigrations, appliedRows) {
2558
- const appliedByName = /* @__PURE__ */ new Map();
2559
- for (const row of appliedRows) if (row.name) appliedByName.set(row.name, row);
2560
- return localMigrations.map((migration) => {
2561
- const row = appliedByName.get(migration.name);
2562
- let appliedAt = null;
2563
- if (row?.appliedAt) {
2564
- const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
2565
- appliedAt = Number.isNaN(parsed.getTime()) ? null : parsed;
2566
- }
2601
+ const unmatchedRows = /* @__PURE__ */ new Map();
2602
+ for (const row of appliedRows) if (row.name) unmatchedRows.set(row.name, row);
2603
+ const entries = localMigrations.map((migration) => {
2604
+ const row = unmatchedRows.get(migration.name);
2605
+ unmatchedRows.delete(migration.name);
2567
2606
  return {
2568
2607
  name: migration.name,
2569
2608
  applied: row !== void 0,
2570
- appliedAt
2609
+ appliedAt: parseAppliedAt(row)
2571
2610
  };
2572
2611
  });
2612
+ if (unmatchedRows.size === 0) return entries;
2613
+ const orphaned = [...unmatchedRows].map(([name, row]) => ({
2614
+ name,
2615
+ applied: true,
2616
+ appliedAt: parseAppliedAt(row),
2617
+ orphaned: true
2618
+ }));
2619
+ return [...entries, ...orphaned].sort((a, b) => a.name.localeCompare(b.name));
2573
2620
  }
2574
2621
  /**
2575
- * Local migrations the tracker has no row for, in the order the migrator will
2576
- * apply them. Best-effort by contract: the names exist to be logged, and a
2577
- * tracker this driver cannot read costs the names, not the boot.
2622
+ * Where the migrations folder and the tracker disagree, in both directions.
2623
+ * Best-effort by contract: the names exist to be logged, and a tracker this
2624
+ * driver cannot read costs the names, not the boot.
2578
2625
  */
2579
- async function pendingMigrationNames(migrationsFolder, readApplied) {
2626
+ async function readMigrationDrift(migrationsFolder, readApplied) {
2580
2627
  try {
2581
- return buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied()).filter((entry) => !entry.applied).map((entry) => entry.name);
2628
+ const status = buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied());
2629
+ return {
2630
+ pending: status.filter((entry) => !entry.applied).map((entry) => entry.name),
2631
+ orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name)
2632
+ };
2582
2633
  } catch {
2583
- return [];
2634
+ return {
2635
+ pending: [],
2636
+ orphaned: []
2637
+ };
2584
2638
  }
2585
2639
  }
2586
2640
  /**
2641
+ * One migrator run, reported on both sides. The tracker is read before the
2642
+ * migrator writes (afterwards every row is applied), and orphans are named
2643
+ * before it runs, since they are the likeliest reason it is about to fail.
2644
+ * Without `readApplied` nothing is read or reported: a reset's re-apply.
2645
+ */
2646
+ async function migrateAndReport(migrationsFolder, { readApplied, migrate }) {
2647
+ const drift = readApplied ? await readMigrationDrift(migrationsFolder, readApplied) : {
2648
+ pending: [],
2649
+ orphaned: []
2650
+ };
2651
+ reportOrphanedMigrations(drift.orphaned, migrationsFolder);
2652
+ await migrate();
2653
+ reportAppliedMigrations(drift.pending, migrationsFolder);
2654
+ }
2655
+ /**
2656
+ * Warns on every boot while the tracker holds rows no folder carries, such as a
2657
+ * generator's migration a dev server applied before `git clean` removed it. Its
2658
+ * tables stay behind, and a later migration creating them again fails.
2659
+ */
2660
+ function reportOrphanedMigrations(orphaned, migrationsFolder) {
2661
+ if (orphaned.length === 0) return;
2662
+ console.warn(`[guren/orm] ${orphaned.length} migration(s) applied to this database have no folder in ${migrationsFolder}: ${orphaned.join(", ")}.\n[guren/orm] Whatever they created is still in the database. \`bun run db:status\` lists them as orphaned.`);
2663
+ }
2664
+ /**
2587
2665
  * Names what a run applied, so a migration nobody added on purpose — an orphan
2588
2666
  * folder a generator left behind on a branch that was deleted, say — does not
2589
2667
  * reach the database in silence. Silent when the run applied nothing: an
@@ -2773,9 +2851,10 @@ function createPostgresDatabase(options) {
2773
2851
  client: migrationClient,
2774
2852
  ...relations ? { relations } : {}
2775
2853
  });
2776
- const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(migrationClient)) : [];
2777
- await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
2778
- reportAppliedMigrations(pending, resolvedMigrationsFolder);
2854
+ await migrateAndReport(resolvedMigrationsFolder, {
2855
+ readApplied: report ? () => readAppliedMigrations(migrationClient) : void 0,
2856
+ migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
2857
+ });
2779
2858
  } finally {
2780
2859
  await migrationClient.end({ timeout: 0 });
2781
2860
  }
@@ -2934,9 +3013,10 @@ function createMySqlDatabase(options) {
2934
3013
  client: migrationClient,
2935
3014
  ...relations ? { relations } : {}
2936
3015
  });
2937
- const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(migrationDb)) : [];
2938
- await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
2939
- reportAppliedMigrations(pending, resolvedMigrationsFolder);
3016
+ await migrateAndReport(resolvedMigrationsFolder, {
3017
+ readApplied: report ? () => readAppliedMigrations(migrationDb) : void 0,
3018
+ migrate: () => migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder })
3019
+ });
2940
3020
  } finally {
2941
3021
  await closePool(migrationClient);
2942
3022
  }
@@ -3042,35 +3122,41 @@ async function closePool(pool) {
3042
3122
  }
3043
3123
  //#endregion
3044
3124
  //#region src/sqlite.ts
3045
- function isInMemory(dbPath) {
3046
- return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
3047
- }
3125
+ const MEMORY = { kind: "memory" };
3126
+ const UNRESOLVABLE = { kind: "unresolvable" };
3048
3127
  /**
3049
- * Path to open for `dbPath`; undefined for in-memory forms and unresolvable
3050
- * URIs, which `new Database()` refuses with no directory created. `file:` URI
3051
- * support is compile-time `SQLITE_USE_URI` (measured: on for Bun/macOS via system
3052
- * libsqlite3, off in Bun's Linux build, which opens `file:local.db` literally), so
3053
- * parsing follows https://sqlite.org/uri.html, not WHATWG (`/local.db` vs the cwd).
3128
+ * What `dbPath` opens. `file:` URI support is compile-time `SQLITE_USE_URI`
3129
+ * (measured: on for Bun/macOS via system libsqlite3, off in Bun's Linux build,
3130
+ * which opens `file:local.db` and `file::memory:` as literal files), so only an
3131
+ * unresolvable URI reaches `new Database()`, and parsing follows
3132
+ * https://sqlite.org/uri.html, not WHATWG (`/local.db` vs the cwd).
3054
3133
  */
3055
- function sqliteFilePath(dbPath) {
3056
- if (isInMemory(dbPath)) return void 0;
3057
- if (!dbPath.startsWith("file:")) return resolve(dbPath);
3134
+ function sqliteTarget(dbPath) {
3135
+ if (dbPath === ":memory:" || dbPath === "") return MEMORY;
3136
+ if (!dbPath.startsWith("file:")) return {
3137
+ kind: "file",
3138
+ path: resolve(dbPath)
3139
+ };
3058
3140
  let rest = dbPath.slice(5);
3059
3141
  if (rest.startsWith("//")) {
3060
3142
  const pathStart = rest.indexOf("/", 2);
3061
3143
  const authority = pathStart === -1 ? rest.slice(2) : rest.slice(2, pathStart);
3062
- if (authority !== "" && authority !== "localhost") return void 0;
3144
+ if (authority !== "" && authority !== "localhost") return UNRESOLVABLE;
3063
3145
  rest = pathStart === -1 ? "" : rest.slice(pathStart);
3064
3146
  }
3065
3147
  const marker = rest.search(/[?#]/);
3066
3148
  const encodedPath = marker === -1 ? rest : rest.slice(0, marker);
3067
3149
  const query = marker !== -1 && rest[marker] === "?" ? rest.slice(marker + 1).split("#")[0] : "";
3068
- if (query !== "") throw new Error(`createSqliteDatabase() cannot honour the URI parameters in ${dbPath} (?${query}). They are only read by a sqlite built with SQLITE_USE_URI, which Bun provides on some platforms and not others, so this driver resolves the URI to a path itself. Pass a plain path, and set the behaviour those parameters asked for in code.`);
3069
- if (encodedPath === "") return void 0;
3150
+ if (query !== "") throw new Error(`createSqliteDatabase() cannot honour the URI parameters in ${dbPath} (?${query}). They are only read by a sqlite built with SQLITE_USE_URI, which Bun provides on some platforms and not others, so this driver resolves the URI to a path itself. Pass a plain path or ":memory:", and set the behaviour those parameters asked for in code.`);
3151
+ if (encodedPath === "") return UNRESOLVABLE;
3070
3152
  try {
3071
- return resolve(decodeURIComponent(encodedPath));
3153
+ const path = decodeURIComponent(encodedPath);
3154
+ return path === ":memory:" ? MEMORY : {
3155
+ kind: "file",
3156
+ path: resolve(path)
3157
+ };
3072
3158
  } catch {
3073
- return;
3159
+ return UNRESOLVABLE;
3074
3160
  }
3075
3161
  }
3076
3162
  /**
@@ -3113,7 +3199,8 @@ function createSqliteDatabase(options) {
3113
3199
  }
3114
3200
  const database = singleFlight(async () => {
3115
3201
  const dbPath = resolveFilename();
3116
- const dbFile = sqliteFilePath(dbPath);
3202
+ const target = sqliteTarget(dbPath);
3203
+ const dbFile = target.kind === "file" ? target.path : void 0;
3117
3204
  if (dbFile) {
3118
3205
  const { mkdirSync } = await import("node:fs");
3119
3206
  const { dirname } = await import("node:path");
@@ -3123,7 +3210,7 @@ function createSqliteDatabase(options) {
3123
3210
  }
3124
3211
  const { Database } = await import("bun:sqlite");
3125
3212
  const { drizzle } = await import("drizzle-orm/bun-sqlite");
3126
- const sqlite = new Database(dbFile ?? dbPath);
3213
+ const sqlite = new Database(target.kind === "memory" ? ":memory:" : dbFile ?? dbPath);
3127
3214
  sqlite.exec("PRAGMA journal_mode = WAL;");
3128
3215
  sqliteClient = sqlite;
3129
3216
  const handle = drizzle({
@@ -3166,10 +3253,11 @@ function createSqliteDatabase(options) {
3166
3253
  const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
3167
3254
  if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
3168
3255
  const db = await database.get();
3169
- const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, readAppliedMigrations) : [];
3170
3256
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
3171
- await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
3172
- reportAppliedMigrations(pending, resolvedMigrationsFolder);
3257
+ await migrateAndReport(resolvedMigrationsFolder, {
3258
+ readApplied: report ? readAppliedMigrations : void 0,
3259
+ migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3260
+ });
3173
3261
  return summary;
3174
3262
  } catch (error) {
3175
3263
  throw migrationFailure(error);
@@ -3318,9 +3406,10 @@ function createAwsDataApiDatabase(options) {
3318
3406
  if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
3319
3407
  const { migrate } = await loadAwsDataApiModules();
3320
3408
  await withAdminDb(async (db) => {
3321
- const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, () => readAppliedMigrations(db)) : [];
3322
- await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
3323
- reportAppliedMigrations(pending, resolvedMigrationsFolder);
3409
+ await migrateAndReport(resolvedMigrationsFolder, {
3410
+ readApplied: report ? () => readAppliedMigrations(db) : void 0,
3411
+ migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3412
+ });
3324
3413
  });
3325
3414
  return summary;
3326
3415
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.9.0",
3
+ "version": "2.10.1",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/instance-guard.ts",