@guren/orm 1.0.0-rc.14 → 1.0.0-rc.16
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 +38 -2
- package/dist/index.js +263 -15
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1150,7 +1150,22 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1150
1150
|
* const activeUsersWithPosts = await User.with('posts', { status: 'active' })
|
|
1151
1151
|
*/
|
|
1152
1152
|
static with<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>): Promise<Array<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
1153
|
-
/**
|
|
1153
|
+
/**
|
|
1154
|
+
* Fetch records with related record counts attached as `${name}Count`.
|
|
1155
|
+
* Counts hasMany/hasOne/morphMany children per record without attaching
|
|
1156
|
+
* the related rows themselves; belongsTo yields 0 or 1.
|
|
1157
|
+
*
|
|
1158
|
+
* @example
|
|
1159
|
+
* const users = await User.withCount('posts')
|
|
1160
|
+
* users[0].postsCount // number
|
|
1161
|
+
*/
|
|
1162
|
+
static withCount<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>): Promise<Array<TRecordFor<T> & RelationCountPick<K | readonly K[]>>>;
|
|
1163
|
+
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1164
|
+
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
1165
|
+
/**
|
|
1166
|
+
* @internal Used by QueryBuilder for eager loading.
|
|
1167
|
+
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
1168
|
+
*/
|
|
1154
1169
|
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
1155
1170
|
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition): Promise<void>;
|
|
1156
1171
|
protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition): Promise<void>;
|
|
@@ -1177,6 +1192,9 @@ type RelationNameUnion<Names> = Names extends readonly (infer Items)[] ? Items :
|
|
|
1177
1192
|
type RelationTypePick<T extends typeof Model, Names> = RelationNameUnion<Names> extends infer Keys ? Keys extends string ? {
|
|
1178
1193
|
[K in Keys & keyof RelationTypesFor<T>]: RelationTypesFor<T>[K];
|
|
1179
1194
|
} : {} : {};
|
|
1195
|
+
type RelationCountPick<Names> = {
|
|
1196
|
+
[K in RelationNameUnion<Names> & string as `${K}Count`]: number;
|
|
1197
|
+
};
|
|
1180
1198
|
interface TransactionModelScope<T extends typeof Model> {
|
|
1181
1199
|
readonly trx: TransactionHandle;
|
|
1182
1200
|
all(): Promise<TRecordFor<T>[]>;
|
|
@@ -1409,6 +1427,12 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
|
1409
1427
|
*/
|
|
1410
1428
|
declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
|
|
1411
1429
|
|
|
1430
|
+
interface MigrationStatusEntry {
|
|
1431
|
+
name: string;
|
|
1432
|
+
applied: boolean;
|
|
1433
|
+
appliedAt: Date | null;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1412
1436
|
type ConnectionResolver$2 = string | (() => string | undefined);
|
|
1413
1437
|
interface PostgresDatabaseOptions {
|
|
1414
1438
|
migrationsFolder: string | URL;
|
|
@@ -1428,6 +1452,10 @@ interface PostgresDatabase {
|
|
|
1428
1452
|
closeDatabase(): Promise<void>;
|
|
1429
1453
|
configureOrm(): Promise<void>;
|
|
1430
1454
|
seedDatabase(): Promise<void>;
|
|
1455
|
+
/** Drops the public schema (and the drizzle tracker schema) so migrations can be re-applied from scratch. */
|
|
1456
|
+
resetDatabase(): Promise<void>;
|
|
1457
|
+
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1458
|
+
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1431
1459
|
}
|
|
1432
1460
|
declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
|
|
1433
1461
|
|
|
@@ -1451,6 +1479,10 @@ interface MySqlDatabase {
|
|
|
1451
1479
|
closeDatabase(): Promise<void>;
|
|
1452
1480
|
configureOrm(): Promise<void>;
|
|
1453
1481
|
seedDatabase(): Promise<void>;
|
|
1482
|
+
/** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1483
|
+
resetDatabase(): Promise<void>;
|
|
1484
|
+
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1485
|
+
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1454
1486
|
}
|
|
1455
1487
|
declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
|
|
1456
1488
|
|
|
@@ -1473,6 +1505,10 @@ interface SqliteDatabase {
|
|
|
1473
1505
|
closeDatabase(): Promise<void>;
|
|
1474
1506
|
configureOrm(): Promise<void>;
|
|
1475
1507
|
seedDatabase(): Promise<void>;
|
|
1508
|
+
/** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1509
|
+
resetDatabase(): Promise<void>;
|
|
1510
|
+
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1511
|
+
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1476
1512
|
}
|
|
1477
1513
|
declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
|
|
1478
1514
|
|
|
@@ -1498,4 +1534,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1498
1534
|
/** Serialize an array of records. */
|
|
1499
1535
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1500
1536
|
|
|
1501
|
-
export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type CastType, DrizzleAdapter, 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, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PaginationMeta, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
|
1537
|
+
export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type CastType, DrizzleAdapter, 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, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PaginationMeta, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
package/dist/index.js
CHANGED
|
@@ -504,14 +504,14 @@ var QueryBuilder = class {
|
|
|
504
504
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
505
505
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
506
506
|
if (val !== void 0) {
|
|
507
|
-
this.addSimpleCondition(key, "=", val);
|
|
507
|
+
this.addSimpleCondition(key, Array.isArray(val) ? "in" : "=", val);
|
|
508
508
|
}
|
|
509
509
|
}
|
|
510
510
|
return this;
|
|
511
511
|
}
|
|
512
512
|
const field = fieldOrConditions;
|
|
513
513
|
if (arguments.length === 2) {
|
|
514
|
-
this.addSimpleCondition(field, "=", operatorOrValue);
|
|
514
|
+
this.addSimpleCondition(field, Array.isArray(operatorOrValue) ? "in" : "=", operatorOrValue);
|
|
515
515
|
} else {
|
|
516
516
|
this.addSimpleCondition(field, operatorOrValue, value);
|
|
517
517
|
}
|
|
@@ -522,13 +522,13 @@ var QueryBuilder = class {
|
|
|
522
522
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
523
523
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
524
524
|
if (val !== void 0) {
|
|
525
|
-
orConditions.push({ type: "simple", field: key, operator: "=", value: val });
|
|
525
|
+
orConditions.push({ type: "simple", field: key, operator: Array.isArray(val) ? "in" : "=", value: val });
|
|
526
526
|
}
|
|
527
527
|
}
|
|
528
528
|
} else {
|
|
529
529
|
const field = fieldOrConditions;
|
|
530
530
|
if (arguments.length === 2) {
|
|
531
|
-
orConditions.push({ type: "simple", field, operator: "=", value: operatorOrValue });
|
|
531
|
+
orConditions.push({ type: "simple", field, operator: Array.isArray(operatorOrValue) ? "in" : "=", value: operatorOrValue });
|
|
532
532
|
} else {
|
|
533
533
|
orConditions.push({ type: "simple", field, operator: operatorOrValue, value });
|
|
534
534
|
}
|
|
@@ -2101,35 +2101,141 @@ var Model = class _Model {
|
|
|
2101
2101
|
}
|
|
2102
2102
|
return copies;
|
|
2103
2103
|
}
|
|
2104
|
-
|
|
2105
|
-
|
|
2104
|
+
static async withCount(relations, where) {
|
|
2105
|
+
const records = where ? await this.where(where) : await this.all();
|
|
2106
|
+
if (!records.length) {
|
|
2107
|
+
return records;
|
|
2108
|
+
}
|
|
2109
|
+
const relationList = normalizeRelations(relations);
|
|
2110
|
+
const copies = records.map((record) => ({ ...record }));
|
|
2111
|
+
for (const relationName of relationList) {
|
|
2112
|
+
await this.loadRelationCountInto(copies, relationName);
|
|
2113
|
+
}
|
|
2114
|
+
return copies;
|
|
2115
|
+
}
|
|
2116
|
+
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
2117
|
+
static async loadRelationCountInto(records, relationName) {
|
|
2118
|
+
if (relationName.includes(".")) {
|
|
2119
|
+
throw new Error(`${this.name}: withCount does not support nested relation "${relationName}".`);
|
|
2120
|
+
}
|
|
2106
2121
|
const definition = this.getRelationDefinition(relationName);
|
|
2107
2122
|
if (!definition) {
|
|
2108
2123
|
throw new Error(`${this.name}: unknown relation "${relationName}".`);
|
|
2109
2124
|
}
|
|
2125
|
+
const countField = `${relationName}Count`;
|
|
2110
2126
|
switch (definition.type) {
|
|
2111
2127
|
case "hasMany":
|
|
2112
|
-
|
|
2128
|
+
case "hasOne": {
|
|
2129
|
+
const related = await resolveModelReference(definition.related);
|
|
2130
|
+
const { foreignKey, localKey } = definition;
|
|
2131
|
+
const values = Array.from(
|
|
2132
|
+
new Set(records.map((record) => record[localKey]).filter((value) => value != null))
|
|
2133
|
+
);
|
|
2134
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2135
|
+
if (values.length > 0) {
|
|
2136
|
+
const relatedRecords = await related.where({ [foreignKey]: values });
|
|
2137
|
+
for (const item of relatedRecords) {
|
|
2138
|
+
const key = item[foreignKey];
|
|
2139
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
for (const record of records) {
|
|
2143
|
+
record[countField] = counts.get(record[localKey]) ?? 0;
|
|
2144
|
+
}
|
|
2145
|
+
return;
|
|
2146
|
+
}
|
|
2147
|
+
case "morphMany": {
|
|
2148
|
+
const withRelation = records.map((record) => ({ ...record }));
|
|
2149
|
+
await this.loadRelationInto(withRelation, relationName);
|
|
2150
|
+
for (const [index, record] of records.entries()) {
|
|
2151
|
+
const value = withRelation[index]?.[relationName];
|
|
2152
|
+
record[countField] = Array.isArray(value) ? value.length : 0;
|
|
2153
|
+
}
|
|
2113
2154
|
return;
|
|
2155
|
+
}
|
|
2156
|
+
case "belongsTo": {
|
|
2157
|
+
const related = await resolveModelReference(definition.related);
|
|
2158
|
+
const { foreignKey, ownerKey } = definition;
|
|
2159
|
+
const values = Array.from(
|
|
2160
|
+
new Set(records.map((record) => record[foreignKey]).filter((value) => value != null))
|
|
2161
|
+
);
|
|
2162
|
+
const ownerKeys = /* @__PURE__ */ new Set();
|
|
2163
|
+
if (values.length > 0) {
|
|
2164
|
+
const owners = await related.where({ [ownerKey]: values });
|
|
2165
|
+
for (const owner of owners) {
|
|
2166
|
+
ownerKeys.add(owner[ownerKey]);
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
for (const record of records) {
|
|
2170
|
+
const key = record[foreignKey];
|
|
2171
|
+
record[countField] = key != null && ownerKeys.has(key) ? 1 : 0;
|
|
2172
|
+
}
|
|
2173
|
+
return;
|
|
2174
|
+
}
|
|
2175
|
+
default:
|
|
2176
|
+
throw new Error(
|
|
2177
|
+
`${this.name}: withCount does not support ${definition.type} relation "${relationName}".`
|
|
2178
|
+
);
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* @internal Used by QueryBuilder for eager loading.
|
|
2183
|
+
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
2184
|
+
*/
|
|
2185
|
+
static async loadRelationInto(records, relationName) {
|
|
2186
|
+
const [head, ...rest] = relationName.split(".");
|
|
2187
|
+
const definition = this.getRelationDefinition(head);
|
|
2188
|
+
if (!definition) {
|
|
2189
|
+
throw new Error(`${this.name}: unknown relation "${head}".`);
|
|
2190
|
+
}
|
|
2191
|
+
switch (definition.type) {
|
|
2192
|
+
case "hasMany":
|
|
2193
|
+
await this.loadHasMany(records, definition);
|
|
2194
|
+
break;
|
|
2114
2195
|
case "hasOne":
|
|
2115
2196
|
await this.loadHasOne(records, definition);
|
|
2116
|
-
|
|
2197
|
+
break;
|
|
2117
2198
|
case "belongsTo":
|
|
2118
2199
|
await this.loadBelongsTo(records, definition);
|
|
2119
|
-
|
|
2200
|
+
break;
|
|
2120
2201
|
case "belongsToMany":
|
|
2121
2202
|
await this.loadBelongsToMany(records, definition);
|
|
2122
|
-
|
|
2203
|
+
break;
|
|
2123
2204
|
case "hasManyThrough":
|
|
2124
2205
|
await this.loadHasManyThrough(records, definition);
|
|
2125
|
-
|
|
2206
|
+
break;
|
|
2126
2207
|
case "morphMany":
|
|
2127
2208
|
await this.loadMorphMany(records, definition);
|
|
2128
|
-
|
|
2209
|
+
break;
|
|
2129
2210
|
case "morphTo":
|
|
2130
2211
|
await this.loadMorphTo(records, definition);
|
|
2131
|
-
|
|
2212
|
+
break;
|
|
2213
|
+
}
|
|
2214
|
+
if (rest.length === 0) {
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
if (definition.type === "morphTo") {
|
|
2218
|
+
throw new Error(
|
|
2219
|
+
`${this.name}: nested eager loading through morphTo relation "${head}" is not supported.`
|
|
2220
|
+
);
|
|
2221
|
+
}
|
|
2222
|
+
const children = [];
|
|
2223
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2224
|
+
for (const record of records) {
|
|
2225
|
+
const value = record[head];
|
|
2226
|
+
const items = Array.isArray(value) ? value : value != null ? [value] : [];
|
|
2227
|
+
for (const item of items) {
|
|
2228
|
+
if (item && typeof item === "object" && !seen.has(item)) {
|
|
2229
|
+
seen.add(item);
|
|
2230
|
+
children.push(item);
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2132
2233
|
}
|
|
2234
|
+
if (children.length === 0) {
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
2237
|
+
const related = await resolveModelReference(definition.related);
|
|
2238
|
+
await related.loadRelationInto(children, rest.join("."));
|
|
2133
2239
|
}
|
|
2134
2240
|
static async loadHasMany(records, definition) {
|
|
2135
2241
|
const { foreignKey, localKey, name } = definition;
|
|
@@ -2473,6 +2579,33 @@ function warnIgnoredFlatSqlMigrations(migrationsFolder) {
|
|
|
2473
2579
|
);
|
|
2474
2580
|
}
|
|
2475
2581
|
}
|
|
2582
|
+
function listLocalMigrations(migrationsFolder) {
|
|
2583
|
+
if (!existsSync(migrationsFolder)) {
|
|
2584
|
+
return [];
|
|
2585
|
+
}
|
|
2586
|
+
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));
|
|
2587
|
+
}
|
|
2588
|
+
function buildMigrationStatus(localMigrations, appliedRows) {
|
|
2589
|
+
const appliedByName = /* @__PURE__ */ new Map();
|
|
2590
|
+
for (const row of appliedRows) {
|
|
2591
|
+
if (row.name) {
|
|
2592
|
+
appliedByName.set(row.name, row);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
return localMigrations.map((migration) => {
|
|
2596
|
+
const row = appliedByName.get(migration.name);
|
|
2597
|
+
let appliedAt = null;
|
|
2598
|
+
if (row?.appliedAt) {
|
|
2599
|
+
const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
|
|
2600
|
+
appliedAt = Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
2601
|
+
}
|
|
2602
|
+
return {
|
|
2603
|
+
name: migration.name,
|
|
2604
|
+
applied: row !== void 0,
|
|
2605
|
+
appliedAt
|
|
2606
|
+
};
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2476
2609
|
|
|
2477
2610
|
// src/seeder.ts
|
|
2478
2611
|
import { readdir } from "fs/promises";
|
|
@@ -2625,12 +2758,49 @@ function createPostgresDatabase(options) {
|
|
|
2625
2758
|
const db = await getDatabase();
|
|
2626
2759
|
await runSeeders(db, resolvedSeedersFolder);
|
|
2627
2760
|
}
|
|
2761
|
+
async function withAdminClient(callback) {
|
|
2762
|
+
const adminClient = postgres(resolveConnectionString(), {
|
|
2763
|
+
max: 1,
|
|
2764
|
+
...clientOptions
|
|
2765
|
+
});
|
|
2766
|
+
try {
|
|
2767
|
+
return await callback(adminClient);
|
|
2768
|
+
} finally {
|
|
2769
|
+
await adminClient.end({ timeout: 0 });
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
async function resetDatabase() {
|
|
2773
|
+
await withAdminClient(async (adminClient) => {
|
|
2774
|
+
await adminClient.unsafe("DROP SCHEMA IF EXISTS public CASCADE");
|
|
2775
|
+
await adminClient.unsafe("CREATE SCHEMA public");
|
|
2776
|
+
await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
|
|
2777
|
+
});
|
|
2778
|
+
migrationsPromise = void 0;
|
|
2779
|
+
}
|
|
2780
|
+
async function migrationStatus() {
|
|
2781
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
2782
|
+
if (localMigrations.length === 0) return [];
|
|
2783
|
+
const appliedRows = await withAdminClient(async (adminClient) => {
|
|
2784
|
+
try {
|
|
2785
|
+
const rows = await adminClient.unsafe("SELECT name FROM drizzle.__drizzle_migrations");
|
|
2786
|
+
return rows.map((row) => {
|
|
2787
|
+
const record = row;
|
|
2788
|
+
return { name: record.name, appliedAt: null };
|
|
2789
|
+
});
|
|
2790
|
+
} catch {
|
|
2791
|
+
return [];
|
|
2792
|
+
}
|
|
2793
|
+
});
|
|
2794
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
2795
|
+
}
|
|
2628
2796
|
return {
|
|
2629
2797
|
getDatabase,
|
|
2630
2798
|
migrateDatabase: migrateOnce,
|
|
2631
2799
|
closeDatabase,
|
|
2632
2800
|
configureOrm,
|
|
2633
|
-
seedDatabase
|
|
2801
|
+
seedDatabase,
|
|
2802
|
+
resetDatabase,
|
|
2803
|
+
migrationStatus
|
|
2634
2804
|
};
|
|
2635
2805
|
}
|
|
2636
2806
|
|
|
@@ -2728,12 +2898,61 @@ function createMySqlDatabase(options) {
|
|
|
2728
2898
|
const db = await getDatabase();
|
|
2729
2899
|
await runSeeders(db, resolvedSeedersFolder);
|
|
2730
2900
|
}
|
|
2901
|
+
async function withAdminDb(callback) {
|
|
2902
|
+
const adminDb = drizzle2({
|
|
2903
|
+
connection: {
|
|
2904
|
+
uri: resolveConnectionString(),
|
|
2905
|
+
...clientOptions
|
|
2906
|
+
},
|
|
2907
|
+
mode: "default"
|
|
2908
|
+
});
|
|
2909
|
+
try {
|
|
2910
|
+
return await callback(adminDb);
|
|
2911
|
+
} finally {
|
|
2912
|
+
await closeClient(adminDb);
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
async function resetDatabase() {
|
|
2916
|
+
const { sql } = await import("drizzle-orm");
|
|
2917
|
+
await withAdminDb(async (adminDb) => {
|
|
2918
|
+
const [rows] = await adminDb.execute(
|
|
2919
|
+
sql.raw("SELECT table_name AS name FROM information_schema.tables WHERE table_schema = DATABASE()")
|
|
2920
|
+
);
|
|
2921
|
+
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 0"));
|
|
2922
|
+
try {
|
|
2923
|
+
for (const { name } of rows) {
|
|
2924
|
+
await adminDb.execute(sql.raw(`DROP TABLE IF EXISTS \`${name.replaceAll("`", "``")}\``));
|
|
2925
|
+
}
|
|
2926
|
+
} finally {
|
|
2927
|
+
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 1"));
|
|
2928
|
+
}
|
|
2929
|
+
});
|
|
2930
|
+
migrationsPromise = void 0;
|
|
2931
|
+
}
|
|
2932
|
+
async function migrationStatus() {
|
|
2933
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
2934
|
+
if (localMigrations.length === 0) return [];
|
|
2935
|
+
const { sql } = await import("drizzle-orm");
|
|
2936
|
+
const appliedRows = await withAdminDb(async (adminDb) => {
|
|
2937
|
+
try {
|
|
2938
|
+
const [rows] = await adminDb.execute(
|
|
2939
|
+
sql.raw("SELECT name, applied_at FROM __drizzle_migrations")
|
|
2940
|
+
);
|
|
2941
|
+
return rows.map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
2942
|
+
} catch {
|
|
2943
|
+
return [];
|
|
2944
|
+
}
|
|
2945
|
+
});
|
|
2946
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
2947
|
+
}
|
|
2731
2948
|
return {
|
|
2732
2949
|
getDatabase,
|
|
2733
2950
|
migrateDatabase: migrateOnce,
|
|
2734
2951
|
closeDatabase,
|
|
2735
2952
|
configureOrm,
|
|
2736
|
-
seedDatabase
|
|
2953
|
+
seedDatabase,
|
|
2954
|
+
resetDatabase,
|
|
2955
|
+
migrationStatus
|
|
2737
2956
|
};
|
|
2738
2957
|
}
|
|
2739
2958
|
async function closeClient(db) {
|
|
@@ -2773,6 +2992,7 @@ function createSqliteDatabase(options) {
|
|
|
2773
2992
|
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
|
|
2774
2993
|
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) : resolve5(String(seedersFolder));
|
|
2775
2994
|
let db;
|
|
2995
|
+
let sqliteClient;
|
|
2776
2996
|
let migrationsPromise;
|
|
2777
2997
|
function resolveFilename() {
|
|
2778
2998
|
const value = typeof filename === "function" ? filename() : filename;
|
|
@@ -2790,6 +3010,7 @@ function createSqliteDatabase(options) {
|
|
|
2790
3010
|
const { Database } = await import("bun:sqlite");
|
|
2791
3011
|
const sqlite = new Database(dbPath);
|
|
2792
3012
|
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
3013
|
+
sqliteClient = sqlite;
|
|
2793
3014
|
const { drizzle: drizzle3 } = await import("drizzle-orm/bun-sqlite");
|
|
2794
3015
|
db = drizzle3({ client: sqlite, ...relations ? { relations } : {} });
|
|
2795
3016
|
return db;
|
|
@@ -2821,6 +3042,33 @@ function createSqliteDatabase(options) {
|
|
|
2821
3042
|
async closeDatabase() {
|
|
2822
3043
|
if (!db) return;
|
|
2823
3044
|
db = void 0;
|
|
3045
|
+
sqliteClient = void 0;
|
|
3046
|
+
},
|
|
3047
|
+
async resetDatabase() {
|
|
3048
|
+
await ensureDatabase2();
|
|
3049
|
+
if (!sqliteClient) return;
|
|
3050
|
+
const tables = sqliteClient.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
|
|
3051
|
+
sqliteClient.exec("PRAGMA foreign_keys = OFF;");
|
|
3052
|
+
try {
|
|
3053
|
+
for (const { name } of tables) {
|
|
3054
|
+
sqliteClient.exec(`DROP TABLE IF EXISTS "${name.replaceAll('"', '""')}"`);
|
|
3055
|
+
}
|
|
3056
|
+
} finally {
|
|
3057
|
+
sqliteClient.exec("PRAGMA foreign_keys = ON;");
|
|
3058
|
+
}
|
|
3059
|
+
migrationsPromise = void 0;
|
|
3060
|
+
},
|
|
3061
|
+
async migrationStatus() {
|
|
3062
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3063
|
+
if (localMigrations.length === 0) return [];
|
|
3064
|
+
await ensureDatabase2();
|
|
3065
|
+
let appliedRows = [];
|
|
3066
|
+
try {
|
|
3067
|
+
const rows = sqliteClient?.query("SELECT name, applied_at FROM __drizzle_migrations").all();
|
|
3068
|
+
appliedRows = (rows ?? []).map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
3069
|
+
} catch {
|
|
3070
|
+
}
|
|
3071
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
2824
3072
|
},
|
|
2825
3073
|
async configureOrm() {
|
|
2826
3074
|
const database2 = await ensureDatabase2();
|