@guren/orm 1.1.0 → 1.2.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
@@ -1592,6 +1592,46 @@ interface SqliteDatabase {
1592
1592
  }
1593
1593
  declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
1594
1594
 
1595
+ interface D1DatabaseOptions {
1596
+ /**
1597
+ * Resolver returning the Cloudflare D1 binding. Bindings arrive with the
1598
+ * first request on Workers, so this must be a deferred closure, e.g.
1599
+ * `binding: () => getWorkersEnv<Env>().DB`.
1600
+ */
1601
+ binding: () => unknown;
1602
+ /**
1603
+ * Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
1604
+ * `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` at
1605
+ * this folder); the factory only references it in error guidance.
1606
+ */
1607
+ migrationsFolder?: string | URL;
1608
+ /**
1609
+ * Drizzle relations for RQB v2 (`db.query.*`).
1610
+ * Build with `defineRelations(schema, ...)` from `drizzle-orm`,
1611
+ * or with `relations()` from `drizzle-orm/_relations` for the RQB v1 partial-upgrade path.
1612
+ */
1613
+ relations?: Record<string, unknown>;
1614
+ }
1615
+ interface D1DatabaseHandle {
1616
+ getDatabase(): Promise<unknown>;
1617
+ /** Always throws: D1 migrations are applied with `wrangler d1 migrations apply`, never at runtime. */
1618
+ migrateDatabase(): Promise<void>;
1619
+ closeDatabase(): Promise<void>;
1620
+ configureOrm(): Promise<void>;
1621
+ /** Always throws: seed with SQL through `wrangler d1 execute`. */
1622
+ seedDatabase(): Promise<void>;
1623
+ /** Always throws: recreate the database with wrangler instead. */
1624
+ resetDatabase(): Promise<void>;
1625
+ /** Always throws: wrangler's tracker is authoritative — use `wrangler d1 migrations list`. */
1626
+ migrationStatus(): Promise<never>;
1627
+ }
1628
+ /**
1629
+ * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
1630
+ * written for `createSqliteDatabase` port unchanged; only the connection and
1631
+ * the migration workflow differ (wrangler owns migrations, see RFC 0003).
1632
+ */
1633
+ declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1634
+
1595
1635
  interface SeederContext {
1596
1636
  db: PostgresJsDatabase;
1597
1637
  }
@@ -1614,4 +1654,4 @@ declare function serializeRecord(record: PlainObject, options: {
1614
1654
  /** Serialize an array of records. */
1615
1655
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1616
1656
 
1617
- export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1657
+ export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
package/dist/index.js CHANGED
@@ -2594,6 +2594,84 @@ function SoftDeletes(Base) {
2594
2594
  import { resolve as resolve3 } from "path";
2595
2595
  import { fileURLToPath as fileURLToPath2 } from "url";
2596
2596
 
2597
+ // src/active-connections.ts
2598
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("guren.orm.activeConnections");
2599
+ var TEARDOWN_TIMEOUT_MS = 5e3;
2600
+ function getRegistry() {
2601
+ const scope = globalThis;
2602
+ const existing = scope[REGISTRY_KEY];
2603
+ if (existing) {
2604
+ return existing;
2605
+ }
2606
+ const registry = /* @__PURE__ */ new Map();
2607
+ scope[REGISTRY_KEY] = registry;
2608
+ return registry;
2609
+ }
2610
+ function isHotReloadRuntime() {
2611
+ return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
2612
+ }
2613
+ function parseFrameLocation(frame) {
2614
+ return frame?.match(/\((.+?):\d+(?::\d+)?\)\s*$/)?.[1] ?? frame?.match(/^\s*at\s+(.+?):\d+(?::\d+)?\s*$/)?.[1];
2615
+ }
2616
+ function describeCallerFile(stack) {
2617
+ return parseFrameLocation(stack?.split("\n")[2]);
2618
+ }
2619
+ function hotReloadKey(driver, stack, target) {
2620
+ if (!isHotReloadRuntime()) {
2621
+ return void 0;
2622
+ }
2623
+ const callerFile = describeCallerFile(stack);
2624
+ if (!callerFile) {
2625
+ return void 0;
2626
+ }
2627
+ return `${driver}|${callerFile}|${target}`;
2628
+ }
2629
+ async function closeWithTimeout(teardown, timeoutMs) {
2630
+ let timer;
2631
+ try {
2632
+ await Promise.race([
2633
+ Promise.resolve(teardown()),
2634
+ new Promise((resolveTimeout) => {
2635
+ timer = setTimeout(() => {
2636
+ console.warn(
2637
+ `[guren/orm] The previous database connection did not close within ${timeoutMs}ms; continuing without it.`
2638
+ );
2639
+ resolveTimeout();
2640
+ }, timeoutMs);
2641
+ })
2642
+ ]);
2643
+ } catch (error) {
2644
+ console.warn("[guren/orm] Failed to close the previous database connection:", error);
2645
+ } finally {
2646
+ if (timer) {
2647
+ clearTimeout(timer);
2648
+ }
2649
+ }
2650
+ }
2651
+ async function replaceActiveConnection(key, teardown, timeoutMs = TEARDOWN_TIMEOUT_MS) {
2652
+ const registry = getRegistry();
2653
+ const previous = registry.get(key);
2654
+ if (previous?.teardown === teardown) {
2655
+ return;
2656
+ }
2657
+ const settled = (async () => {
2658
+ if (!previous) {
2659
+ return;
2660
+ }
2661
+ await previous.settled.catch(() => {
2662
+ });
2663
+ await closeWithTimeout(previous.teardown, timeoutMs);
2664
+ })();
2665
+ registry.set(key, { teardown, settled });
2666
+ await settled;
2667
+ }
2668
+ function releaseActiveConnection(key, teardown) {
2669
+ const registry = getRegistry();
2670
+ if (registry.get(key)?.teardown === teardown) {
2671
+ registry.delete(key);
2672
+ }
2673
+ }
2674
+
2597
2675
  // src/migration-utils.ts
2598
2676
  import { existsSync, readdirSync } from "fs";
2599
2677
  import { resolve } from "path";
@@ -2738,6 +2816,8 @@ function createPostgresDatabase(options) {
2738
2816
  let migrationsPromise;
2739
2817
  let databasePromise;
2740
2818
  let client;
2819
+ let activeKey;
2820
+ const callSite = new Error().stack;
2741
2821
  function resolveConnectionString() {
2742
2822
  const value = typeof connectionString === "function" ? connectionString() : connectionString;
2743
2823
  const resolved = value ?? process.env.DATABASE_URL;
@@ -2783,11 +2863,19 @@ function createPostgresDatabase(options) {
2783
2863
  await migrateOnce();
2784
2864
  const { drizzle, postgres: postgresFactory } = await loadPostgresModules();
2785
2865
  const url = resolveConnectionString();
2786
- client = postgresFactory(url, {
2866
+ const activeClient = postgresFactory(url, {
2787
2867
  max: 1,
2788
2868
  ...clientOptions
2789
2869
  });
2790
- return drizzle({ client, ...relations ? { relations } : {} });
2870
+ client = activeClient;
2871
+ activeKey = hotReloadKey("postgres", callSite, url);
2872
+ if (activeKey) {
2873
+ await replaceActiveConnection(activeKey, closeDatabase);
2874
+ }
2875
+ return drizzle({
2876
+ client: activeClient,
2877
+ ...relations ? { relations } : {}
2878
+ });
2791
2879
  })();
2792
2880
  databasePromise = promise.catch((error) => {
2793
2881
  databasePromise = void 0;
@@ -2799,9 +2887,17 @@ function createPostgresDatabase(options) {
2799
2887
  if (!client) {
2800
2888
  return;
2801
2889
  }
2802
- await client.end({ timeout: 0 });
2803
- client = void 0;
2804
- databasePromise = void 0;
2890
+ const key = activeKey;
2891
+ activeKey = void 0;
2892
+ try {
2893
+ await client.end({ timeout: 0 });
2894
+ } finally {
2895
+ client = void 0;
2896
+ databasePromise = void 0;
2897
+ if (key) {
2898
+ releaseActiveConnection(key, closeDatabase);
2899
+ }
2900
+ }
2805
2901
  }
2806
2902
  async function configureOrm() {
2807
2903
  const db = await getDatabase();
@@ -2885,6 +2981,8 @@ function createMySqlDatabase(options) {
2885
2981
  let migrationsPromise;
2886
2982
  let databasePromise;
2887
2983
  let database2;
2984
+ let activeKey;
2985
+ const callSite = new Error().stack;
2888
2986
  function resolveConnectionString() {
2889
2987
  const value = typeof connectionString === "function" ? connectionString() : connectionString;
2890
2988
  const resolved = value ?? process.env.DATABASE_URL;
@@ -2942,6 +3040,10 @@ function createMySqlDatabase(options) {
2942
3040
  ...relations ? { relations } : {}
2943
3041
  });
2944
3042
  database2 = db;
3043
+ activeKey = hotReloadKey("mysql", callSite, url);
3044
+ if (activeKey) {
3045
+ await replaceActiveConnection(activeKey, closeDatabase);
3046
+ }
2945
3047
  return db;
2946
3048
  })();
2947
3049
  databasePromise = promise.catch((error) => {
@@ -2954,9 +3056,17 @@ function createMySqlDatabase(options) {
2954
3056
  if (!database2) {
2955
3057
  return;
2956
3058
  }
2957
- await closeClient(database2);
2958
- database2 = void 0;
2959
- databasePromise = void 0;
3059
+ const key = activeKey;
3060
+ activeKey = void 0;
3061
+ try {
3062
+ await closeClient(database2);
3063
+ } finally {
3064
+ database2 = void 0;
3065
+ databasePromise = void 0;
3066
+ if (key) {
3067
+ releaseActiveConnection(key, closeDatabase);
3068
+ }
3069
+ }
2960
3070
  }
2961
3071
  async function configureOrm() {
2962
3072
  const db = await getDatabase();
@@ -3059,6 +3169,9 @@ function isPromiseLike2(value) {
3059
3169
  // src/sqlite.ts
3060
3170
  import { resolve as resolve5 } from "path";
3061
3171
  import { fileURLToPath as fileURLToPath4 } from "url";
3172
+ function isInMemory(dbPath) {
3173
+ return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
3174
+ }
3062
3175
  function createSqliteDatabase(options) {
3063
3176
  const { migrationsFolder, filename, seedersFolder, relations } = options;
3064
3177
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
@@ -3066,6 +3179,8 @@ function createSqliteDatabase(options) {
3066
3179
  let db;
3067
3180
  let sqliteClient;
3068
3181
  let migrationsPromise;
3182
+ let activeKey;
3183
+ const callSite = new Error().stack;
3069
3184
  function resolveFilename() {
3070
3185
  const value = typeof filename === "function" ? filename() : filename;
3071
3186
  return value ?? process.env.DATABASE_URL ?? "./data/guren.db";
@@ -3084,8 +3199,27 @@ function createSqliteDatabase(options) {
3084
3199
  sqlite.exec("PRAGMA journal_mode = WAL;");
3085
3200
  sqliteClient = sqlite;
3086
3201
  const { drizzle } = await import("drizzle-orm/bun-sqlite");
3087
- db = drizzle({ client: sqlite, ...relations ? { relations } : {} });
3088
- return db;
3202
+ const database2 = drizzle({ client: sqlite, ...relations ? { relations } : {} });
3203
+ db = database2;
3204
+ activeKey = isInMemory(dbPath) ? void 0 : hotReloadKey("sqlite", callSite, resolve5(dbPath));
3205
+ if (activeKey) {
3206
+ await replaceActiveConnection(activeKey, closeDatabase);
3207
+ }
3208
+ return database2;
3209
+ }
3210
+ async function closeDatabase() {
3211
+ if (!db) return;
3212
+ const key = activeKey;
3213
+ activeKey = void 0;
3214
+ try {
3215
+ sqliteClient?.close();
3216
+ } finally {
3217
+ db = void 0;
3218
+ sqliteClient = void 0;
3219
+ if (key) {
3220
+ releaseActiveConnection(key, closeDatabase);
3221
+ }
3222
+ }
3089
3223
  }
3090
3224
  async function migrateOnce() {
3091
3225
  if (migrationsPromise) return migrationsPromise;
@@ -3111,11 +3245,7 @@ function createSqliteDatabase(options) {
3111
3245
  return ensureDatabase2();
3112
3246
  },
3113
3247
  migrateDatabase: migrateOnce,
3114
- async closeDatabase() {
3115
- if (!db) return;
3116
- db = void 0;
3117
- sqliteClient = void 0;
3118
- },
3248
+ closeDatabase,
3119
3249
  async resetDatabase() {
3120
3250
  await ensureDatabase2();
3121
3251
  if (!sqliteClient) return;
@@ -3159,6 +3289,63 @@ function createSqliteDatabase(options) {
3159
3289
  }
3160
3290
  };
3161
3291
  }
3292
+
3293
+ // src/d1.ts
3294
+ import { relative } from "path";
3295
+ import { fileURLToPath as fileURLToPath5 } from "url";
3296
+ function createD1Database(options) {
3297
+ const { binding, migrationsFolder, relations } = options;
3298
+ const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath5(migrationsFolder)) : migrationsFolder;
3299
+ let databasePromise;
3300
+ function ensureDatabase2() {
3301
+ if (databasePromise) return databasePromise;
3302
+ const promise = (async () => {
3303
+ const client = binding();
3304
+ if (client == null) {
3305
+ throw new Error(
3306
+ '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.'
3307
+ );
3308
+ }
3309
+ const { drizzle } = await import("drizzle-orm/d1");
3310
+ return drizzle(client, relations ? { relations } : void 0);
3311
+ })();
3312
+ databasePromise = promise.catch((error) => {
3313
+ databasePromise = void 0;
3314
+ throw error;
3315
+ });
3316
+ return databasePromise;
3317
+ }
3318
+ return {
3319
+ getDatabase: ensureDatabase2,
3320
+ async migrateDatabase() {
3321
+ throw new Error(
3322
+ `D1 migrations are not applied at runtime. Run \`wrangler d1 migrations apply <database>\` (local: add --local) with d1_databases[].migrations_dir pointing at ${migrationsHint}.`
3323
+ );
3324
+ },
3325
+ async closeDatabase() {
3326
+ databasePromise = void 0;
3327
+ },
3328
+ async configureOrm() {
3329
+ const database2 = await ensureDatabase2();
3330
+ DrizzleAdapter.configure(database2);
3331
+ },
3332
+ async seedDatabase() {
3333
+ throw new Error(
3334
+ "D1 seeding runs outside the Worker: generate SQL and apply it with `wrangler d1 execute <database> --file <seed.sql>` (local: add --local)."
3335
+ );
3336
+ },
3337
+ async resetDatabase() {
3338
+ throw new Error(
3339
+ "D1 databases are reset with wrangler, not at runtime: delete and recreate the database (`wrangler d1 delete` / `wrangler d1 create`), then re-apply migrations with `wrangler d1 migrations apply`."
3340
+ );
3341
+ },
3342
+ async migrationStatus() {
3343
+ throw new Error(
3344
+ "Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead."
3345
+ );
3346
+ }
3347
+ };
3348
+ }
3162
3349
  export {
3163
3350
  DrizzleAdapter,
3164
3351
  GlobalScopeRegistry,
@@ -3170,6 +3357,7 @@ export {
3170
3357
  applyAccessors,
3171
3358
  applyMutators,
3172
3359
  buildDrizzleConditions,
3360
+ createD1Database,
3173
3361
  createMySqlDatabase,
3174
3362
  createPostgresDatabase,
3175
3363
  createSqliteDatabase,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {