@guren/orm 2.13.1 → 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";
@@ -279,11 +280,14 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
279
280
  perPage?: number;
280
281
  }): Promise<PaginatedResult<TResult>>;
281
282
  /**
282
- * Bulk update. Mass-assignment protection and persistence preparation
283
- * (mutators, casts, `preparePersistencePayload`) apply exactly as in
284
- * `Model.update()`; per-record hooks and observers are skipped by design.
283
+ * Bulk update. Mass-assignment protection and persistence preparation apply
284
+ * exactly as in `Model.update()`; per-record hooks and observers are skipped.
285
+ * `set` holds the columns the server chooses (RFC 0031); `data` is untyped
286
+ * here, so a key in both is refused at runtime only, by `filterFillable()`.
285
287
  */
286
- update(data: PlainObject): Promise<TRecord>;
288
+ update(data: PlainObject, options?: {
289
+ set?: PlainObject;
290
+ }): Promise<TRecord>;
287
291
  /**
288
292
  * Bulk update bypassing mass-assignment protection. Trusted server-side data
289
293
  * only, never raw request input.
@@ -1101,6 +1105,21 @@ interface ConnectionContext {
1101
1105
  */
1102
1106
  type ConnectionResolver = string | ((context?: ConnectionContext) => string | undefined);
1103
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
1104
1123
  //#region src/migration-utils.d.ts
1105
1124
  /**
1106
1125
  * What one `migrateDatabase()` call had to work with. `db:migrate` reports
@@ -1130,6 +1149,8 @@ interface MigrationStatusEntry {
1130
1149
  * then deleted from disk (or migrated by another checkout). Absent otherwise.
1131
1150
  */
1132
1151
  orphaned?: boolean;
1152
+ /** The absolute `migration.sql` for a local migration; absent on an orphaned row. */
1153
+ path?: string;
1133
1154
  }
1134
1155
  //#endregion
1135
1156
  //#region src/seeder.d.ts
@@ -1179,6 +1200,12 @@ declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHan
1179
1200
  //#region src/postgres.d.ts
