@guren/orm 2.14.0 → 2.15.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.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { DestructiveMigrationError, guardPendingMigrations } from "./migration-guard.js";
1
2
  import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, max, min, ne, notInArray, or, sql } from "drizzle-orm";
2
3
  import { extname, relative, resolve } from "node:path";
3
4
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -99,6 +100,8 @@ const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
99
100
  const READ_TRANSFORMS = Symbol("guren.orm.readTransforms");
100
101
  /** Rows as the adapter read them, for the joins a relation loader makes. */
101
102
  const RAW_RESULTS = Symbol("guren.orm.rawResults");
103
+ /** A model's own relation definitions, for the serializer, which cannot import `Model`. */
104
+ const RELATION_DEFINITIONS = Symbol("guren.orm.relationDefinitions");
102
105
  /** Model-specific bulk deletion, preserving the builder's scopes. */
103
106
  const BULK_DELETE = Symbol("guren.orm.bulkDelete");
104
107
  /** Explicit physical deletion, used by SoftDeletes.forceDelete. */
@@ -246,9 +249,38 @@ async function loadRelatedRecords(related, keys, clause, queryOptions, constrain
246
249
  async function countByChunks(values, size, count) {
247
250
  return new Map(await loadByChunks(values, size, async (chunk) => Array.from(await count(chunk))));
248
251
  }
252
+ const resolvedReferences = /* @__PURE__ */ new WeakMap();
253
+ function isModelClass(reference) {
254
+ return typeof reference.newQuery === "function";
255
+ }
249
256
  async function resolveModelReference(reference) {
250
- if (typeof reference.newQuery === "function") return reference;
251
- return await reference();
257
+ if (isModelClass(reference)) return reference;
258
+ const model = await reference();
259
+ resolvedReferences.set(reference, model);
260
+ return model;
261
+ }
262
+ const morphTargets = /* @__PURE__ */ new WeakMap();
263
+ function rememberMorphTarget(row, model) {
264
+ morphTargets.set(row, model);
265
+ }
266
+ function knownMorphTarget(row) {
267
+ return row !== null && typeof row === "object" ? morphTargets.get(row) : void 0;
268
+ }
269
+ /**
270
+ * The model a reference names. A thunk no load has resolved is called: rows can
271
+ * reach the serializer without a load in this process (a cache, a job payload).
272
+ * An asynchronous one yields `undefined` this time and is remembered once it settles.
273
+ */
274
+ function knownModelReference(reference) {
275
+ if (isModelClass(reference)) return reference;
276
+ const known = resolvedReferences.get(reference);
277
+ if (known) return known;
278
+ const result = reference();
279
+ if (isModelClass(result)) {
280
+ resolvedReferences.set(reference, result);
281
+ return result;
282
+ }
283
+ result.then((model) => resolvedReferences.set(reference, model), () => void 0);
252
284
  }
253
285
  //#endregion
254
286
  //#region src/relation-loading.ts
@@ -419,6 +451,7 @@ async function loadMorphTo(morphMap, records, definition, queryOptions, constrai
419
451
  const idMap = /* @__PURE__ */ new Map();
420
452
  for (const r of results) idMap.set(r.id, { ...r });
421
453
  applyRelatedReadTransforms(modelClass, Array.from(idMap.values()), projected);
454
+ for (const row of idMap.values()) rememberMorphTarget(row, modelClass);
422
455
  resolved.set(type, idMap);
423
456
  }
424
457
  for (const record of records) {
@@ -1786,6 +1819,112 @@ function serializeRecord(record, options) {
1786
1819
  function serializeRecords(records, options) {
1787
1820
  return records.map((r) => serializeRecord(r, options));
1788
1821
  }
1822
+ /**
1823
+ * Filters the relation rows on `serialized` (a copy `serializeRecord` made of
1824
+ * `source`) by each related model's own `hidden`/`visible`, at every depth.
1825
+ * Only keys present on the rows are visited; untouched values keep their
1826
+ * references, and no input is written to.
1827
+ */
1828
+ function serializeLoadedRelations(model, source, serialized, walk) {
1829
+ const definitions = model[RELATION_DEFINITIONS]();
1830
+ if (definitions.size === 0) return serialized;
1831
+ for (const key in serialized) {
1832
+ const definition = definitions.get(key);
1833
+ if (definition === void 0) continue;
1834
+ const value = serialized[key];
1835
+ const filtered = filterRelationValue(relatedModelOf(definition, source, value, walk.morphMap), value, walk);
1836
+ if (filtered !== value) serialized[key] = filtered;
1837
+ }
1838
+ return serialized;
1839
+ }
1840
+ /**
1841
+ * The related model; an asynchronous reference no load has resolved yields
1842
+ * `undefined`. A morphTo target is the model its load
1843
+ * resolved, since the holder's casts or accessors may rewrite the type column
1844
+ * afterwards; a row no load tagged falls back to that column.
1845
+ */
1846
+ function relatedModelOf(definition, holder, value, morphMap) {
1847
+ if (definition.type !== "morphTo") return knownModelReference(definition.related);
1848
+ const loaded = knownMorphTarget(value);
1849
+ if (loaded) return loaded;
1850
+ const type = holder[`${definition.morphName}Type`];
1851
+ return typeof type === "string" && morphMap && Object.hasOwn(morphMap, type) ? morphMap[type] : void 0;
1852
+ }
1853
+ function hasColumnFilter(model) {
1854
+ return (model.visible?.length ?? 0) > 0 || (model.hidden?.length ?? 0) > 0;
1855
+ }
1856
+ function isRow(value) {
1857
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1858
+ }
1859
+ function holdsRelation(definitions, row) {
1860
+ for (const key in row) if (definitions.has(key)) return true;
1861
+ return false;
1862
+ }
1863
+ function filterRelationValue(model, value, walk) {
1864
+ if (!model || value === null || typeof value !== "object") return value;
1865
+ const definitions = model[RELATION_DEFINITIONS]();
1866
+ const filtered = hasColumnFilter(model);
1867
+ if (!filtered && definitions.size === 0) return value;
1868
+ if (!Array.isArray(value)) return isRow(value) ? filterRow(model, definitions, filtered, value, walk) : value;
1869
+ let copy;
1870
+ for (let i = 0; i < value.length; i++) {
1871
+ const item = value[i];
1872
+ const next = isRow(item) ? filterRow(model, definitions, filtered, item, walk) : item;
1873
+ if (copy) copy.push(next);
1874
+ else if (next !== item) {
1875
+ copy = value.slice(0, i);
1876
+ copy.push(next);
1877
+ }
1878
+ }
1879
+ return copy ?? value;
1880
+ }
1881
+ function filterRow(model, definitions, filtered, row, walk) {
1882
+ if (!filtered && !holdsRelation(definitions, row)) return row;
1883
+ walk.memo ??= /* @__PURE__ */ new Map();
1884
+ let rows = walk.memo.get(model);
1885
+ if (!rows) {
1886
+ rows = /* @__PURE__ */ new Map();
1887
+ walk.memo.set(model, rows);
1888
+ }
1889
+ const seen = rows.get(row);
1890
+ if (seen) {
1891
+ if (!seen.done && seen.output === row) seen.output = { ...row };
1892
+ return seen.output;
1893
+ }
1894
+ const entry = {
1895
+ output: filtered ? filterColumns(model, row) : row,
1896
+ done: false
1897
+ };
1898
+ rows.set(row, entry);
1899
+ for (const key in entry.output) {
1900
+ const definition = definitions.get(key);
1901
+ if (definition === void 0) continue;
1902
+ const value = row[key];
1903
+ const next = filterRelationValue(relatedModelOf(definition, row, value, walk.morphMap), value, walk);
1904
+ if (next === value) continue;
1905
+ if (entry.output === row) entry.output = { ...row };
1906
+ entry.output[key] = next;
1907
+ }
1908
+ entry.done = true;
1909
+ return entry.output;
1910
+ }
1911
+ /**
1912
+ * A related row's own columns, by the rule `serializeRecord` applies to the
1913
+ * serialized record: `visible` keeps only the keys it names (relations
1914
+ * included), in loaded order; otherwise `hidden` keys go. Appends are not computed.
1915
+ */
1916
+ function filterColumns(model, row) {
1917
+ const hidden = model.hidden;
1918
+ const visible = model.visible;
1919
+ const kept = {};
1920
+ if (visible && visible.length > 0) {
1921
+ for (const key in row) if (visible.includes(key)) kept[key] = row[key];
1922
+ return kept;
1923
+ }
1924
+ if (!hidden?.some((key) => key in row)) return row;
1925
+ for (const key in row) if (!hidden.includes(key)) kept[key] = row[key];
1926
+ return kept;
1927
+ }
1789
1928
  //#endregion
1790
1929
  //#region src/MassAssignmentException.ts
1791
1930
  /**
@@ -1972,22 +2111,32 @@ var Model = class Model {
1972
2111
  if (!everyFilterDropped(where)) return;
1973
2112
  throw new Error(`${this.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
1974
2113
  }
1975
- /** Applies hidden/visible filtering, accessors and appends. */
2114
+ /**
2115
+ * Applies hidden/visible filtering, accessors and appends, then each loaded
2116
+ * relation's own model's hidden/visible to its rows, nested ones included.
2117
+ */
1976
2118
  static serialize(record) {
1977
- return serializeRecord(record, {
2119
+ const serialized = serializeRecord(record, {
1978
2120
  hidden: this.hidden,
1979
2121
  visible: this.visible,
1980
2122
  appends: this.appends,
1981
2123
  accessors: this.accessors
1982
2124
  });
2125
+ return serializeLoadedRelations(this, record, serialized, { morphMap: Model.morphMap });
1983
2126
  }
1984
2127
  static serializeMany(records) {
1985
- return serializeRecords(records, {
2128
+ const options = {
1986
2129
  hidden: this.hidden,
1987
2130
  visible: this.visible,
1988
2131
  appends: this.appends,
1989
2132
  accessors: this.accessors
1990
- });
2133
+ };
2134
+ const walk = { morphMap: Model.morphMap };
2135
+ return records.map((record) => serializeLoadedRelations(this, record, serializeRecord(record, options), walk));
2136
+ }
2137
+ /** @internal The serializer's view of the relations, symbol-keyed like `[READ_TRANSFORMS]`. */
2138
+ static [RELATION_DEFINITIONS]() {
2139
+ return this.getRelationDefinitions();
1991
2140
  }
1992
2141
  static applyCasts(record) {
1993
2142
  const castDefs = this.casts;
@@ -2122,21 +2271,28 @@ var Model = class Model {
2122
2271
  return record;
2123
2272
  }
2124
2273
  static async findWith(id, relations, key, queryOptions) {
2125
- const record = await this.find(id, key, queryOptions);
2126
- if (record == null) return null;
2127
2274
  const relationList = normalizeRelations(relations);
2128
- if (relationList.length === 0) return record;
2275
+ return relationList.length === 0 ? await this.find(id, key, queryOptions) : await this.findRawWith(id, relationList, key, queryOptions);
2276
+ }
2277
+ /**
2278
+ * `find()` with its relations loaded ahead of the read transforms: a loader
2279
+ * matches rows on raw key values, which a cast or an accessor on this model
2280
+ * would have rewritten.
2281
+ */
2282
+ static async findRawWith(id, relationList, key = "id", queryOptions) {
2283
+ if (id === void 0) return null;
2284
+ const where = { [key]: id };
2285
+ if (this.hasScopes()) return this.newQuery(queryOptions).where(where).with(...relationList).first();
2286
+ const record = await this.getAdapter().findUnique(this.resolveTable(), where, queryOptions);
2287
+ if (record == null) return null;
2129
2288
  const copy = { ...record };
2130
2289
  await this.loadRelationsInto([copy], relationList, queryOptions);
2131
- return copy;
2290
+ return this.applyReadTransforms(copy);
2132
2291
  }
2133
2292
  static async findWithOrFail(id, relations, key, queryOptions) {
2134
- const record = await this.findOrFail(id, key, queryOptions);
2135
- const relationList = normalizeRelations(relations);
2136
- if (relationList.length === 0) return record;
2137
- const copy = { ...record };
2138
- await this.loadRelationsInto([copy], relationList, queryOptions);
2139
- return copy;
2293
+ const record = await this.findWith(id, relations, key, queryOptions);
2294
+ if (record == null) throw new ModelNotFoundException(this.name, id, key ?? "id");
2295
+ return record;
2140
2296
  }
2141
2297
  static async first(where, queryOptions) {
2142
2298
  if (everyFilterDropped(where)) return null;
@@ -2974,7 +3130,10 @@ function describeConnectionEndpoint(connectionString) {
2974
3130
  /** drizzle-kit migrations, sorted the way the drizzle migrator applies them. */
2975
3131
  function listLocalMigrations(migrationsFolder) {
2976
3132
  if (!existsSync(migrationsFolder)) return [];
2977
- 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));
3133
+ return readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))).map((entry) => ({
3134
+ name: entry.name,
3135
+ path: resolve(migrationsFolder, entry.name, "migration.sql")
3136
+ })).sort((a, b) => a.name.localeCompare(b.name));
2978
3137
  }
2979
3138
  function parseAppliedAt(row) {
2980
3139
  if (!row?.appliedAt) return null;
@@ -2996,7 +3155,8 @@ function buildMigrationStatus(localMigrations, appliedRows) {
2996
3155
  return {
2997
3156
  name: migration.name,
2998
3157
  applied: row !== void 0,
2999
- appliedAt: parseAppliedAt(row)
3158
+ appliedAt: parseAppliedAt(row),
3159
+ path: migration.path
3000
3160
  };
3001
3161
  });
3002
3162
  if (unmatchedRows.size === 0) return entries;
@@ -3018,12 +3178,15 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3018
3178
  const status = buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied());
3019
3179
  return {
3020
3180
  pending: status.filter((entry) => !entry.applied).map((entry) => entry.name),
3021
- orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name)
3181
+ orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name),
3182
+ readable: true
3022
3183
  };
