@guren/orm 2.14.0 → 2.15.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
@@ -1,3 +1,4 @@
1
+ import { DestructiveMigrationError, DestructiveMigrationMode } from "./migration-guard.js";
1
2
  import { SQL } from "drizzle-orm";
2
3
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
4
  import postgres from "postgres";
@@ -1104,6 +1105,21 @@ interface ConnectionContext {
1104
1105
  */
1105
1106
  type ConnectionResolver = string | ((context?: ConnectionContext) => string | undefined);
1106
1107
  //#endregion
1108
+ //#region src/database-description.d.ts
1109
+ /**
1110
+ * Where a factory's database lives, judged without connecting (RFC 0033 §3): what lets
1111
+ * `guren browser:serve` refuse to boot an app against a database it cannot show is local.
1112
+ * Anything not positively local is `remote` or `unknown`, never `local`. The connection
1113
+ * string itself is never part of the result, since it can carry a password.
1114
+ */
1115
+ interface DatabaseDescription {
1116
+ dialect: 'postgres' | 'mysql' | 'sqlite' | 'd1';
1117
+ location: 'local' | 'remote' | 'unknown';
1118
+ reason?: string;
1119
+ /** The Workers binding a D1 factory names as a string; a closure is opaque, so it has none (RFC 0035 §2.1). */
1120
+ binding?: string;
1121
+ }
1122
+ //#endregion
1107
1123
  //#region src/migration-utils.d.ts
1108
1124
  /**
1109
1125
  * What one `migrateDatabase()` call had to work with. `db:migrate` reports
@@ -1133,6 +1149,8 @@ interface MigrationStatusEntry {
1133
1149
  * then deleted from disk (or migrated by another checkout). Absent otherwise.
1134
1150
  */
1135
1151
  orphaned?: boolean;
1152
+ /** The absolute `migration.sql` for a local migration; absent on an orphaned row. */
1153
+ path?: string;
1136
1154
  }
1137
1155
  //#endregion
1138
1156
  //#region src/seeder.d.ts
@@ -1182,6 +1200,12 @@ declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHan
1182
1200
  //#region src/postgres.d.ts