1180
1201
  interface PostgresDatabaseOptions {
1181
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;
1182
1209
  connectionString?: ConnectionResolver;
1183
1210
  clientOptions?: postgres.Options<Record<string, never>>;
1184
1211
  seedersFolder?: string | URL;
@@ -1204,6 +1231,8 @@ interface PostgresDatabase {
1204
1231
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1205
1232
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1206
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;
1207
1236
  }
1208
1237
  declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
1209
1238
  //#endregion
@@ -1211,6 +1240,12 @@ declare function createPostgresDatabase(options: PostgresDatabaseOptions): Postg
1211
1240
  type MySqlConnectionOptions = Record<string, unknown>;
1212
1241
  interface MySqlDatabaseOptions {
1213
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;
1214
1249
  connectionString?: ConnectionResolver;
1215
1250
  clientOptions?: MySqlConnectionOptions;
1216
1251
  seedersFolder?: string | URL;
@@ -1236,12 +1271,20 @@ interface MySqlDatabase {
1236
1271
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1237
1272
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1238
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;
1239
1276
  }
1240
1277
  declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
1241
1278
  //#endregion
1242
1279
  //#region src/sqlite.d.ts
1243
1280
  interface SqliteDatabaseOptions {
1244
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;
1245
1288
  /** Path to the SQLite database file. Defaults to `./data/guren.db`. */
1246
1289
  filename?: ConnectionResolver;
1247
1290
  seedersFolder?: string | URL;
@@ -1271,17 +1314,19 @@ interface SqliteDatabase {
1271
1314
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1272
1315
  /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1273
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;
1274
1319
  }
1275
1320
  declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
1276
1321
  //#endregion
1277
1322
  //#region src/d1.d.ts
1278
1323
  interface D1DatabaseOptions {
1279
1324
  /**
1280
- * Resolver returning the Cloudflare D1 binding. Bindings arrive with the
1281
- * first request on Workers, so this must be a deferred closure, e.g.
1282
- * `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.
1283
1328
  */
1284
- binding: () => unknown;
1329
+ binding: string | (() => unknown);
1285
1330
  /**
1286
1331
  * Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
1287
1332
  * `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` here);
@@ -1309,6 +1354,8 @@ interface D1DatabaseHandle {
1309
1354
  migrationStatus(): Promise<never>;
1310
1355
  /** Always false: wrangler applies D1 migrations and the factory never seeds, so nothing at boot acts on them. */
1311
1356
  hasMigrations(): boolean;
1357
+ /** Always `unknown`; see its `reason`. */
1358
+ describe(): DatabaseDescription;
1312
1359
  }
1313
1360
  /**
1314
1361
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
@@ -1321,6 +1368,12 @@ declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1321
1368
  type AwsDataApiPgDatabase$1 = import('drizzle-orm/aws-data-api/pg').AwsDataApiPgDatabase;
1322
1369
  interface AwsDataApiDatabaseOptions {
1323
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;
1324
1377
  /** Database name. Falls back to the DATABASE_NAME environment variable. */
1325
1378
  database?: ConnectionResolver;
1326
1379
  /** Aurora cluster ARN. Falls back to the DATABASE_RESOURCE_ARN environment variable. */
@@ -1373,4 +1426,4 @@ declare function serializeRecord(record: PlainObject, options: {
1373
1426
  /** Serialize an array of records. */
1374
1427
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1375
1428
  //#endregion
1376
- 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";
@@ -1554,12 +1555,13 @@ var QueryBuilder = class QueryBuilder {
1554
1555
  };
1555
1556
  }
1556
1557
  /**
1557
- * Bulk update. Mass-assignment protection and persistence preparation
1558
- * (mutators, casts, `preparePersistencePayload`) apply exactly as in
1559
- * `Model.update()`; per-record hooks and observers are skipped by design.
1558
+ * Bulk update. Mass-assignment protection and persistence preparation apply
1559
+ * exactly as in `Model.update()`; per-record hooks and observers are skipped.
1560
+ * `set` holds the columns the server chooses (RFC 0031); `data` is untyped
1561
+ * here, so a key in both is refused at runtime only, by `filterFillable()`.
1560
1562
  */
1561
- async update(data) {
1562
- return this.runBulkUpdate(data, true);
1563
+ async update(data, options) {
1564
+ return this.runBulkUpdate(data, true, options?.set);
1563
1565
  }
1564
1566
  /**
1565
1567
  * Bulk update bypassing mass-assignment protection. Trusted server-side data
@@ -1568,9 +1570,9 @@ var QueryBuilder = class QueryBuilder {
1568
1570
  async forceUpdate(data) {
1569
1571
  return this.runBulkUpdate(data, false);
1570
1572
  }
1571
- async runBulkUpdate(data, applyFillable) {
1573
+ async runBulkUpdate(data, applyFillable, set) {
1572
1574
  const model = this.modelClass;
1573
- const filtered = applyFillable ? model.filterFillable(data) : { ...data };
1575
+ const filtered = applyFillable ? model.filterFillable(data, set) : { ...data };
1574
1576
  const payload = await model.prepareBulkPersistencePayload(filtered);
1575
1577
  return this[PREPARED_UPDATE](payload);
1576
1578
  }
@@ -2973,7 +2975,10 @@ function describeConnectionEndpoint(connectionString) {
2973
2975
  /** drizzle-kit migrations, sorted the way the drizzle migrator applies them. */
2974
2976
  function listLocalMigrations(migrationsFolder) {
2975
2977
  if (!existsSync(migrationsFolder)) return [];
2976
- 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));
2977
2982
  }
2978
2983
  function parseAppliedAt(row) {
2979
2984
  if (!row?.appliedAt) return null;
@@ -2995,7 +3000,8 @@ function buildMigrationStatus(localMigrations, appliedRows) {
2995
3000
  return {
2996
3001
  name: migration.name,
2997
3002
  applied: row !== void 0,
2998
- appliedAt: parseAppliedAt(row)
3003
+ appliedAt: parseAppliedAt(row),
3004
+ path: migration.path
2999
3005
  };
3000
3006
  });
3001
3007
  if (unmatchedRows.size === 0) return entries;
@@ -3017,12 +3023,15 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3017
3023
  const status = buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied());
3018
3024
  return {
3019
3025
  pending: status.filter((entry) => !entry.applied).map((entry) => entry.name),
3020
- orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name)
3026
+ orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name),
3027
+ readable: true
3021
3028
  };
3022
- } catch {
3029
+ } catch (error) {
3023
3030
  return {
3024
3031
  pending: [],
3025
- orphaned: []
3032
+ orphaned: [],
3033
+ readable: false,
3034
+ error
3026
3035
  };
3027
3036
  }
3028
3037
  }