3023
- } catch {
3184
+ } catch (error) {
3024
3185
  return {
3025
3186
  pending: [],
3026
- orphaned: []
3187
+ orphaned: [],
3188
+ readable: false,
3189
+ error
3027
3190
  };
3028
3191
  }
3029
3192
  }
@@ -3033,12 +3196,22 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3033
3196
  * before it runs, since they are the likeliest reason it is about to fail.
3034
3197
  * Without `readApplied` nothing is read or reported: a reset's re-apply.
3035
3198
  */
3036
- async function migrateAndReport(migrationsFolder, { readApplied, migrate }) {
3199
+ async function migrateAndReport(migrationsFolder, { readApplied, migrate, destructiveMigrations = "warn", dialect, foreignKeysEnforced }) {
3037
3200
  const drift = readApplied ? await readMigrationDrift(migrationsFolder, readApplied) : {
3038
3201
  pending: [],
3039
- orphaned: []
3202
+ orphaned: [],
3203
+ readable: true
3040
3204
  };
3041
3205
  reportOrphanedMigrations(drift.orphaned, migrationsFolder);
3206
+ if (readApplied) {
3207
+ const pending = drift.readable ? drift.pending : listLocalMigrations(migrationsFolder).map((entry) => entry.name);
3208
+ guardPendingMigrations(migrationsFolder, pending, destructiveMigrations, {
3209
+ pendingKnown: drift.readable,
3210
+ trackerError: drift.error,
3211
+ dialect,
3212
+ foreignKeysEnforced
3213
+ });
3214
+ }
3042
3215
  await migrate();
3043
3216
  reportAppliedMigrations(drift.pending, migrationsFolder);
3044
3217
  }
@@ -3176,6 +3349,10 @@ function singleFlight(factory) {
3176
3349
  }
3177
3350
  //#endregion
3178
3351
  //#region src/connection-context.ts
3352
+ /** A resolver's value for `context`, without touching a factory's kept context or its staleness record. */
3353
+ function resolveFor(value, context) {
3354
+ return typeof value === "function" ? value(context) : value;
3355
+ }
3179
3356
  /**
3180
3357
  * One per factory. The context is kept rather than passed, because resolutions
3181
3358
  * also run inside memoized flights and admin clients that no `configureOrm()`
@@ -3201,6 +3378,151 @@ function connectionSettings() {
3201
3378
  };
3202
3379
  }
3203
3380
  //#endregion
3381
+ //#region src/database-description.ts
3382
+ const REDACTED = "[REDACTED]";
3383
+ /**
3384
+ * Client option and connection-string query keys that cannot move the endpoint off the URL's
3385
+ * host. Anything else (`host`, mysql2's `uri`, a `stream` or `socket` factory, a key a later
3386
+ * driver adds) reads as `unknown`: an allowlist, so a new option fails closed.
3387
+ */
3388
+ const ENDPOINT_NEUTRAL_KEYS = {
3389
+ postgres: /* @__PURE__ */ new Set([
3390
+ "max",
3391
+ "idle_timeout",
3392
+ "connect_timeout",
3393
+ "max_lifetime",
3394
+ "backoff",
3395
+ "keep_alive",
3396
+ "ssl",
3397
+ "sslmode",
3398
+ "prepare",
3399
+ "types",
3400
+ "transform",
3401
+ "onnotice",
3402
+ "onparameter",
3403
+ "onclose",
3404
+ "debug",
3405
+ "fetch_types",
3406
+ "connection",
3407
+ "publications",
3408
+ "user",
3409
+ "username",
3410
+ "pass",
3411
+ "password",
3412
+ "database",
3413
+ "db",
3414
+ "port",
3415
+ "application_name",
3416
+ "options",
3417
+ "search_path"
3418
+ ]),
3419
+ mysql: /* @__PURE__ */ new Set([
3420
+ "waitForConnections",
3421
+ "connectionLimit",
3422
+ "maxIdle",
3423
+ "idleTimeout",
3424
+ "queueLimit",
3425
+ "enableKeepAlive",
3426
+ "keepAliveInitialDelay",
3427
+ "ssl",
3428
+ "timezone",
3429
+ "charset",
3430
+ "typeCast",
3431
+ "connectTimeout",
3432
+ "user",
3433
+ "password",
3434
+ "database",
3435
+ "port",
3436
+ "dateStrings",
3437
+ "decimalNumbers",
3438
+ "supportBigNumbers",
3439
+ "bigNumberStrings",
3440
+ "jsonStrings",
3441
+ "multipleStatements",
3442
+ "namedPlaceholders",
3443
+ "rowsAsArray",
3444
+ "nestTables",
3445
+ "compress",
3446
+ "debug",
3447
+ "trace"
3448
+ ])
3449
+ };
3450
+ /** The loopback rule of `isLoopbackOrigin()` in @guren/server's loopback-guard.ts, over a WHATWG hostname. */
3451
+ function isLoopbackHost(hostname) {
3452
+ return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(hostname);
3453
+ }
3454
+ /** A server database's location from its connection string and the client options laid over it. */
3455
+ function describeServerDatabase(dialect, connectionString, clientOptions) {
3456
+ if (connectionString === void 0) return {
3457
+ dialect,
3458
+ location: "unknown",
3459
+ reason: "No connection string resolves."
3460
+ };
3461
+ if (connectionString.includes(REDACTED)) return {
3462
+ dialect,
3463
+ location: "unknown",
3464
+ reason: "The connection string is the placeholder the env reader writes for a missing or invalid value."
3465
+ };
3466
+ const neutral = ENDPOINT_NEUTRAL_KEYS[dialect];
3467
+ const option = Object.keys(clientOptions ?? {}).find((key) => !neutral.has(key));
3468
+ if (option) return {
3469
+ dialect,
3470
+ location: "unknown",
3471
+ reason: `The client options set \`${option}\`, which may choose the endpoint.`
3472
+ };
3473
+ let url;
3474
+ try {
3475
+ url = new URL(connectionString);
3476
+ } catch {
3477
+ return {
3478
+ dialect,
3479
+ location: "unknown",
3480
+ reason: "The connection string is not a URL."
3481
+ };
3482
+ }
3483
+ const query = [...url.searchParams.keys()].find((key) => dialect === "mysql" ? !neutral.has(key) : key === "host" || key === "hostaddr");
3484
+ if (query) return {
3485
+ dialect,
3486
+ location: "unknown",
3487
+ reason: `The connection string's query sets \`${query}\`, which may choose the endpoint.`
3488
+ };
3489
+ const hostname = url.hostname.toLowerCase();
3490
+ if (hostname === "") return {
3491
+ dialect,
3492
+ location: "unknown",
3493
+ reason: "The connection string names no host."
3494
+ };
3495
+ return isLoopbackHost(hostname) ? {
3496
+ dialect,
3497
+ location: "local"
3498
+ } : {
3499
+ dialect,
3500
+ location: "remote",
3501
+ reason: `The database host ${hostname} is not a loopback address.`
3502
+ };
3503
+ }
3504
+ function describeSqliteDatabase(filename) {
3505
+ let value;
3506
+ try {
3507
+ value = filename();
3508
+ } catch {
3509
+ return {
3510
+ dialect: "sqlite",
3511
+ location: "unknown",
3512
+ reason: "The database setting is not a file path the SQLite driver accepts, such as a connection URI."
3513
+ };
3514
+ }
3515
+ if (value.includes(REDACTED)) return {
3516
+ dialect: "sqlite",
3517
+ location: "unknown",
3518
+ reason: "The database file is the placeholder the env reader writes for a missing or invalid value."
3519
+ };
3520
+ return {
3521
+ dialect: "sqlite",
3522
+ location: "local"
3523
+ };
3524
+ }
3525
+ //#endregion
3204
3526
  //#region src/postgres.ts
3205
3527
  async function loadPostgresModules() {
3206
3528
  try {
@@ -3220,15 +3542,19 @@ async function loadPostgresModules() {
3220
3542
  }
3221
3543
  }
3222
3544
  function createPostgresDatabase(options) {
3223
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3545
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3224
3546
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3225
3547
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3226
3548
  let client;
3227
3549
  let activeKey;
3228
3550
  const callSite = (/* @__PURE__ */ new Error()).stack;
3229
3551
  const settings = connectionSettings();
3552
+ /** The one fallback rule, so what `describe()` judges is what a connection opens. */
3553
+ function connectionStringFrom(value) {
3554
+ return (value ?? process.env.DATABASE_URL) || void 0;
3555
+ }
3230
3556
  function resolveConnectionString() {
3231
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3557
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3232
3558
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3233
3559
  return resolved;
3234
3560
  }
@@ -3269,6 +3595,8 @@ function createPostgresDatabase(options) {
3269
3595
  ...relations ? { relations } : {}
3270
3596
  });
3271
3597
  await migrateAndReport(resolvedMigrationsFolder, {
3598
+ destructiveMigrations,
3599
+ dialect: "postgres",
3272
3600
  readApplied: report ? () => readAppliedMigrations(migrationClient) : void 0,
3273
3601
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3274
3602
  });
@@ -3366,7 +3694,10 @@ function createPostgresDatabase(options) {
3366
3694
  seedDatabase,
3367
3695
  resetDatabase,
3368
3696
  migrationStatus,
3369
- hasMigrations
3697
+ hasMigrations,
3698
+ describe(context) {
3699
+ return describeServerDatabase("postgres", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3700
+ }
3370
3701
  };
3371
3702
  }
3372
3703
  //#endregion
@@ -3389,15 +3720,19 @@ async function loadMySqlModules() {
3389
3720
  }
3390
3721
  }
3391
3722
  function createMySqlDatabase(options) {
3392
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3723
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3393
3724
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3394
3725
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3395
3726
  let client;
3396
3727
  let activeKey;
3397
3728
  const callSite = (/* @__PURE__ */ new Error()).stack;
3398
3729
  const settings = connectionSettings();
3730
+ /** The one fallback rule, so what `describe()` judges is what a connection opens. */
3731
+ function connectionStringFrom(value) {
3732
+ return (value ?? process.env.DATABASE_URL) || void 0;
3733
+ }
3399
3734
  function resolveConnectionString() {
3400
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3735
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3401
3736
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3402
3737
  return resolved;
3403
3738
  }
@@ -3440,6 +3775,8 @@ function createMySqlDatabase(options) {
3440
3775
  ...relations ? { relations } : {}
3441
3776
  });
3442
3777
  await migrateAndReport(resolvedMigrationsFolder, {
3778
+ destructiveMigrations,
3779
+ dialect: "mysql",
3443
3780
  readApplied: report ? () => readAppliedMigrations(migrationDb) : void 0,
3444
3781
  migrate: () => migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder })
3445
3782
  });
