@guren/orm 2.10.1 → 2.11.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +108 -12
  2. package/dist/index.js +214 -14
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -36,6 +36,30 @@ declare const RAW_RESULTS: unique symbol;
36
36
  //#endregion
37
37
  //#region src/QueryBuilder.d.ts
38
38
  type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
39
+ type AggregateFunction = 'sum' | 'avg' | 'min' | 'max';
40
+ /**
41
+ * A sum comes back in the column's own kind: drizzle types `numeric`/`decimal`
42
+ * as `string` so no digit is lost, and a sum of one stays exact the same way.
43
+ */
44
+ type SumValue<TValue> = unknown extends TValue ? number | bigint | string : NonNullable<TValue> extends number ? number : NonNullable<TValue> extends bigint ? bigint : NonNullable<TValue> extends string ? string : never;
45
+ /** An average is fractional, so only a `number` column's stays a `number`; exact kinds render as a decimal string. */
46
+ type AvgValue<TValue> = unknown extends TValue ? number | string : NonNullable<TValue> extends number ? number : NonNullable<TValue> extends bigint | string ? string : never;
47
+ /**
48
+ * Columns `sum()`/`avg()` accept; any name on an untyped record (`withTrashed()`'s).
49
+ * A text column is a `string` too, which the type cannot tell from `numeric`.
50
+ */
51
+ type NumericFieldKey<TRecord extends PlainObject> = string extends keyof TRecord ? string : { [K in FieldKey<TRecord>]: [SumValue<TRecord[K]>] extends [never] ? never : K; }[FieldKey<TRecord>];
52
+ /** A Drizzle select builder as `toDrizzle(query)` needs it: something to add a where clause to. */
53
+ type DrizzleWhereable = {
54
+ where: (...args: any[]) => unknown;
55
+ };
56
+ /** What `toDrizzle()` promises of `select().from(table)`; hand it a query of your own for joins. */
57
+ interface DrizzleSelectQuery<TRow> extends PromiseLike<TRow[]> {
58
+ where(clause: SQL | undefined): this;
59
+ orderBy(...columns: Array<SQL | SQL.Aliased | object>): this;
60
+ limit(limit: number): this;
61
+ offset(offset: number): this;
62
+ }
39
63
  type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
40
64
  interface SimpleCondition {
41
65
  type: 'simple';
@@ -158,6 +182,39 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
158
182
  * and whole where it cannot.
159
183
  */
160
184
  countBy(field: FieldKey<TRecord>): Promise<Map<unknown, number>>;
185
+ /**
186
+ * Sum of `field` over the matching rows, in the column's own kind (see
187
+ * {@link SumValue}); no rows sum to that kind's zero. Like `count()`, it
188
+ * ignores `limit()`/`offset()`. A throw from an integer column means the
189
+ * total is past `Number.MAX_SAFE_INTEGER`: declare the column in bigint mode.
190
+ */
191
+ sum<TKey extends NumericFieldKey<TRecord>>(field: TKey): Promise<SumValue<TRecord[TKey]>>;
192
+ /** Average of `field` over the matching rows; `null` when none match. */
193
+ avg<TKey extends NumericFieldKey<TRecord>>(field: TKey): Promise<AvgValue<TRecord[TKey]> | null>;
194
+ /** Smallest `field` over the matching rows, decoded as the column is; `null` when none match. */
195
+ min<TKey extends FieldKey<TRecord>>(field: TKey): Promise<NonNullable<TRecord[TKey]> | null>;
196
+ /** Largest `field` over the matching rows, decoded as the column is; `null` when none match. */
197
+ max<TKey extends FieldKey<TRecord>>(field: TKey): Promise<NonNullable<TRecord[TKey]> | null>;
198
+ /** Whether any row matches. Reads at most one row and runs no casts, accessors or eager loads. */
199
+ exists(): Promise<boolean>;
200
+ /**
201
+ * The model's conditions, global scopes included, as one Drizzle `SQL`
202
+ * fragment for a hand-built query; `undefined` when there are none. Combine
203
+ * it with `and()`: a second `.where()` on a Drizzle builder replaces the first.
204
+ * @example db.select().from(posts).where(and(Post.newQuery().toSql(), gt(posts.views, 100)))
205
+ */
206
+ toSql(): SQL | undefined;
207
+ /**
208
+ * A Drizzle select carrying {@link toSql}, `orderBy()`, `limit()` and `offset()`; a later `.where()` is AND-ed with the conditions.
209
+ * No argument: `select().from(table)` narrowed by `select()`, on this builder's `trx`, else the open transaction, else the database.
210
+ * With a query (`db.select({ ... }).from(posts).leftJoin(...)`): that query, keeping its Drizzle type and selection.
211
+ * Rows are Drizzle's either way: no casts, accessors or eager loads.
212
+ */
213
+ toDrizzle(): DrizzleSelectQuery<TResult>;
214
+ toDrizzle<TQuery extends DrizzleWhereable>(query: TQuery): TQuery;
215
+ private selectFromTable;
216
+ private resolveDrizzleDatabase;
217
+ private aggregate;
161
218
  /**
162
219
  * Takes positional arguments or the same options object as
163
220
  * `Model.paginate()`, so the two APIs stay interchangeable.
@@ -246,6 +303,14 @@ interface ORMAdapterAdvanced extends ORMAdapter {
246
303
  * supports admits.
247
304
  */
248
305
  maxInListSize?(): number;
306
+ /**
307
+ * `SELECT fn(field)` under `conditions`, decoded in the column's own kind
308
+ * ({@link SumValue}, {@link AvgValue}); a sum over no rows is that kind's
309
+ * zero, the other functions `null`.
310
+ */
311
+ aggregateAdvanced?(table: unknown, fn: AggregateFunction, field: string, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<unknown>;
312
+ /** The handle a query built outside the ORM runs on: `trx`, else the open transaction, else the database. */
313
+ executor?(queryOptions?: AdapterQueryOptions): unknown;
249
314
  /** `SELECT field, COUNT(*) ... GROUP BY field` under `conditions`. */
250
315
  countByAdvanced?(table: unknown, field: string, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<Array<{
251
316
  key: unknown;
@@ -627,6 +692,9 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
627
692
  /**
628
693
  * A raw Drizzle builder starting at `select().from(table)`. Carries no model
629
694
  * scopes, casts or accessors.
695
+ *
696
+ * @deprecated Reads soft-deleted rows and other tenants' rows. Use `Model.newQuery().toDrizzle()`
697
+ * (or `toDrizzle(db.select().from(table))`), which keeps the scopes, or the builder's `sum`/`avg`/`min`/`max`/`exists`.
630
698
  */
631
699
  static query<TDatabase extends {
632
700
  select: (...args: any[]) => any;
@@ -937,6 +1005,24 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
937
1005
  */
938
1006
  declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
939
1007
  //#endregion
1008
+ //#region src/connection-context.d.ts
1009
+ /**
1010
+ * The app's validated environment, as a connection resolver sees it. Empty
1011
+ * here: `@guren/orm` cannot depend on `@guren/server`, so `@guren/core`
1012
+ * extends it with `AppEnv` (RFC 0027 §2).
1013
+ */
1014
+ interface OrmConnectionEnv {}
1015
+ /** What `configureOrm(context)` hands every later resolution of a connection setting. */
1016
+ interface ConnectionContext {
1017
+ readonly env: OrmConnectionEnv;
1018
+ }
1019
+ /**
1020
+ * A connection setting, or a function of the context the factory last received
1021
+ * through `configureOrm(context)`; `undefined` outside an application. A result
1022
+ * of `undefined` falls back to the driver's environment variable.
1023
+ */
1024
+ type ConnectionResolver = string | ((context?: ConnectionContext) => string | undefined);
1025
+ //#endregion
940
1026
  //#region src/migration-utils.d.ts
941
1027
  /**
942
1028
  * What one `migrateDatabase()` call had to work with. `db:migrate` reports
@@ -1013,10 +1099,9 @@ declare function runSeeders<TDatabase>(db: TDatabase, directory: string | URL):
1013
1099
  declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHandler<TDatabase>): SeederHandler<TDatabase>;
1014
1100
  //#endregion
1015
1101
  //#region src/postgres.d.ts
1016
- type ConnectionResolver$3 = string | (() => string | undefined);
1017
1102
  interface PostgresDatabaseOptions {
1018
1103
  migrationsFolder: string | URL;
1019
- connectionString?: ConnectionResolver$3;
1104
+ connectionString?: ConnectionResolver;
1020
1105
  clientOptions?: postgres.Options<Record<string, never>>;
1021
1106
  seedersFolder?: string | URL;
1022
1107
  /**
@@ -1031,22 +1116,24 @@ interface PostgresDatabase {
1031
1116
  /** Applies pending drizzle-kit migrations and reports what the folder held. */
1032
1117
  migrateDatabase(): Promise<MigrationRunSummary>;
1033
1118
  closeDatabase(): Promise<void>;
1034
- configureOrm(): Promise<void>;
1119
+ /** `context` reaches `connectionString` here and in every later resolution. */
1120
+ configureOrm(context?: ConnectionContext): Promise<void>;
1035
1121
  /** Runs every seeder in the configured folder and reports what it held. */
1036
1122
  seedDatabase(): Promise<SeederRunSummary>;
1037
1123
  /** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
1038
1124
  resetDatabase(): Promise<MigrationRunSummary>;
1039
1125
  /** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
1040
1126
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1127
+ /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1128
+ hasMigrations(): boolean;
1041
1129
  }
1042
1130
  declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
1043
1131
  //#endregion
1044
1132
  //#region src/mysql.d.ts
1045
- type ConnectionResolver$2 = string | (() => string | undefined);
1046
1133
  type MySqlConnectionOptions = Record<string, unknown>;
1047
1134
  interface MySqlDatabaseOptions {
1048
1135
  migrationsFolder: string | URL;
1049
- connectionString?: ConnectionResolver$2;
1136
+ connectionString?: ConnectionResolver;
1050
1137
  clientOptions?: MySqlConnectionOptions;
1051
1138
  seedersFolder?: string | URL;
1052
1139
  /**
@@ -1061,22 +1148,24 @@ interface MySqlDatabase {
1061
1148
  /** Applies pending drizzle-kit migrations and reports what the folder held. */
1062
1149
  migrateDatabase(): Promise<MigrationRunSummary>;
1063
1150
  closeDatabase(): Promise<void>;
1064
- configureOrm(): Promise<void>;
1151
+ /** `context` reaches `connectionString` here and in every later resolution. */
1152
+ configureOrm(context?: ConnectionContext): Promise<void>;
1065
1153
  /** Runs every seeder in the configured folder and reports what it held. */
1066
1154
  seedDatabase(): Promise<SeederRunSummary>;
1067
1155
  /** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
1068
1156
  resetDatabase(): Promise<MigrationRunSummary>;
1069
1157
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1070
1158
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1159
+ /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1160
+ hasMigrations(): boolean;
1071
1161
  }
1072
1162
  declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
1073
1163
  //#endregion
1074
1164
  //#region src/sqlite.d.ts
1075
- type ConnectionResolver$1 = string | (() => string | undefined);
1076
1165
  interface SqliteDatabaseOptions {
1077
1166
  migrationsFolder: string | URL;
1078
1167
  /** Path to the SQLite database file. Defaults to `./data/guren.db`. */
1079
- filename?: ConnectionResolver$1;
1168
+ filename?: ConnectionResolver;
1080
1169
  seedersFolder?: string | URL;
1081
1170
  /**
1082
1171
  * Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
@@ -1090,7 +1179,8 @@ interface SqliteDatabase {
1090
1179
  /** Applies pending drizzle-kit migrations and reports what the folder held. */
1091
1180
  migrateDatabase(): Promise<MigrationRunSummary>;
1092
1181
  closeDatabase(): Promise<void>;
1093
- configureOrm(): Promise<void>;
1182
+ /** `context` reaches `filename` here and in every later resolution. */
1183
+ configureOrm(context?: ConnectionContext): Promise<void>;
1094
1184
  /** Runs every seeder in the configured folder and reports what it held. */
1095
1185
  seedDatabase(): Promise<SeederRunSummary>;
1096
1186
  /**
@@ -1101,6 +1191,8 @@ interface SqliteDatabase {
1101
1191
  resetDatabase(): Promise<MigrationRunSummary | undefined>;
1102
1192
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1103
1193
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1194
+ /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1195
+ hasMigrations(): boolean;
1104
1196
  }
1105
1197
  declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
1106
1198
  //#endregion
@@ -1137,6 +1229,8 @@ interface D1DatabaseHandle {
1137
1229
  resetDatabase(): Promise<never>;
1138
1230
  /** Always throws: wrangler's tracker is authoritative — use `wrangler d1 migrations list`. */
1139
1231
  migrationStatus(): Promise<never>;
1232
+ /** Always false: wrangler applies D1 migrations and the factory never seeds, so nothing at boot acts on them. */
1233
+ hasMigrations(): boolean;
1140
1234
  }
1141
1235
  /**
1142
1236
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
@@ -1146,7 +1240,6 @@ interface D1DatabaseHandle {
1146
1240
  declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1147
1241
  //#endregion
1148
1242
  //#region src/aws-data-api.d.ts
1149
- type ConnectionResolver = string | (() => string | undefined);
1150
1243
  type AwsDataApiPgDatabase$1 = import('drizzle-orm/aws-data-api/pg').AwsDataApiPgDatabase;
1151
1244
  interface AwsDataApiDatabaseOptions {
1152
1245
  migrationsFolder: string | URL;
@@ -1178,13 +1271,16 @@ interface AwsDataApiDatabase {
1178
1271
  /** Applies pending drizzle-kit migrations and reports what the folder held. */
1179
1272
  migrateDatabase(): Promise<MigrationRunSummary>;
1180
1273
  closeDatabase(): Promise<void>;
1181
- configureOrm(): Promise<void>;
1274
+ /** `context` reaches `database`, `resourceArn` and `secretArn` here and in every later resolution. */
1275
+ configureOrm(context?: ConnectionContext): Promise<void>;
1182
1276
  /** Runs every seeder in the configured folder and reports what it held. */
1183
1277
  seedDatabase(): Promise<SeederRunSummary>;
1184
1278
  /** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
1185
1279
  resetDatabase(): Promise<MigrationRunSummary>;
1186
1280
  /** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
1187
1281
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1282
+ /** Whether the migrations folder holds a migration. Reads files only, never the database. */
1283
+ hasMigrations(): boolean;
1188
1284
  }
1189
1285
  declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
1190
1286
  //#endregion
@@ -1199,4 +1295,4 @@ declare function serializeRecord(record: PlainObject, options: {
1199
1295
  /** Serialize an array of records. */
1200
1296
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1201
1297
  //#endregion
1202
- export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, 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 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 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 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 };
1298
+ 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 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,4 +1,4 @@
1
- import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or, sql } from "drizzle-orm";
1
+ import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, max, min, ne, notInArray, or, sql } from "drizzle-orm";
2
2
  import { extname, relative, resolve } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { existsSync, readdirSync } from "node:fs";
@@ -215,6 +215,31 @@ function toCount(value) {
215
215
  const total = Number(value ?? 0);
216
216
  return Number.isNaN(total) ? 0 : total;
217
217
  }
218
+ /** A drizzle 1.x column's `dataType` leads with its JS kind (`number int32`, `string numeric`); 0.x has only the kind. */
219
+ function columnKind(column) {
220
+ const dataType = column.dataType;
221
+ return typeof dataType === "string" ? dataType.split(" ")[0] : "";
222
+ }
223
+ /**
224
+ * Drivers disagree on an aggregate's wire type (postgres-js and mysql2 send
225
+ * `sum(int)` as a decimal string, bun:sqlite as a number), so the column's kind
226
+ * decides, never the driver.
227
+ */
228
+ function decodeAggregate(fn, column, field, raw) {
229
+ const kind = columnKind(column);
230
+ if (raw === null || raw === void 0) {
231
+ if (fn !== "sum") return null;
232
+ return kind === "bigint" ? 0n : kind === "string" ? "0" : 0;
233
+ }
234
+ if (kind === "number") {
235
+ const value = Number(raw);
236
+ if (typeof raw === "string" && /^-?\d+$/.test(raw) && !Number.isSafeInteger(value)) throw new RangeError(`DrizzleAdapter: ${fn}("${field}") is ${String(raw)}, past Number.MAX_SAFE_INTEGER; declare the column with mode: 'bigint'.`);
237
+ return value;
238
+ }
239
+ if (kind === "bigint") return fn === "avg" ? String(raw) : typeof raw === "bigint" ? raw : BigInt(String(raw));
240
+ if (kind === "string") return String(raw);
241
+ return raw;
242
+ }
218
243
  function ensureDatabase() {
219
244
  if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
220
245
  return database;
@@ -523,6 +548,15 @@ const DrizzleAdapter = {
523
548
  async countAdvanced(table, conditions, queryOptions) {
524
549
  return toCount((await resolveList(withConditions(resolveExecutor(queryOptions).select({ value: count() }).from(table), table, conditions)))[0]?.value);
525
550
  },
551
+ async aggregateAdvanced(table, fn, field, conditions, queryOptions) {
552
+ const db = resolveExecutor(queryOptions);
553
+ const column = resolveColumn(table, field);
554
+ const expression = fn === "min" ? min(column) : fn === "max" ? max(column) : sql`${sql.raw(fn)}(${column})`;
555
+ return decodeAggregate(fn, column, field, (await resolveList(withConditions(db.select({ value: expression }).from(table), table, conditions)))[0]?.value ?? null);
556
+ },
557
+ executor(queryOptions) {
558
+ return resolveExecutor(queryOptions);
559
+ },
526
560
  async countByAdvanced(table, field, conditions, queryOptions) {
527
561
  const db = resolveExecutor(queryOptions);
528
562
  const column = table[field];
@@ -617,6 +651,19 @@ function applyMutators(data, mutators) {
617
651
  return result;
618
652
  }
619
653
  //#endregion
654
+ //#region src/deprecate.ts
655
+ const warned = /* @__PURE__ */ new Set();
656
+ /**
657
+ * @internal The deprecation policy's warning format
658
+ * (`contributing/deprecation-policy.md`), once per `id:symbol` per process.
659
+ */
660
+ function warnDeprecated(id, symbol, replacement, versions) {
661
+ const key = `${id}:${symbol}`;
662
+ if (warned.has(key)) return;
663
+ warned.add(key);
664
+ console.warn(`[guren] Deprecation (${id}): ${symbol}() is deprecated\n since ${versions.since}, will be removed in ${versions.removedIn}.\n ${replacement}`);
665
+ }
666
+ //#endregion
620
667
  //#region src/GlobalScopeRegistry.ts
621
668
  /** Registry for the named global scopes applied to every query on a model. */
622
669
  var GlobalScopeRegistry = class GlobalScopeRegistry {
@@ -884,6 +931,87 @@ var QueryBuilder = class QueryBuilder {
884
931
  }
885
932
  return counts;
886
933
  }
934
+ /**
935
+ * Sum of `field` over the matching rows, in the column's own kind (see
936
+ * {@link SumValue}); no rows sum to that kind's zero. Like `count()`, it
937
+ * ignores `limit()`/`offset()`. A throw from an integer column means the
938
+ * total is past `Number.MAX_SAFE_INTEGER`: declare the column in bigint mode.
939
+ */
940
+ async sum(field) {
941
+ return this.aggregate("sum", field);
942
+ }
943
+ /** Average of `field` over the matching rows; `null` when none match. */
944
+ async avg(field) {
945
+ return this.aggregate("avg", field);
946
+ }
947
+ /** Smallest `field` over the matching rows, decoded as the column is; `null` when none match. */
948
+ async min(field) {
949
+ return this.aggregate("min", field);
950
+ }
951
+ /** Largest `field` over the matching rows, decoded as the column is; `null` when none match. */
952
+ async max(field) {
953
+ return this.aggregate("max", field);
954
+ }
955
+ /** Whether any row matches. Reads at most one row and runs no casts, accessors or eager loads. */
956
+ async exists() {
957
+ if (this.filtersEvaporated()) return false;
958
+ return (await this.executeQuery({
959
+ limit: 1,
960
+ orderBy: []
961
+ })).length > 0;
962
+ }
963
+ /**
964
+ * The model's conditions, global scopes included, as one Drizzle `SQL`
965
+ * fragment for a hand-built query; `undefined` when there are none. Combine
966
+ * it with `and()`: a second `.where()` on a Drizzle builder replaces the first.
967
+ * @example db.select().from(posts).where(and(Post.newQuery().toSql(), gt(posts.views, 100)))
968
+ */
969
+ toSql() {
970
+ return buildDrizzleConditions(this.table, this.effectiveConditions());
971
+ }
972
+ toDrizzle(query) {
973
+ const target = query ?? this.selectFromTable();
974
+ if (!target || typeof target.where !== "function") throw new Error(`${this.modelClass.name}: toDrizzle() needs a Drizzle select; what it reached has no where().`);
975
+ const scoped = this.toSql();
976
+ const replaceWhere = target.where.bind(target);
977
+ const existing = target.config?.where;
978
+ if (scoped) replaceWhere(and(existing, scoped));
979
+ Object.defineProperty(target, "where", {
980
+ configurable: true,
981
+ writable: true,
982
+ value: (clause) => replaceWhere(typeof clause === "function" ? (fields) => and(scoped, clause(fields)) : and(scoped, clause))
983
+ });
984
+ const { orderBy, limitValue, offsetValue } = this.options;
985
+ const pageable = target;
986
+ if (orderBy.length > 0) pageable.orderBy(...orderBy.map(({ column, direction }) => (direction === "desc" ? desc : asc)(resolveColumn(this.table, column))));
987
+ if (limitValue !== void 0) pageable.limit(limitValue);
988
+ if (offsetValue !== void 0) pageable.offset(offsetValue);
989
+ return target;
990
+ }
991
+ selectFromTable() {
992
+ const fields = this.options.selectFields;
993
+ const selection = fields && fields.length > 0 ? Object.fromEntries(fields.map((field) => [field, resolveColumn(this.table, field)])) : void 0;
994
+ return this.resolveDrizzleDatabase().select(selection)?.from?.(this.table);
995
+ }
996
+ resolveDrizzleDatabase() {
997
+ const advancedAdapter = this.adapter;
998
+ const handle = advancedAdapter.executor?.({ trx: this.options.trx }) ?? advancedAdapter.getDatabase?.();
999
+ if (!handle || typeof handle.select !== "function") throw new Error(`${this.modelClass.name}: the configured adapter exposes no Drizzle database; pass a query instead: toDrizzle(db.select().from(table)).`);
1000
+ return handle;
1001
+ }
1002
+ async aggregate(fn, field) {
1003
+ const advancedAdapter = this.adapter;
1004
+ if (typeof advancedAdapter.aggregateAdvanced !== "function") throw new Error(`${this.modelClass.name}: ${fn}() needs an adapter that implements aggregateAdvanced.`);
1005
+ const evaporated = this.filtersEvaporated();
1006
+ if (evaporated && fn !== "sum") return null;
1007
+ const conditions = evaporated ? [{
1008
+ type: "simple",
1009
+ field,
1010
+ operator: "in",
1011
+ value: []
1012
+ }] : this.effectiveConditions();
1013
+ return advancedAdapter.aggregateAdvanced(this.table, fn, field, conditions, { trx: this.options.trx });
1014
+ }
887
1015
  async paginate(pageOrOptions = 1, perPageArg = 15) {
888
1016
  const page = typeof pageOrOptions === "object" ? pageOrOptions.page ?? 1 : pageOrOptions;
889
1017
  const perPage = typeof pageOrOptions === "object" ? pageOrOptions.perPage ?? 15 : perPageArg;
@@ -1047,8 +1175,9 @@ var QueryBuilder = class QueryBuilder {
1047
1175
  const advancedAdapter = this.adapter;
1048
1176
  const limit = overrides.limit ?? this.options.limitValue;
1049
1177
  const offset = overrides.offset ?? this.options.offsetValue;
1178
+ const orderBy = overrides.orderBy ?? this.options.orderBy;
1050
1179
  if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.effectiveConditions(), {
1051
- orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
1180
+ orderBy: orderBy.length > 0 ? orderBy : void 0,
1052
1181
  limit,
1053
1182
  offset,
1054
1183
  select: overrides.select ?? this.options.selectFields
@@ -1057,7 +1186,7 @@ var QueryBuilder = class QueryBuilder {
1057
1186
  if (simpleWhere === null && this.hasConditions()) throw new Error(`${this.modelClass.name}: this query uses conditions the configured adapter cannot express (it implements neither findManyAdvanced nor countAdvanced). Running it would drop every condition, including any global scope, and return unfiltered rows.`);
1058
1187
  return this.adapter.findMany(this.table, {
1059
1188
  where: simpleWhere ?? void 0,
1060
- orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
1189
+ orderBy: orderBy.length > 0 ? orderBy : void 0,
1061
1190
  limit,
1062
1191
  offset
1063
1192
  }, { trx: this.options.trx });
@@ -1741,8 +1870,15 @@ var Model = class Model {
1741
1870
  /**
1742
1871
  * A raw Drizzle builder starting at `select().from(table)`. Carries no model
1743
1872
  * scopes, casts or accessors.
1873
+ *
1874
+ * @deprecated Reads soft-deleted rows and other tenants' rows. Use `Model.newQuery().toDrizzle()`
1875
+ * (or `toDrizzle(db.select().from(table))`), which keeps the scopes, or the builder's `sum`/`avg`/`min`/`max`/`exists`.
1744
1876
  */
1745
1877
  static query(db) {
1878
+ warnDeprecated("model-query-raw", `${this.name}.query`, "It skips every global scope, SoftDeletes included. Use newQuery().toDrizzle(), or toDrizzle(query) for joins.", {
1879
+ since: "2.11.0",
1880
+ removedIn: "3.0.0"
1881
+ });
1746
1882
  const table = this.resolveTable();
1747
1883
  if (db) {
1748
1884
  const selectBuilder = db.select();
@@ -2785,6 +2921,32 @@ function singleFlight(factory) {
2785
2921
  };
2786
2922
  }
2787
2923
  //#endregion
2924
+ //#region src/connection-context.ts
2925
+ /**
2926
+ * One per factory. The context is kept rather than passed, because resolutions
2927
+ * also run inside memoized flights and admin clients that no `configureOrm()`
2928
+ * call reaches.
2929
+ */
2930
+ function connectionSettings() {
2931
+ let kept;
2932
+ const resolved = /* @__PURE__ */ new Map();
2933
+ return {
2934
+ resolve(value) {
2935
+ if (typeof value !== "function") return value;
2936
+ const result = value(kept);
2937
+ resolved.set(value, result);
2938
+ return result;
2939
+ },
2940
+ remember(context) {
2941
+ if (!context || context === kept) return false;
2942
+ kept = context;
2943
+ const stale = [...resolved].some(([resolver, previous]) => resolver(context) !== previous);
2944
+ resolved.clear();
2945
+ return stale;
2946
+ }
2947
+ };
2948
+ }
2949
+ //#endregion
2788
2950
  //#region src/postgres.ts
2789
2951
  async function loadPostgresModules() {
2790
2952
  try {
@@ -2810,8 +2972,9 @@ function createPostgresDatabase(options) {
2810
2972
  let client;
2811
2973
  let activeKey;
2812
2974
  const callSite = (/* @__PURE__ */ new Error()).stack;
2975
+ const settings = connectionSettings();
2813
2976
  function resolveConnectionString() {
2814
- const resolved = (typeof connectionString === "function" ? connectionString() : connectionString) ?? process.env.DATABASE_URL;
2977
+ const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
2815
2978
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
2816
2979
  return resolved;
2817
2980
  }
@@ -2891,7 +3054,11 @@ function createPostgresDatabase(options) {
2891
3054
  if (key) releaseActiveConnection(key, closeDatabase);
2892
3055
  }
2893
3056
  }
2894
- async function configureOrm() {
3057
+ async function configureOrm(context) {
3058
+ if (settings.remember(context)) {
3059
+ await closeDatabase();
3060
+ migrations.reset();
3061
+ }
2895
3062
  const db = await database.get();
2896
3063
  DrizzleAdapter.configure(db);
2897
3064
  }
@@ -2929,6 +3096,9 @@ function createPostgresDatabase(options) {
2929
3096
  reapplyingAfterReset = true;
2930
3097
  return migrations.get();
2931
3098
  }
3099
+ function hasMigrations() {
3100
+ return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3101
+ }
2932
3102
  async function migrationStatus() {
2933
3103
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
2934
3104
  if (localMigrations.length === 0) return [];
@@ -2941,7 +3111,8 @@ function createPostgresDatabase(options) {
2941
3111
  configureOrm,
2942
3112
  seedDatabase,
2943
3113
  resetDatabase,
2944
- migrationStatus
3114
+ migrationStatus,
3115
+ hasMigrations
2945
3116
  };
2946
3117
  }
2947
3118
  //#endregion
@@ -2970,8 +3141,9 @@ function createMySqlDatabase(options) {
2970
3141
  let client;
2971
3142
  let activeKey;
2972
3143
  const callSite = (/* @__PURE__ */ new Error()).stack;
3144
+ const settings = connectionSettings();
2973
3145
  function resolveConnectionString() {
2974
- const resolved = (typeof connectionString === "function" ? connectionString() : connectionString) ?? process.env.DATABASE_URL;
3146
+ const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
2975
3147
  if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
2976
3148
  return resolved;
2977
3149
  }
@@ -3053,7 +3225,11 @@ function createMySqlDatabase(options) {
3053
3225
  if (key) releaseActiveConnection(key, closeDatabase);
3054
3226
  }
3055
3227
  }
3056
- async function configureOrm() {
3228
+ async function configureOrm(context) {
3229
+ if (settings.remember(context)) {
3230
+ await closeDatabase();
3231
+ migrations.reset();
3232
+ }
3057
3233
  const db = await database.get();
3058
3234
  DrizzleAdapter.configure(db);
3059
3235
  }
@@ -3100,6 +3276,9 @@ function createMySqlDatabase(options) {
3100
3276
  reapplyingAfterReset = true;
3101
3277
  return migrations.get();
3102
3278
  }
3279
+ function hasMigrations() {
3280
+ return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3281
+ }
3103
3282
  async function migrationStatus() {
3104
3283
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3105
3284
  if (localMigrations.length === 0) return [];
@@ -3112,7 +3291,8 @@ function createMySqlDatabase(options) {
3112
3291
  configureOrm,
3113
3292
  seedDatabase,
3114
3293
  resetDatabase,
3115
- migrationStatus
3294
+ migrationStatus,
3295
+ hasMigrations
3116
3296
  };
3117
3297
  }
3118
3298
  async function closePool(pool) {
@@ -3184,8 +3364,9 @@ function createSqliteDatabase(options) {
3184
3364
  let sqliteClient;
3185
3365
  let activeKey;
3186
3366
  const callSite = (/* @__PURE__ */ new Error()).stack;
3367
+ const settings = connectionSettings();
3187
3368
  function resolveFilename() {
3188
- const value = typeof filename === "function" ? filename() : filename;
3369
+ const value = settings.resolve(filename);
3189
3370
  if (value != null) {
3190
3371
  assertNotConnectionUri(value, "the \"filename\" option");
3191
3372
  return value;
@@ -3287,13 +3468,20 @@ function createSqliteDatabase(options) {
3287
3468
  reapplyingAfterReset = true;
3288
3469
  return migrations.get();
3289
3470
  },
3471
+ hasMigrations() {
3472
+ return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3473
+ },
3290
3474
  async migrationStatus() {
3291
3475
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3292
3476
  if (localMigrations.length === 0) return [];
3293
3477
  await database.get();
3294
3478
  return buildMigrationStatus(localMigrations, readAppliedMigrations());
3295
3479
  },
3296
- async configureOrm() {
3480
+ async configureOrm(context) {
3481
+ if (settings.remember(context)) {
3482
+ await closeDatabase();
3483
+ migrations.reset();
3484
+ }
3297
3485
  const db = await database.get();
3298
3486
  await migrations.get();
3299
3487
  DrizzleAdapter.configure(db);
@@ -3343,6 +3531,9 @@ function createD1Database(options) {
3343
3531
  async resetDatabase() {
3344
3532
  throw new Error("D1 databases are reset with wrangler, not at runtime: delete and recreate the database (`wrangler d1 delete` / `wrangler d1 create`), then re-apply migrations with `wrangler d1 migrations apply`.");
3345
3533
  },
3534
+ hasMigrations() {
3535
+ return false;
3536
+ },
3346
3537
  async migrationStatus() {
3347
3538
  throw new Error("Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead.");
3348
3539
  }
@@ -3369,9 +3560,10 @@ function createAwsDataApiDatabase(options) {
3369
3560
  let client;
3370
3561
  let activeKey;
3371
3562
  const callSite = (/* @__PURE__ */ new Error()).stack;
3563
+ const settings = connectionSettings();
3372
3564
  function resolveConnection() {
3373
3565
  const resolveValue = (value, envKey) => {
3374
- return (typeof value === "function" ? value() : value) ?? process.env[envKey];
3566
+ return settings.resolve(value) ?? process.env[envKey];
3375
3567
  };
3376
3568
  const resolvedDatabase = resolveValue(database, "DATABASE_NAME");
3377
3569
  const resolvedResourceArn = resolveValue(resourceArn, "DATABASE_RESOURCE_ARN");
@@ -3439,7 +3631,11 @@ function createAwsDataApiDatabase(options) {
3439
3631
  if (key) releaseActiveConnection(key, closeDatabase);
3440
3632
  }
3441
3633
  }
3442
- async function configureOrm() {
3634
+ async function configureOrm(context) {
3635
+ if (settings.remember(context)) {
3636
+ await closeDatabase();
3637
+ migrations.reset();
3638
+ }
3443
3639
  const db = await databaseHandle.get();
3444
3640
  DrizzleAdapter.configure(db);
3445
3641
  }
@@ -3485,6 +3681,9 @@ function createAwsDataApiDatabase(options) {
3485
3681
  throw error;
3486
3682
  }
3487
3683
  }
3684
+ function hasMigrations() {
3685
+ return listLocalMigrations(resolvedMigrationsFolder).length > 0;
3686
+ }
3488
3687
  async function migrationStatus() {
3489
3688
  const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3490
3689
  if (localMigrations.length === 0) return [];
@@ -3497,7 +3696,8 @@ function createAwsDataApiDatabase(options) {
3497
3696
  configureOrm,
3498
3697
  seedDatabase,
3499
3698
  resetDatabase,
3500
- migrationStatus
3699
+ migrationStatus,
3700
+ hasMigrations
3501
3701
  };
3502
3702
  }
3503
3703
  function isMissingTrackerTableError(error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.10.1",
3
+ "version": "2.11.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/instance-guard.ts",