@@ -3032,12 +3041,22 @@ async function readMigrationDrift(migrationsFolder, readApplied) {
3032
3041
  * before it runs, since they are the likeliest reason it is about to fail.
3033
3042
  * Without `readApplied` nothing is read or reported: a reset's re-apply.
3034
3043
  */
3035
- async function migrateAndReport(migrationsFolder, { readApplied, migrate }) {
3044
+ async function migrateAndReport(migrationsFolder, { readApplied, migrate, destructiveMigrations = "warn", dialect, foreignKeysEnforced }) {
3036
3045
  const drift = readApplied ? await readMigrationDrift(migrationsFolder, readApplied) : {
3037
3046
  pending: [],
3038
- orphaned: []
3047
+ orphaned: [],
3048
+ readable: true
3039
3049
  };
3040
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
+ }
3041
3060
  await migrate();
3042
3061
  reportAppliedMigrations(drift.pending, migrationsFolder);
3043
3062
  }
@@ -3175,6 +3194,10 @@ function singleFlight(factory) {
3175
3194
  }
3176
3195
  //#endregion
3177
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
+ }
3178
3201
  /**
3179
3202
  * One per factory. The context is kept rather than passed, because resolutions
3180
3203
  * also run inside memoized flights and admin clients that no `configureOrm()`
@@ -3200,6 +3223,151 @@ function connectionSettings() {
3200
3223
  };
3201
3224
  }
3202
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
3203
3371
  //#region src/postgres.ts
3204
3372
  async function loadPostgresModules() {
3205
3373
  try {
@@ -3219,15 +3387,19 @@ async function loadPostgresModules() {
3219
3387
  }
3220
3388
  }
3221
3389
  function createPostgresDatabase(options) {
3222
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3390
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3223
3391
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3224
3392
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3225
3393
  let client;
3226
3394
  let activeKey;
3227
3395
  const callSite = (/* @__PURE__ */ new Error()).stack;
3228
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
+ }
3229
3401
  function resolveConnectionString() {
3230
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3402
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3231
3403
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3232
3404
  return resolved;
3233
3405
  }
@@ -3268,6 +3440,8 @@ function createPostgresDatabase(options) {
3268
3440
  ...relations ? { relations } : {}
3269
3441
  });
3270
3442
  await migrateAndReport(resolvedMigrationsFolder, {
3443
+ destructiveMigrations,
3444
+ dialect: "postgres",
3271
3445
  readApplied: report ? () => readAppliedMigrations(migrationClient) : void 0,
3272
3446
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3273
3447
  });
@@ -3365,7 +3539,10 @@ function createPostgresDatabase(options) {
3365
3539
  seedDatabase,
3366
3540
  resetDatabase,
3367
3541
  migrationStatus,
3368
- hasMigrations
3542
+ hasMigrations,
3543
+ describe(context) {
3544
+ return describeServerDatabase("postgres", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3545
+ }
3369
3546
  };
3370
3547
  }
3371
3548
  //#endregion
@@ -3388,15 +3565,19 @@ async function loadMySqlModules() {
3388
3565
  }
3389
3566
  }
3390
3567
  function createMySqlDatabase(options) {
3391
- const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
3568
+ const { migrationsFolder, destructiveMigrations, connectionString, clientOptions, seedersFolder, relations } = options;
3392
3569
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3393
3570
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3394
3571
  let client;
3395
3572
  let activeKey;
3396
3573
  const callSite = (/* @__PURE__ */ new Error()).stack;
3397
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
+ }
3398
3579
  function resolveConnectionString() {
3399
- const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
3580
+ const resolved = connectionStringFrom(settings.resolve(connectionString));
3400
3581
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
3401
3582
  return resolved;
3402
3583
  }
@@ -3439,6 +3620,8 @@ function createMySqlDatabase(options) {
3439
3620
  ...relations ? { relations } : {}
3440
3621
  });
3441
3622
  await migrateAndReport(resolvedMigrationsFolder, {
3623
+ destructiveMigrations,
3624
+ dialect: "mysql",
3442
3625
  readApplied: report ? () => readAppliedMigrations(migrationDb) : void 0,
3443
3626
  migrate: () => migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder })
3444
3627
  });
@@ -3545,7 +3728,10 @@ function createMySqlDatabase(options) {
3545
3728
  seedDatabase,
3546
3729
  resetDatabase,
3547
3730
  migrationStatus,
3548
- hasMigrations
3731
+ hasMigrations,
3732
+ describe(context) {
3733
+ return describeServerDatabase("mysql", connectionStringFrom(resolveFor(connectionString, context)), clientOptions);
3734
+ }
3549
3735
  };
3550
3736
  }
3551
3737
  async function closePool(pool) {
@@ -3627,7 +3813,7 @@ function reportForeignKeyViolations(handle) {
3627
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.`);
3628
3814
  }
3629
3815
  function createSqliteDatabase(options) {
3630
- const { migrationsFolder, filename, seedersFolder, relations } = options;
3816
+ const { migrationsFolder, destructiveMigrations, filename, seedersFolder, relations } = options;
3631
3817
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3632
3818
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3633
3819
  let sqliteClient;
@@ -3635,7 +3821,9 @@ function createSqliteDatabase(options) {
3635
3821
  const callSite = (/* @__PURE__ */ new Error()).stack;
3636
3822
  const settings = connectionSettings();
3637
3823
  function resolveFilename() {
3638
- const value = settings.resolve(filename);
3824
+ return filenameFrom(settings.resolve(filename));
3825
+ }
3826
+ function filenameFrom(value) {
3639
3827
  if (value != null) {
3640
3828
  assertNotConnectionUri(value, "the \"filename\" option");
3641
3829
  return value;
@@ -3706,6 +3894,9 @@ function createSqliteDatabase(options) {
3706
3894
  const db = await database.get();
3707
3895
  const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
3708
3896
  await migrateAndReport(resolvedMigrationsFolder, {
3897
+ destructiveMigrations,
3898
+ dialect: "sqlite",
3899
+ foreignKeysEnforced: false,
3709
3900
  readApplied: report ? readAppliedMigrations : void 0,
3710
3901
  migrate: () => {
3711
3902
  const handle = db;
@@ -3751,6 +3942,9 @@ function createSqliteDatabase(options) {
3751
3942
  hasMigrations() {
3752
3943
  return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3753
3944
  },
3945
+ describe(context) {
3946
+ return describeSqliteDatabase(() => filenameFrom(resolveFor(filename, context)));
3947
+ },
3754
3948
  async migrationStatus() {
3755
3949
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3756
3950
  if (localMigrations.length === 0) return [];
@@ -3779,6 +3973,16 @@ function createSqliteDatabase(options) {
3779
3973
  }
3780
3974
  //#endregion
3781
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
+ }
3782
3986
  /**
3783
3987
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
3784
3988
  * written for `createSqliteDatabase` port unchanged; wrangler owns migrations
@@ -3787,9 +3991,15 @@ function createSqliteDatabase(options) {
3787
3991
  function createD1Database(options) {
3788
3992
  const { binding, migrationsFolder, relations } = options;
3789
3993
  const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath(migrationsFolder)) : migrationsFolder;
3790
- 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) : () => {
3791
3997
  const client = binding();
3792
- 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();
3793
4003
  const { drizzle } = await import("drizzle-orm/d1");
3794
4004
  return drizzle(client, relations ? { relations } : void 0);
3795
4005
  });
@@ -3814,8 +4024,16 @@ function createD1Database(options) {
3814
4024
  hasMigrations() {
3815
4025
  return false;
3816
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
+ },
3817
4035
  async migrationStatus() {
3818
- 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.");
3819
4037
  }
3820
4038
  };
3821
4039
  }
@@ -3834,7 +4052,7 @@ async function loadAwsDataApiModules() {
3834
4052
  }
3835
4053
  }
3836
4054
  function createAwsDataApiDatabase(options) {
3837
- const { migrationsFolder, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
4055
+ const { migrationsFolder, destructiveMigrations, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
3838
4056
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
3839
4057
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
3840
4058
  let client;
@@ -3879,6 +4097,8 @@ function createAwsDataApiDatabase(options) {
3879
4097
  const { migrate } = await loadAwsDataApiModules();
3880
4098
  await withAdminDb(async (db) => {
3881
4099
  await migrateAndReport(resolvedMigrationsFolder, {
4100
+ destructiveMigrations,
4101
+ dialect: "postgres",
3882
4102
  readApplied: report ? () => readAppliedMigrations(db) : void 0,
3883
4103
  migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
3884
4104
  });
@@ -3985,4 +4205,4 @@ function isMissingTrackerTableError(error) {
3985
4205
  return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
3986
4206
  }
3987
4207
  //#endregion
3988
- 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 };