1183
1201
  interface PostgresDatabaseOptions {
1184
1202
  migrationsFolder: string | URL;
1203
+ /**
1204
+ * What a boot or `migrateDatabase()` does with a pending migration that drops,
1205
+ * narrows or renames without a `-- guren:allow-destructive` comment (RFC 0034):
1206
+ * `'warn'` (the v2 default) prints it and applies; `'refuse'` throws first.
1207
+ */
1208
+ destructiveMigrations?: DestructiveMigrationMode;
1185
1209
  connectionString?: ConnectionResolver;
1186
1210
  clientOptions?: postgres.Options<Record<string, never>>;
1187
1211
  seedersFolder?: string | URL;
@@ -1207,6 +1231,8 @@ interface PostgresDatabase {
1207
1231
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1208
1232
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1209
1233
  hasMigrations(): boolean;
1234
+ /** Where the database lives for `context`, without connecting (RFC 0033 §3); never carries the connection string. */
1235
+ describe(context?: ConnectionContext): DatabaseDescription;
1210
1236
  }
1211
1237
  declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
1212
1238
  //#endregion
@@ -1214,6 +1240,12 @@ declare function createPostgresDatabase(options: PostgresDatabaseOptions): Postg
1214
1240
  type MySqlConnectionOptions = Record<string, unknown>;
1215
1241
  interface MySqlDatabaseOptions {
1216
1242
  migrationsFolder: string | URL;
1243
+ /**
1244
+ * What a boot or `migrateDatabase()` does with a pending migration that drops,
1245
+ * narrows or renames without a `-- guren:allow-destructive` comment (RFC 0034):
1246
+ * `'warn'` (the v2 default) prints it and applies; `'refuse'` throws first.
1247
+ */
1248
+ destructiveMigrations?: DestructiveMigrationMode;
1217
1249
  connectionString?: ConnectionResolver;
1218
1250
  clientOptions?: MySqlConnectionOptions;
1219
1251
  seedersFolder?: string | URL;
@@ -1239,12 +1271,20 @@ interface MySqlDatabase {
1239
1271
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1240
1272
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1241
1273
  hasMigrations(): boolean;
1274
+ /** Where the database lives for `context`, without connecting (RFC 0033 §3); never carries the connection string. */
1275
+ describe(context?: ConnectionContext): DatabaseDescription;
1242
1276
  }
1243
1277
  declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
1244
1278
  //#endregion
1245
1279
  //#region src/sqlite.d.ts
1246
1280
  interface SqliteDatabaseOptions {
1247
1281
  migrationsFolder: string | URL;
1282
+ /**
1283
+ * What a boot or `migrateDatabase()` does with a pending migration that drops,
1284
+ * narrows or renames without a `-- guren:allow-destructive` comment (RFC 0034):
1285
+ * `'warn'` (the v2 default) prints it and applies; `'refuse'` throws first.
1286
+ */
1287
+ destructiveMigrations?: DestructiveMigrationMode;
1248
1288
  /** Path to the SQLite database file. Defaults to `./data/guren.db`. */
1249
1289
  filename?: ConnectionResolver;
1250
1290
  seedersFolder?: string | URL;
@@ -1274,17 +1314,19 @@ interface SqliteDatabase {
1274
1314
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1275
1315
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1276
1316
  hasMigrations(): boolean;
1317
+ /** Where the database lives for `context`, without connecting (RFC 0033 §3); never carries the connection string. */
1318
+ describe(context?: ConnectionContext): DatabaseDescription;
1277
1319
  }
1278
1320
  declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
1279
1321
  //#endregion
1280
1322
  //#region src/d1.d.ts
1281
1323
  interface D1DatabaseOptions {
1282
1324
  /**
1283
- * Resolver returning the Cloudflare D1 binding. Bindings arrive with the
1284
- * first request on Workers, so this must be a deferred closure, e.g.
1285
- * `binding: () => getWorkersEnv<Env>().DB`.
1325
+ * The Cloudflare D1 binding: its name (`'DB'`), read from the Workers env the first
1326
+ * request captured, or a deferred closure such as `() => getWorkersEnv<Env>().DB`.
1327
+ * The name is what `describe()` reports, so the deploy can tell which binding it is.
1286
1328
  */
1287
- binding: () => unknown;
1329
+ binding: string | (() => unknown);
1288
1330
  /**
1289
1331
  * Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
1290
1332
  * `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` here);
@@ -1312,6 +1354,8 @@ interface D1DatabaseHandle {
1312
1354
  migrationStatus(): Promise<never>;
1313
1355
  /** Always false: wrangler applies D1 migrations and the factory never seeds, so nothing at boot acts on them. */
1314
1356
  hasMigrations(): boolean;
1357
+ /** Always `unknown`; see its `reason`. */
1358
+ describe(): DatabaseDescription;
1315
1359
  }
1316
1360
  /**
1317
1361
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
@@ -1324,6 +1368,12 @@ declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1324
1368
  type AwsDataApiPgDatabase$1 = import('drizzle-orm/aws-data-api/pg').AwsDataApiPgDatabase;
1325
1369
  interface AwsDataApiDatabaseOptions {
1326
1370
  migrationsFolder: string | URL;
1371
+ /**
1372
+ * What a boot or `migrateDatabase()` does with a pending migration that drops,
1373
+ * narrows or renames without a `-- guren:allow-destructive` comment (RFC 0034):
1374
+ * `'warn'` (the v2 default) prints it and applies; `'refuse'` throws first.
1375
+ */
1376
+ destructiveMigrations?: DestructiveMigrationMode;
1327
1377
  /** Database name. Falls back to the DATABASE_NAME environment variable. */
1328
1378
  database?: ConnectionResolver;
1329
1379
  /** Aurora cluster ARN. Falls back to the DATABASE_RESOURCE_ARN environment variable. */
@@ -1376,4 +1426,4 @@ declare function serializeRecord(record: PlainObject, options: {
1376
1426
  /** Serialize an array of records. */
1377
1427
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1378
1428
  //#endregion
1379
- export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, 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 MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1429
+ export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, 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 MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
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";
@@ -2974,7 +2975,10 @@ function describeConnectionEndpoint(connectionString) {
2974
2975
  /** drizzle-kit migrations, sorted the way the drizzle migrator applies them. */
2975
2976
  function listLocalMigrations(migrationsFolder) {
2976
2977
  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));
2978
+ return readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))).map((entry) => ({
2979
+ name: entry.name,
2980
+ path: resolve(migrationsFolder, entry.name, "migration.sql")
2981
+ })).sort((a, b) => a.name.localeCompare(b.name));
2978
2982
  }
2979
2983
  function parseAppliedAt(row) {
2980
2984
  if (!row?.appliedAt) return null;
@@ -2996,7 +3000,8 @@ function buildMigrationStatus(localMigrations, appliedRows) {
2996
3000
  return {
2997
3001
  name: migration.name,
2998
3002
  applied: row !== void 0,
2999
- appliedAt: parseAppliedAt(row)
3003
+ appliedAt: parseAppliedAt(row),
3004
+ path: migration.path
3000
3005
  };
3001
3006
  });
3002
3007
  if (unmatchedRows.size === 0) return entries;
@@ -3018,12 +3023,15 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3018
3023
  const status = buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied());