@@ -3546,7 +3883,10 @@ function createMySqlDatabase(options) {
3546
3883
  seedDatabase,
3547
3884
  resetDatabase,
3548
3885
  migrationStatus,
3549
- hasMigrations
3886
+ hasMigrations,
3887
+ describe(context) {
3888
+ return describeServerDatabase("mysql", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3889
+ }
3550
3890
  };
3551
3891
  }
3552
3892
  async function closePool(pool) {
@@ -3628,7 +3968,7 @@ function reportForeignKeyViolations(handle) {
3628
3968
  console.warn(`[guren/orm] The migrations just applied left ${rows.length} row(s) whose foreign key names no parent row: ${summary}.\n[guren/orm] Foreign keys are not enforced while migrations run. \`PRAGMA foreign_key_check\` lists the rows.`);
3629
3969
  }
3630
3970
  function createSqliteDatabase(options) {
3631
- const { migrationsFolder, filename, seedersFolder, relations } = options;
3971
+ const { migrationsFolder, destructiveMigrations, filename, seedersFolder, relations } = options;
3632
3972
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3633
3973
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3634
3974
  let sqliteClient;
@@ -3636,7 +3976,9 @@ function createSqliteDatabase(options) {
3636
3976
  const callSite = (/* @__PURE__ */ new Error()).stack;
3637
3977
  const settings = connectionSettings();
3638
3978
  function resolveFilename() {
3639
- const value = settings.resolve(filename);
3979
+ return filenameFrom(settings.resolve(filename));
3980
+ }
3981
+ function filenameFrom(value) {
3640
3982
  if (value != null) {
3641
3983
  assertNotConnectionUri(value, "the \"filename\" option");
3642
3984
  return value;
@@ -3707,6 +4049,9 @@ function createSqliteDatabase(options) {
3707
4049
  const db = await database.get();
3708
4050
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
3709
4051
  await migrateAndReport(resolvedMigrationsFolder, {
4052
+ destructiveMigrations,
4053
+ dialect: "sqlite",
4054
+ foreignKeysEnforced: false,
3710
4055
  readApplied: report ? readAppliedMigrations : void 0,
3711
4056
  migrate: () => {
3712
4057
  const handle = db;
@@ -3752,6 +4097,9 @@ function createSqliteDatabase(options) {
3752
4097
  hasMigrations() {
3753
4098
  return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3754
4099
  },
4100
+ describe(context) {
4101
+ return describeSqliteDatabase(() => filenameFrom(resolveFor(filename, context)));
4102
+ },
3755
4103
  async migrationStatus() {
3756
4104
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3757
4105
  if (localMigrations.length === 0) return [];
@@ -3780,6 +4128,16 @@ function createSqliteDatabase(options) {
3780
4128
  }
3781
4129
  //#endregion
3782
4130
  //#region src/d1.ts
4131
+ /** `WORKERS_ENV_SLOT` in `@guren/plugin-cloudflare/env`, which captures the env; the ORM cannot import it. */
4132
+ const WORKERS_ENV_SLOT = Symbol.for("guren.workersEnv");
4133
+ /** Mirrors `readWorkersBinding()` in `@guren/plugin-cloudflare/env`. */
4134
+ function workersBinding(name) {
4135
+ const holder = globalThis[WORKERS_ENV_SLOT];
4136
+ if (!holder) throw new Error(`createD1Database: the "${name}" binding was read before the first request captured the Workers env. Use it inside a request.`);
4137
+ const value = holder.env?.[name];
4138
+ if (value == null) throw new Error(`createD1Database: the Workers env has no "${name}" binding. Check wrangler.jsonc, or the binding in cloudflare.config.ts.`);
4139
+ return value;
4140
+ }
3783
4141
  /**
3784
4142
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
3785
4143
  * written for `createSqliteDatabase` port unchanged; wrangler owns migrations
@@ -3788,9 +4146,15 @@ function createSqliteDatabase(options) {
3788
4146
  function createD1Database(options) {
3789
4147
  const { binding, migrationsFolder, relations } = options;
3790
4148
  const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath(migrationsFolder)) : migrationsFolder;
3791
- const databaseHandle = singleFlight(async () => {
4149
+ if (binding === "") throw new Error("createD1Database: `binding` names no binding; pass its name, such as 'DB'.");
4150
+ const bindingName = typeof binding === "string" ? binding : void 0;
4151
+ const resolveBinding = typeof binding === "string" ? () => workersBinding(binding) : () => {
3792
4152
  const client = binding();
3793
- if (client == null) throw new Error("createD1Database: the \"binding\" resolver returned no D1 binding. On Workers this usually means it ran before the first request — defer access (e.g. binding: () => getWorkersEnv<Env>().DB) and check the d1_databases entry in wrangler.jsonc.");
4153
+ if (client == null) throw new Error("createD1Database: the \"binding\" resolver returned no D1 binding. On Workers this usually means it ran before the first request — defer access (e.g. binding: () => getWorkersEnv<Env>().DB, or name it: binding: 'DB') and check the d1_databases entry in wrangler.jsonc.");
4154
+ return client;
4155
+ };
4156
+ const databaseHandle = singleFlight(async () => {
4157
+ const client = resolveBinding();
3794
4158
  const { drizzle } = await import("drizzle-orm/d1");
3795
4159
  return drizzle(client, relations ? { relations } : void 0);
3796
4160
  });
@@ -3815,8 +4179,16 @@ function createD1Database(options) {
3815
4179
  hasMigrations() {
3816
4180
  return false;
3817
4181
  },
4182
+ describe() {
4183
+ return {
4184
+ dialect: "d1",
4185
+ location: "unknown",
4186
+ reason: "A D1 binding is resolved per request, inside the Workers runtime.",
4187
+ ...bindingName ? { binding: bindingName } : {}
4188
+ };
4189
+ },
3818
4190
  async migrationStatus() {
3819
- throw new Error("Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead.");
4191
+ throw new Error("Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead, and `wrangler d1 migrations apply <database>` to apply them once `guren check` reports no unacknowledged destructive migration.");
3820
4192
  }
3821
4193
  };
3822
4194
  }
@@ -3835,7 +4207,7 @@ async function loadAwsDataApiModules() {
3835
4207
  }
3836
4208
  }
3837
4209
  function createAwsDataApiDatabase(options) {
3838
- const { migrationsFolder, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
4210
+ const { migrationsFolder, destructiveMigrations, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
3839
4211
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3840
4212
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3841
4213
  let client;
@@ -3880,6 +4252,8 @@ function createAwsDataApiDatabase(options) {
3880
4252
  const { migrate } = await loadAwsDataApiModules();
3881
4253
  await withAdminDb(async (db) => {
3882
4254
  await migrateAndReport(resolvedMigrationsFolder, {
4255
+ destructiveMigrations,
4256
+ dialect: "postgres",
3883
4257
  readApplied: report ? () => readAppliedMigrations(db) : void 0,
3884
4258
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3885
4259
  });
@@ -3986,4 +4360,4 @@ function isMissingTrackerTableError(error) {
3986
4360
  return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
3987
4361
  }
3988
4362
  //#endregion
3989
- export { DrizzleAdapter, GlobalScopeRegistry, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
4363
+ export { DestructiveMigrationError, DrizzleAdapter, GlobalScopeRegistry, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };