@guren/orm 2.10.0 → 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.
- package/dist/index.d.ts +108 -12
- package/dist/index.js +286 -43
- 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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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,8 +1,21 @@
|
|
|
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";
|
|
5
5
|
import { readdir } from "node:fs/promises";
|
|
6
|
+
//#region src/hot-reload-runtime.ts
|
|
7
|
+
/**
|
|
8
|
+
* `bun --hot` re-runs the module graph in-process: module-level state resets
|
|
9
|
+
* while `globalThis` survives, so state parked there has to tell a
|
|
10
|
+
* re-evaluation from a new participant. `bun --watch` restarts the process
|
|
11
|
+
* instead, and this answers for no other in-process re-evaluator (a Vite SSR
|
|
12
|
+
* runner, `vi.resetModules()`). Twin of
|
|
13
|
+
* `packages/server/src/hot-reload/hot-disposables.ts` — keep the two in step.
|
|
14
|
+
*/
|
|
15
|
+
function isHotReloadRuntime() {
|
|
16
|
+
return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
6
19
|
//#region src/instance-guard.ts
|
|
7
20
|
/**
|
|
8
21
|
* Detects multiple loaded copies of @guren/orm in one process. Model and
|
|
@@ -12,20 +25,37 @@ import { readdir } from "node:fs/promises";
|
|
|
12
25
|
*/
|
|
13
26
|
const INSTANCE_KEY = Symbol.for("guren.orm.loaded");
|
|
14
27
|
const globalScope = globalThis;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
28
|
+
/** Empty where a bundler shims `import.meta.url` away, which no copy can be told apart by. */
|
|
29
|
+
function moduleIdentity() {
|
|
30
|
+
return import.meta.url || void 0;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Counts this evaluation as a copy unless the same module URL already
|
|
34
|
+
* registered under `bun --hot`, which re-evaluates a file against a surviving
|
|
35
|
+
* `globalThis`. A bundle inlines both copies at one URL, so outside `--hot` a
|
|
36
|
+
* repeat is a duplicate rather than a reload. Any other in-process
|
|
37
|
+
* re-evaluator (a Vite SSR runner, `vi.resetModules()`) still counts.
|
|
38
|
+
*/
|
|
39
|
+
function registerOrmInstance(identity) {
|
|
40
|
+
const marker = globalScope[INSTANCE_KEY] ??= {
|
|
41
|
+
count: 0,
|
|
42
|
+
warned: false,
|
|
43
|
+
identities: /* @__PURE__ */ new Set()
|
|
44
|
+
};
|
|
45
|
+
const identities = marker.identities ??= /* @__PURE__ */ new Set();
|
|
46
|
+
if (identity !== void 0) {
|
|
47
|
+
if (identities.has(identity) && isHotReloadRuntime()) return;
|
|
48
|
+
identities.add(identity);
|
|
49
|
+
}
|
|
21
50
|
marker.count += 1;
|
|
22
51
|
const quiet = typeof process !== "undefined" && process.env.GUREN_QUIET_DUPLICATE_ORM === "1";
|
|
23
|
-
if (!marker.warned && !quiet) {
|
|
52
|
+
if (marker.count > 1 && !marker.warned && !quiet) {
|
|
24
53
|
marker.warned = true;
|
|
25
54
|
console.warn(`[guren/orm] ${marker.count} copies of @guren/orm are loaded in this process. Adapter configuration and model state are NOT shared between copies, so database access will fail with "database has not been configured" for models imported through the extra copy.
|
|
26
55
|
[guren/orm] This usually means mixed @guren/* versions (check \`bun pm ls | grep @guren\`). Fix it by aligning all @guren/* packages to the same release, e.g. \`bunx guren upgrade\` or updating every @guren/* entry in package.json together, then reinstalling. Set GUREN_QUIET_DUPLICATE_ORM=1 to silence this warning (e.g. monorepo dev where src and dist copies coexist by design).`);
|
|
27
56
|
}
|
|
28
57
|
}
|
|
58
|
+
registerOrmInstance(moduleIdentity());
|
|
29
59
|
//#endregion
|
|
30
60
|
//#region src/internal-keys.ts
|
|
31
61
|
/**
|
|
@@ -185,6 +215,31 @@ function toCount(value) {
|
|
|
185
215
|
const total = Number(value ?? 0);
|
|
186
216
|
return Number.isNaN(total) ? 0 : total;
|
|
187
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
|
+
}
|
|
188
243
|
function ensureDatabase() {
|
|
189
244
|
if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
|
|
190
245
|
return database;
|
|
@@ -493,6 +548,15 @@ const DrizzleAdapter = {
|
|
|
493
548
|
async countAdvanced(table, conditions, queryOptions) {
|
|
494
549
|
return toCount((await resolveList(withConditions(resolveExecutor(queryOptions).select({ value: count() }).from(table), table, conditions)))[0]?.value);
|
|
495
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
|
+
},
|
|
496
560
|
async countByAdvanced(table, field, conditions, queryOptions) {
|
|
497
561
|
const db = resolveExecutor(queryOptions);
|
|
498
562
|
const column = table[field];
|
|
@@ -587,6 +651,19 @@ function applyMutators(data, mutators) {
|
|
|
587
651
|
return result;
|
|
588
652
|
}
|
|
589
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
|
|
590
667
|
//#region src/GlobalScopeRegistry.ts
|
|
591
668
|
/** Registry for the named global scopes applied to every query on a model. */
|
|
592
669
|
var GlobalScopeRegistry = class GlobalScopeRegistry {
|
|
@@ -854,6 +931,87 @@ var QueryBuilder = class QueryBuilder {
|
|
|
854
931
|
}
|
|
855
932
|
return counts;
|
|
856
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
|
+
}
|
|
857
1015
|
async paginate(pageOrOptions = 1, perPageArg = 15) {
|
|
858
1016
|
const page = typeof pageOrOptions === "object" ? pageOrOptions.page ?? 1 : pageOrOptions;
|
|
859
1017
|
const perPage = typeof pageOrOptions === "object" ? pageOrOptions.perPage ?? 15 : perPageArg;
|
|
@@ -1017,8 +1175,9 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1017
1175
|
const advancedAdapter = this.adapter;
|
|
1018
1176
|
const limit = overrides.limit ?? this.options.limitValue;
|
|
1019
1177
|
const offset = overrides.offset ?? this.options.offsetValue;
|
|
1178
|
+
const orderBy = overrides.orderBy ?? this.options.orderBy;
|
|
1020
1179
|
if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.effectiveConditions(), {
|
|
1021
|
-
orderBy:
|
|
1180
|
+
orderBy: orderBy.length > 0 ? orderBy : void 0,
|
|
1022
1181
|
limit,
|
|
1023
1182
|
offset,
|
|
1024
1183
|
select: overrides.select ?? this.options.selectFields
|
|
@@ -1027,7 +1186,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1027
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.`);
|
|
1028
1187
|
return this.adapter.findMany(this.table, {
|
|
1029
1188
|
where: simpleWhere ?? void 0,
|
|
1030
|
-
orderBy:
|
|
1189
|
+
orderBy: orderBy.length > 0 ? orderBy : void 0,
|
|
1031
1190
|
limit,
|
|
1032
1191
|
offset
|
|
1033
1192
|
}, { trx: this.options.trx });
|
|
@@ -1711,8 +1870,15 @@ var Model = class Model {
|
|
|
1711
1870
|
/**
|
|
1712
1871
|
* A raw Drizzle builder starting at `select().from(table)`. Carries no model
|
|
1713
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`.
|
|
1714
1876
|
*/
|
|
1715
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
|
+
});
|
|
1716
1882
|
const table = this.resolveTable();
|
|
1717
1883
|
if (db) {
|
|
1718
1884
|
const selectBuilder = db.select();
|
|
@@ -2250,6 +2416,16 @@ function SoftDeletes(Base) {
|
|
|
2250
2416
|
}
|
|
2251
2417
|
//#endregion
|
|
2252
2418
|
//#region src/active-connections.ts
|
|
2419
|
+
/**
|
|
2420
|
+
* Closes the database client a previous module evaluation left open.
|
|
2421
|
+
*
|
|
2422
|
+
* `bun --hot` re-runs the module graph in-process: a `create*Database()`
|
|
2423
|
+
* factory's cached client resets but its connection leaks, one per reload.
|
|
2424
|
+
* Bun exposes no `import.meta.hot` under `--hot` (checked on 1.3.14), so the
|
|
2425
|
+
* teardown is parked on `globalThis`, which survives re-evaluation. Handles are
|
|
2426
|
+
* keyed by caller file + target, not line, so two handles built in one file
|
|
2427
|
+
* against one database share a key; give them separate modules.
|
|
2428
|
+
*/
|
|
2253
2429
|
const REGISTRY_KEY = Symbol.for("guren.orm.activeConnections");
|
|
2254
2430
|
/**
|
|
2255
2431
|
* Awaiting the teardown is the back-pressure that keeps a burst of reloads from
|
|
@@ -2265,10 +2441,6 @@ function getRegistry() {
|
|
|
2265
2441
|
scope[REGISTRY_KEY] = registry;
|
|
2266
2442
|
return registry;
|
|
2267
2443
|
}
|
|
2268
|
-
/** `bun --watch` restarts the process instead, so `--hot` is the only mode that leaks. */
|
|
2269
|
-
function isHotReloadRuntime() {
|
|
2270
|
-
return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
|
|
2271
|
-
}
|
|
2272
2444
|
/** Both match one character, so neither can backtrack the way `\s*` in a pattern can. */
|
|
2273
2445
|
const WHITESPACE = /\s/;
|
|
2274
2446
|
const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
@@ -2749,6 +2921,32 @@ function singleFlight(factory) {
|
|
|
2749
2921
|
};
|
|
2750
2922
|
}
|
|
2751
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
|
|
2752
2950
|
//#region src/postgres.ts
|
|
2753
2951
|
async function loadPostgresModules() {
|
|
2754
2952
|
try {
|
|
@@ -2774,8 +2972,9 @@ function createPostgresDatabase(options) {
|
|
|
2774
2972
|
let client;
|
|
2775
2973
|
let activeKey;
|
|
2776
2974
|
const callSite = (/* @__PURE__ */ new Error()).stack;
|
|
2975
|
+
const settings = connectionSettings();
|
|
2777
2976
|
function resolveConnectionString() {
|
|
2778
|
-
const resolved = (
|
|
2977
|
+
const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
|
|
2779
2978
|
if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
|
|
2780
2979
|
return resolved;
|
|
2781
2980
|
}
|
|
@@ -2855,7 +3054,11 @@ function createPostgresDatabase(options) {
|
|
|
2855
3054
|
if (key) releaseActiveConnection(key, closeDatabase);
|
|
2856
3055
|
}
|
|
2857
3056
|
}
|
|
2858
|
-
async function configureOrm() {
|
|
3057
|
+
async function configureOrm(context) {
|
|
3058
|
+
if (settings.remember(context)) {
|
|
3059
|
+
await closeDatabase();
|
|
3060
|
+
migrations.reset();
|
|
3061
|
+
}
|
|
2859
3062
|
const db = await database.get();
|
|
2860
3063
|
DrizzleAdapter.configure(db);
|
|
2861
3064
|
}
|
|
@@ -2893,6 +3096,9 @@ function createPostgresDatabase(options) {
|
|
|
2893
3096
|
reapplyingAfterReset = true;
|
|
2894
3097
|
return migrations.get();
|
|
2895
3098
|
}
|
|
3099
|
+
function hasMigrations() {
|
|
3100
|
+
return listLocalMigrations(resolvedMigrationsFolder).length > 0;
|
|
3101
|
+
}
|
|
2896
3102
|
async function migrationStatus() {
|
|
2897
3103
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
2898
3104
|
if (localMigrations.length === 0) return [];
|
|
@@ -2905,7 +3111,8 @@ function createPostgresDatabase(options) {
|
|
|
2905
3111
|
configureOrm,
|
|
2906
3112
|
seedDatabase,
|
|
2907
3113
|
resetDatabase,
|
|
2908
|
-
migrationStatus
|
|
3114
|
+
migrationStatus,
|
|
3115
|
+
hasMigrations
|
|
2909
3116
|
};
|
|
2910
3117
|
}
|
|
2911
3118
|
//#endregion
|
|
@@ -2934,8 +3141,9 @@ function createMySqlDatabase(options) {
|
|
|
2934
3141
|
let client;
|
|
2935
3142
|
let activeKey;
|
|
2936
3143
|
const callSite = (/* @__PURE__ */ new Error()).stack;
|
|
3144
|
+
const settings = connectionSettings();
|
|
2937
3145
|
function resolveConnectionString() {
|
|
2938
|
-
const resolved = (
|
|
3146
|
+
const resolved = settings.resolve(connectionString) ?? process.env.DATABASE_URL;
|
|
2939
3147
|
if (!resolved) throw new Error("DATABASE_URL is not set and no connection string was provided.");
|
|
2940
3148
|
return resolved;
|
|
2941
3149
|
}
|
|
@@ -3017,7 +3225,11 @@ function createMySqlDatabase(options) {
|
|
|
3017
3225
|
if (key) releaseActiveConnection(key, closeDatabase);
|
|
3018
3226
|
}
|
|
3019
3227
|
}
|
|
3020
|
-
async function configureOrm() {
|
|
3228
|
+
async function configureOrm(context) {
|
|
3229
|
+
if (settings.remember(context)) {
|
|
3230
|
+
await closeDatabase();
|
|
3231
|
+
migrations.reset();
|
|
3232
|
+
}
|
|
3021
3233
|
const db = await database.get();
|
|
3022
3234
|
DrizzleAdapter.configure(db);
|
|
3023
3235
|
}
|
|
@@ -3064,6 +3276,9 @@ function createMySqlDatabase(options) {
|
|
|
3064
3276
|
reapplyingAfterReset = true;
|
|
3065
3277
|
return migrations.get();
|
|
3066
3278
|
}
|
|
3279
|
+
function hasMigrations() {
|
|
3280
|
+
return listLocalMigrations(resolvedMigrationsFolder).length > 0;
|
|
3281
|
+
}
|
|
3067
3282
|
async function migrationStatus() {
|
|
3068
3283
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3069
3284
|
if (localMigrations.length === 0) return [];
|
|
@@ -3076,7 +3291,8 @@ function createMySqlDatabase(options) {
|
|
|
3076
3291
|
configureOrm,
|
|
3077
3292
|
seedDatabase,
|
|
3078
3293
|
resetDatabase,
|
|
3079
|
-
migrationStatus
|
|
3294
|
+
migrationStatus,
|
|
3295
|
+
hasMigrations
|
|
3080
3296
|
};
|
|
3081
3297
|
}
|
|
3082
3298
|
async function closePool(pool) {
|
|
@@ -3086,35 +3302,41 @@ async function closePool(pool) {
|
|
|
3086
3302
|
}
|
|
3087
3303
|
//#endregion
|
|
3088
3304
|
//#region src/sqlite.ts
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
}
|
|
3305
|
+
const MEMORY = { kind: "memory" };
|
|
3306
|
+
const UNRESOLVABLE = { kind: "unresolvable" };
|
|
3092
3307
|
/**
|
|
3093
|
-
*
|
|
3094
|
-
*
|
|
3095
|
-
*
|
|
3096
|
-
*
|
|
3097
|
-
*
|
|
3308
|
+
* What `dbPath` opens. `file:` URI support is compile-time `SQLITE_USE_URI`
|
|
3309
|
+
* (measured: on for Bun/macOS via system libsqlite3, off in Bun's Linux build,
|
|
3310
|
+
* which opens `file:local.db` and `file::memory:` as literal files), so only an
|
|
3311
|
+
* unresolvable URI reaches `new Database()`, and parsing follows
|
|
3312
|
+
* https://sqlite.org/uri.html, not WHATWG (`/local.db` vs the cwd).
|
|
3098
3313
|
*/
|
|
3099
|
-
function
|
|
3100
|
-
if (
|
|
3101
|
-
if (!dbPath.startsWith("file:")) return
|
|
3314
|
+
function sqliteTarget(dbPath) {
|
|
3315
|
+
if (dbPath === ":memory:" || dbPath === "") return MEMORY;
|
|
3316
|
+
if (!dbPath.startsWith("file:")) return {
|
|
3317
|
+
kind: "file",
|
|
3318
|
+
path: resolve(dbPath)
|
|
3319
|
+
};
|
|
3102
3320
|
let rest = dbPath.slice(5);
|
|
3103
3321
|
if (rest.startsWith("//")) {
|
|
3104
3322
|
const pathStart = rest.indexOf("/", 2);
|
|
3105
3323
|
const authority = pathStart === -1 ? rest.slice(2) : rest.slice(2, pathStart);
|
|
3106
|
-
if (authority !== "" && authority !== "localhost") return
|
|
3324
|
+
if (authority !== "" && authority !== "localhost") return UNRESOLVABLE;
|
|
3107
3325
|
rest = pathStart === -1 ? "" : rest.slice(pathStart);
|
|
3108
3326
|
}
|
|
3109
3327
|
const marker = rest.search(/[?#]/);
|
|
3110
3328
|
const encodedPath = marker === -1 ? rest : rest.slice(0, marker);
|
|
3111
3329
|
const query = marker !== -1 && rest[marker] === "?" ? rest.slice(marker + 1).split("#")[0] : "";
|
|
3112
|
-
if (query !== "") throw new Error(`createSqliteDatabase() cannot honour the URI parameters in ${dbPath} (?${query}). They are only read by a sqlite built with SQLITE_USE_URI, which Bun provides on some platforms and not others, so this driver resolves the URI to a path itself. Pass a plain path, and set the behaviour those parameters asked for in code.`);
|
|
3113
|
-
if (encodedPath === "") return
|
|
3330
|
+
if (query !== "") throw new Error(`createSqliteDatabase() cannot honour the URI parameters in ${dbPath} (?${query}). They are only read by a sqlite built with SQLITE_USE_URI, which Bun provides on some platforms and not others, so this driver resolves the URI to a path itself. Pass a plain path or ":memory:", and set the behaviour those parameters asked for in code.`);
|
|
3331
|
+
if (encodedPath === "") return UNRESOLVABLE;
|
|
3114
3332
|
try {
|
|
3115
|
-
|
|
3333
|
+
const path = decodeURIComponent(encodedPath);
|
|
3334
|
+
return path === ":memory:" ? MEMORY : {
|
|
3335
|
+
kind: "file",
|
|
3336
|
+
path: resolve(path)
|
|
3337
|
+
};
|
|
3116
3338
|
} catch {
|
|
3117
|
-
return;
|
|
3339
|
+
return UNRESOLVABLE;
|
|
3118
3340
|
}
|
|
3119
3341
|
}
|
|
3120
3342
|
/**
|
|
@@ -3142,8 +3364,9 @@ function createSqliteDatabase(options) {
|
|
|
3142
3364
|
let sqliteClient;
|
|
3143
3365
|
let activeKey;
|
|
3144
3366
|
const callSite = (/* @__PURE__ */ new Error()).stack;
|
|
3367
|
+
const settings = connectionSettings();
|
|
3145
3368
|
function resolveFilename() {
|
|
3146
|
-
const value =
|
|
3369
|
+
const value = settings.resolve(filename);
|
|
3147
3370
|
if (value != null) {
|
|
3148
3371
|
assertNotConnectionUri(value, "the \"filename\" option");
|
|
3149
3372
|
return value;
|
|
@@ -3157,7 +3380,8 @@ function createSqliteDatabase(options) {
|
|
|
3157
3380
|
}
|
|
3158
3381
|
const database = singleFlight(async () => {
|
|
3159
3382
|
const dbPath = resolveFilename();
|
|
3160
|
-
const
|
|
3383
|
+
const target = sqliteTarget(dbPath);
|
|
3384
|
+
const dbFile = target.kind === "file" ? target.path : void 0;
|
|
3161
3385
|
if (dbFile) {
|
|
3162
3386
|
const { mkdirSync } = await import("node:fs");
|
|
3163
3387
|
const { dirname } = await import("node:path");
|
|
@@ -3167,7 +3391,7 @@ function createSqliteDatabase(options) {
|
|
|
3167
3391
|
}
|
|
3168
3392
|
const { Database } = await import("bun:sqlite");
|
|
3169
3393
|
const { drizzle } = await import("drizzle-orm/bun-sqlite");
|
|
3170
|
-
const sqlite = new Database(dbFile ?? dbPath);
|
|
3394
|
+
const sqlite = new Database(target.kind === "memory" ? ":memory:" : dbFile ?? dbPath);
|
|
3171
3395
|
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
3172
3396
|
sqliteClient = sqlite;
|
|
3173
3397
|
const handle = drizzle({
|
|
@@ -3244,13 +3468,20 @@ function createSqliteDatabase(options) {
|
|
|
3244
3468
|
reapplyingAfterReset = true;
|
|
3245
3469
|
return migrations.get();
|
|
3246
3470
|
},
|
|
3471
|
+
hasMigrations() {
|
|
3472
|
+
return listLocalMigrations(resolvedMigrationsFolder).length > 0;
|
|
3473
|
+
},
|
|
3247
3474
|
async migrationStatus() {
|
|
3248
3475
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3249
3476
|
if (localMigrations.length === 0) return [];
|
|
3250
3477
|
await database.get();
|
|
3251
3478
|
return buildMigrationStatus(localMigrations, readAppliedMigrations());
|
|
3252
3479
|
},
|
|
3253
|
-
async configureOrm() {
|
|
3480
|
+
async configureOrm(context) {
|
|
3481
|
+
if (settings.remember(context)) {
|
|
3482
|
+
await closeDatabase();
|
|
3483
|
+
migrations.reset();
|
|
3484
|
+
}
|
|
3254
3485
|
const db = await database.get();
|
|
3255
3486
|
await migrations.get();
|
|
3256
3487
|
DrizzleAdapter.configure(db);
|
|
@@ -3300,6 +3531,9 @@ function createD1Database(options) {
|
|
|
3300
3531
|
async resetDatabase() {
|
|
3301
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`.");
|
|
3302
3533
|
},
|
|
3534
|
+
hasMigrations() {
|
|
3535
|
+
return false;
|
|
3536
|
+
},
|
|
3303
3537
|
async migrationStatus() {
|
|
3304
3538
|
throw new Error("Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead.");
|
|
3305
3539
|
}
|
|
@@ -3326,9 +3560,10 @@ function createAwsDataApiDatabase(options) {
|
|
|
3326
3560
|
let client;
|
|
3327
3561
|
let activeKey;
|
|
3328
3562
|
const callSite = (/* @__PURE__ */ new Error()).stack;
|
|
3563
|
+
const settings = connectionSettings();
|
|
3329
3564
|
function resolveConnection() {
|
|
3330
3565
|
const resolveValue = (value, envKey) => {
|
|
3331
|
-
return (
|
|
3566
|
+
return settings.resolve(value) ?? process.env[envKey];
|
|
3332
3567
|
};
|
|
3333
3568
|
const resolvedDatabase = resolveValue(database, "DATABASE_NAME");
|
|
3334
3569
|
const resolvedResourceArn = resolveValue(resourceArn, "DATABASE_RESOURCE_ARN");
|
|
@@ -3396,7 +3631,11 @@ function createAwsDataApiDatabase(options) {
|
|
|
3396
3631
|
if (key) releaseActiveConnection(key, closeDatabase);
|
|
3397
3632
|
}
|
|
3398
3633
|
}
|
|
3399
|
-
async function configureOrm() {
|
|
3634
|
+
async function configureOrm(context) {
|
|
3635
|
+
if (settings.remember(context)) {
|
|
3636
|
+
await closeDatabase();
|
|
3637
|
+
migrations.reset();
|
|
3638
|
+
}
|
|
3400
3639
|
const db = await databaseHandle.get();
|
|
3401
3640
|
DrizzleAdapter.configure(db);
|
|
3402
3641
|
}
|
|
@@ -3442,6 +3681,9 @@ function createAwsDataApiDatabase(options) {
|
|
|
3442
3681
|
throw error;
|
|
3443
3682
|
}
|
|
3444
3683
|
}
|
|
3684
|
+
function hasMigrations() {
|
|
3685
|
+
return listLocalMigrations(resolvedMigrationsFolder).length > 0;
|
|
3686
|
+
}
|
|
3445
3687
|
async function migrationStatus() {
|
|
3446
3688
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3447
3689
|
if (localMigrations.length === 0) return [];
|
|
@@ -3454,7 +3696,8 @@ function createAwsDataApiDatabase(options) {
|
|
|
3454
3696
|
configureOrm,
|
|
3455
3697
|
seedDatabase,
|
|
3456
3698
|
resetDatabase,
|
|
3457
|
-
migrationStatus
|
|
3699
|
+
migrationStatus,
|
|
3700
|
+
hasMigrations
|
|
3458
3701
|
};
|
|
3459
3702
|
}
|
|
3460
3703
|
function isMissingTrackerTableError(error) {
|