3019
3024
  return {
3020
3025
  pending: status.filter((entry) => !entry.applied).map((entry) => entry.name),
3021
- orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name)
3026
+ orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name),
3027
+ readable: true
3022
3028
  };
3023
- } catch {
3029
+ } catch (error) {
3024
3030
  return {
3025
3031
  pending: [],
3026
- orphaned: []
3032
+ orphaned: [],
3033
+ readable: false,
3034
+ error
3027
3035
  };
3028
3036
  }
3029
3037
  }
@@ -3033,12 +3041,22 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3033
3041
  * before it runs, since they are the likeliest reason it is about to fail.
3034
3042
  * Without `readApplied` nothing is read or reported: a reset's re-apply.
3035
3043
  */
3036
- async function migrateAndReport(migrationsFolder, { readApplied, migrate }) {
3044
+ async function migrateAndReport(migrationsFolder, { readApplied, migrate, destructiveMigrations = "warn", dialect, foreignKeysEnforced }) {
3037
3045
  const drift = readApplied ? await readMigrationDrift(migrationsFolder, readApplied) : {
3038
3046
  pending: [],
3039
- orphaned: []
3047
+ orphaned: [],
3048
+ readable: true
3040
3049
  };
3041
3050
  reportOrphanedMigrations(drift.orphaned, migrationsFolder);
3051
+ if (readApplied) {
3052
+ const pending = drift.readable ? drift.pending : listLocalMigrations(migrationsFolder).map((entry) => entry.name);
3053
+ guardPendingMigrations(migrationsFolder, pending, destructiveMigrations, {
3054
+ pendingKnown: drift.readable,
3055
+ trackerError: drift.error,
3056
+ dialect,
3057
+ foreignKeysEnforced
3058
+ });
3059
+ }
3042
3060
  await migrate();
3043
3061
  reportAppliedMigrations(drift.pending, migrationsFolder);
3044
3062
  }
@@ -3176,6 +3194,10 @@ function singleFlight(factory) {
3176
3194
  }
3177
3195
  //#endregion
3178
3196
  //#region src/connection-context.ts
3197
+ /** A resolver's value for `context`, without touching a factory's kept context or its staleness record. */
3198
+ function resolveFor(value, context) {
3199
+ return typeof value === "function" ? value(context) : value;
3200
+ }
3179
3201
  /**
3180
3202
  * One per factory. The context is kept rather than passed, because resolutions
3181
3203
  * also run inside memoized flights and admin clients that no `configureOrm()`
@@ -3201,6 +3223,151 @@ function connectionSettings() {
3201
3223
  };
3202
3224
  }
3203
3225
  //#endregion
3226
+ //#region src/database-description.ts
3227
+ const REDACTED = "[REDACTED]";
3228
+ /**
3229
+ * Client option and connection-string query keys that cannot move the endpoint off the URL's
3230
+ * host. Anything else (`host`, mysql2's `uri`, a `stream` or `socket` factory, a key a later
3231
+ * driver adds) reads as `unknown`: an allowlist, so a new option fails closed.
3232
+ */
3233
+ const ENDPOINT_NEUTRAL_KEYS = {
3234
+ postgres: /* @__PURE__ */ new Set([
3235
+ "max",
3236
+ "idle_timeout",
3237
+ "connect_timeout",
3238
+ "max_lifetime",
3239
+ "backoff",
3240
+ "keep_alive",
3241
+ "ssl",
3242
+ "sslmode",
3243
+ "prepare",
3244
+ "types",
3245
+ "transform",
3246
+ "onnotice",
3247
+ "onparameter",
3248
+ "onclose",
3249
+ "debug",
3250
+ "fetch_types",
3251
+ "connection",
3252
+ "publications",
3253
+ "user",
3254
+ "username",
3255
+ "pass",
3256
+ "password",
3257
+ "database",
3258
+ "db",
3259
+ "port",
3260
+ "application_name",
3261
+ "options",
3262
+ "search_path"
3263
+ ]),
3264
+ mysql: /* @__PURE__ */ new Set([
3265
+ "waitForConnections",
3266
+ "connectionLimit",
3267
+ "maxIdle",
3268
+ "idleTimeout",
3269
+ "queueLimit",
3270
+ "enableKeepAlive",
3271
+ "keepAliveInitialDelay",
3272
+ "ssl",
3273
+ "timezone",
3274
+ "charset",
3275
+ "typeCast",
3276
+ "connectTimeout",
3277
+ "user",
3278
+ "password",
3279
+ "database",
3280
+ "port",
3281
+ "dateStrings",
3282
+ "decimalNumbers",
3283
+ "supportBigNumbers",
3284
+ "bigNumberStrings",
3285
+ "jsonStrings",
3286
+ "multipleStatements",
3287
+ "namedPlaceholders",
3288
+ "rowsAsArray",
3289
+ "nestTables",
3290
+ "compress",
3291
+ "debug",
3292
+ "trace"
3293
+ ])
3294
+ };
3295
+ /** The loopback rule of `isLoopbackOrigin()` in @guren/server's loopback-guard.ts, over a WHATWG hostname. */
3296
+ function isLoopbackHost(hostname) {
3297
+ return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(hostname);
3298
+ }
3299
+ /** A server database's location from its connection string and the client options laid over it. */
3300
+ function describeServerDatabase(dialect, connectionString, clientOptions) {
3301
+ if (connectionString === void 0) return {
3302
+ dialect,
3303
+ location: "unknown",
3304
+ reason: "No connection string resolves."
3305
+ };
3306
+ if (connectionString.includes(REDACTED)) return {
3307
+ dialect,
3308
+ location: "unknown",
3309
+ reason: "The connection string is the placeholder the env reader writes for a missing or invalid value."
3310
+ };
3311
+ const neutral = ENDPOINT_NEUTRAL_KEYS[dialect];
3312
+ const option = Object.keys(clientOptions ?? {}).find((key) => !neutral.has(key));
3313
+ if (option) return {
3314
+ dialect,
3315
+ location: "unknown",
3316
+ reason: `The client options set \`${option}\`, which may choose the endpoint.`
3317
+ };
3318
+ let url;
3319
+ try {
3320
+ url = new URL(connectionString);
3321
+ } catch {
3322
+ return {
3323
+ dialect,
3324
+ location: "unknown",
3325
+ reason: "The connection string is not a URL."
3326
+ };
3327
+ }
3328
+ const query = [...url.searchParams.keys()].find((key) => dialect === "mysql" ? !neutral.has(key) : key === "host" || key === "hostaddr");
3329
+ if (query) return {
3330
+ dialect,
3331
+ location: "unknown",
3332
+ reason: `The connection string's query sets \`${query}\`, which may choose the endpoint.`
3333
+ };
3334
+ const hostname = url.hostname.toLowerCase();
3335
+ if (hostname === "") return {
3336
+ dialect,
3337
+ location: "unknown",
3338
+ reason: "The connection string names no host."
3339
+ };
3340
+ return isLoopbackHost(hostname) ? {
3341
+ dialect,
3342
+ location: "local"
3343
+ } : {
3344
+ dialect,
3345
+ location: "remote",
3346
+ reason: `The database host ${hostname} is not a loopback address.`
3347
+ };
3348
+ }
3349
+ function describeSqliteDatabase(filename) {
3350
+ let value;
3351
+ try {
3352
+ value = filename();
3353
+ } catch {
3354
+ return {
3355
+ dialect: "sqlite",
3356
+ location: "unknown",
3357
+ reason: "The database setting is not a file path the SQLite driver accepts, such as a connection URI."
3358
+ };
3359
+ }
3360
+ if (value.includes(REDACTED)) return {
3361
+ dialect: "sqlite",
3362
+ location: "unknown",
3363
+ reason: "The database file is the placeholder the env reader writes for a missing or invalid value."
3364
+ };
3365
+ return {
3366
+ dialect: "sqlite",
3367
+ location: "local"
3368
+ };
3369
+ }
3370
+ //#endregion
3204
3371
  //#region src/postgres.ts
3205
3372
  async function loadPostgresModules() {
3206
3373
  try {
@@ -3220,15 +3387,19 @@ async function loadPostgresModules() {
3220
3387
  }
3221
3388
  }
3222
3389
  function createPostgresDatabase(options) {
3223
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3390
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3224
3391
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3225
3392
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3226
3393
  let client;
3227
3394
  let activeKey;
3228
3395
  const callSite = (/* @__PURE__ */ new Error()).stack;
3229
3396
  const settings = connectionSettings();
3397
+ /** The one fallback rule, so what `describe()` judges is what a connection opens. */
3398
+ function connectionStringFrom(value) {
3399
+ return (value ?? process.env.DATABASE_URL) || void 0;
3400
+ }
3230
3401
  function resolveConnectionString() {
3231
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3402
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3232
3403
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3233
3404
  return resolved;
3234
3405
  }
@@ -3269,6 +3440,8 @@ function createPostgresDatabase(options) {
3269
3440
  ...relations ? { relations } : {}
3270
3441
  });
3271
3442
  await migrateAndReport(resolvedMigrationsFolder, {
3443
+ destructiveMigrations,
3444
+ dialect: "postgres",
3272
3445
  readApplied: report ? () => readAppliedMigrations(migrationClient) : void 0,
3273
3446
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3274
3447
  });
@@ -3366,7 +3539,10 @@ function createPostgresDatabase(options) {
3366
3539
  seedDatabase,
3367
3540
  resetDatabase,
3368
3541
  migrationStatus,
3369
- hasMigrations
3542
+ hasMigrations,
3543
+ describe(context) {
3544
+ return describeServerDatabase("postgres", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3545
+ }
3370
3546
  };
3371
3547
  }
3372
3548
  //#endregion
@@ -3389,15 +3565,19 @@ async function loadMySqlModules() {
3389
3565
  }
3390
3566
  }
3391
3567
  function createMySqlDatabase(options) {
3392
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3568
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3393
3569
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3394
3570
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3395
3571
  let client;
3396
3572
  let activeKey;
3397
3573
  const callSite = (/* @__PURE__ */ new Error()).stack;
3398
3574
  const settings = connectionSettings();
3575
+ /** The one fallback rule, so what `describe()` judges is what a connection opens. */
3576
+ function connectionStringFrom(value) {
3577
+ return (value ?? process.env.DATABASE_URL) || void 0;
3578
+ }
3399
3579
  function resolveConnectionString() {
3400
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3580
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3401
3581
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3402
3582
  return resolved;
3403
3583
  }
@@ -3440,6 +3620,8 @@ function createMySqlDatabase(options) {
3440
3620
  ...relations ? { relations } : {}
3441
3621
  });
3442
3622
  await migrateAndReport(resolvedMigrationsFolder, {
3623
+ destructiveMigrations,
3624
+ dialect: "mysql",
3443
3625
  readApplied: report ? () => readAppliedMigrations(migrationDb) : void 0,
3444
3626
  migrate: () => migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder })
3445
3627
  });
@@ -3546,7 +3728,10 @@ function createMySqlDatabase(options) {
3546
3728
  seedDatabase,
3547
3729
  resetDatabase,
3548
3730
  migrationStatus,
3549
- hasMigrations
3731
+ hasMigrations,
3732
+ describe(context) {
3733
+ return describeServerDatabase("mysql", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3734
+ }
3550
3735
  };
3551
3736
  }
3552
3737
  async function closePool(pool) {
@@ -3628,7 +3813,7 @@ function reportForeignKeyViolations(handle) {
3628
3813
  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
3814
  }
3630
3815
  function createSqliteDatabase(options) {
3631
- const { migrationsFolder, filename, seedersFolder, relations } = options;
3816
+ const { migrationsFolder, destructiveMigrations, filename, seedersFolder, relations } = options;
3632
3817
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3633
3818
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3634
3819
  let sqliteClient;
@@ -3636,7 +3821,9 @@ function createSqliteDatabase(options) {
3636
3821
  const callSite = (/* @__PURE__ */ new Error()).stack;
3637
3822
  const settings = connectionSettings();
3638
3823
  function resolveFilename() {
3639
- const value = settings.resolve(filename);
3824
+ return filenameFrom(settings.resolve(filename));
3825
+ }
3826
+ function filenameFrom(value) {
3640
3827
  if (value != null) {
3641
3828
  assertNotConnectionUri(value, "the \"filename\" option");
3642
3829
  return value;
@@ -3707,6 +3894,9 @@ function createSqliteDatabase(options) {
3707
3894
  const db = await database.get();
3708
3895
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
3709
3896
  await migrateAndReport(resolvedMigrationsFolder, {
3897
+ destructiveMigrations,
3898
+ dialect: "sqlite",
3899
+ foreignKeysEnforced: false,
3710
3900
  readApplied: report ? readAppliedMigrations : void 0,
3711
3901
  migrate: () => {
3712
3902
  const handle = db;
@@ -3752,6 +3942,9 @@ function createSqliteDatabase(options) {
3752
3942
  hasMigrations() {
3753
3943
  return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3754
3944
  },
3945
+ describe(context) {
3946
+ return describeSqliteDatabase(() => filenameFrom(resolveFor(filename, context)));
3947
+ },
3755
3948
  async migrationStatus() {
3756
3949
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3757
3950
  if (localMigrations.length === 0) return [];
@@ -3780,6 +3973,16 @@ function createSqliteDatabase(options) {
3780
3973
  }
3781
3974
  //#endregion
3782
3975
  //#region src/d1.ts
3976
+ /** `WORKERS_ENV_SLOT` in `@guren/plugin-cloudflare/env`, which captures the env; the ORM cannot import it. */
3977
+ const WORKERS_ENV_SLOT = Symbol.for("guren.workersEnv");
3978
+ /** Mirrors `readWorkersBinding()` in `@guren/plugin-cloudflare/env`. */
3979
+ function workersBinding(name) {
3980
+ const holder = globalThis[WORKERS_ENV_SLOT];
3981
+ if (!holder) throw new Error(`createD1Database: the "${name}" binding was read before the first request captured the Workers env. Use it inside a request.`);
3982
+ const value = holder.env?.[name];
3983
+ if (value == null) throw new Error(`createD1Database: the Workers env has no "${name}" binding. Check wrangler.jsonc, or the binding in cloudflare.config.ts.`);
3984
+ return value;
3985
+ }
3783
3986
  /**
3784
3987
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
3785
3988
  * written for `createSqliteDatabase` port unchanged; wrangler owns migrations
@@ -3788,9 +3991,15 @@ function createSqliteDatabase(options) {
3788
3991
  function createD1Database(options) {
3789
3992
  const { binding, migrationsFolder, relations } = options;
3790
3993
  const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath(migrationsFolder)) : migrationsFolder;
3791
- const databaseHandle = singleFlight(async () => {
3994
+ if (binding === "") throw new Error("createD1Database: `binding` names no binding; pass its name, such as 'DB'.");
3995
+ const bindingName = typeof binding === "string" ? binding : void 0;
3996
+ const resolveBinding = typeof binding === "string" ? () => workersBinding(binding) : () => {
3792
3997
  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.");
3998
+ 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.");
3999
+ return client;
4000
+ };
4001
+ const databaseHandle = singleFlight(async () => {
4002
+ const client = resolveBinding();
3794
4003
  const { drizzle } = await import("drizzle-orm/d1");
3795
4004
  return drizzle(client, relations ? { relations } : void 0);
3796
4005
  });
@@ -3815,8 +4024,16 @@ function createD1Database(options) {
3815
4024
  hasMigrations() {
3816
4025
  return false;
3817
4026
  },
4027
+ describe() {
4028
+ return {
4029
+ dialect: "d1",
4030
+ location: "unknown",
4031
+ reason: "A D1 binding is resolved per request, inside the Workers runtime.",
4032
+ ...bindingName ? { binding: bindingName } : {}
4033
+ };
4034
+ },
3818
4035
  async migrationStatus() {
3819
- throw new Error("Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead.");
4036
+ 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
4037
  }
3821
4038
  };
3822
4039
  }
@@ -3835,7 +4052,7 @@ async function loadAwsDataApiModules() {
3835
4052
  }
3836
4053
  }
3837
4054
  function createAwsDataApiDatabase(options) {
3838
- const { migrationsFolder, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
4055
+ const { migrationsFolder, destructiveMigrations, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
3839
4056
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3840
4057
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3841
4058
  let client;
@@ -3880,6 +4097,8 @@ function createAwsDataApiDatabase(options) {
3880
4097
  const { migrate } = await loadAwsDataApiModules();
3881
4098
  await withAdminDb(async (db) => {
3882
4099
  await migrateAndReport(resolvedMigrationsFolder, {
4100
+ destructiveMigrations,
4101
+ dialect: "postgres",
3883
4102
  readApplied: report ? () => readAppliedMigrations(db) : void 0,
3884
4103
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3885
4104
  });
@@ -3986,4 +4205,4 @@ function isMissingTrackerTableError(error) {
3986
4205
  return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
3987
4206
  }
3988
4207
  //#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 };
4208
+ 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 };