@guren/orm 1.0.0-rc.13 → 1.0.0-rc.15

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/drizzle.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { SQL, sql } from 'drizzle-orm';
2
- export { PgColumn, PgTable, bigint, boolean, integer, pgTable, serial, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
2
+ export { PgColumn, PgTable, bigint, boolean, integer, jsonb, pgTable, serial, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
3
3
  export { MySqlColumn, MySqlTable, datetime, int, mysqlTable, varchar } from 'drizzle-orm/mysql-core';
package/dist/drizzle.js CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  bigint,
9
9
  timestamp,
10
10
  boolean,
11
+ jsonb,
11
12
  uniqueIndex
12
13
  } from "drizzle-orm/pg-core";
13
14
  import {
@@ -22,6 +23,7 @@ export {
22
23
  datetime,
23
24
  int,
24
25
  integer,
26
+ jsonb,
25
27
  mysqlTable,
26
28
  pgTable,
27
29
  serial,
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
- /** @internal Used by QueryBuilder for eager loading. */
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
@@ -2101,35 +2101,141 @@ var Model = class _Model {
2101
2101
  }
2102
2102
  return copies;
2103
2103
  }
2104
- /** @internal Used by QueryBuilder for eager loading. */
2105
- static async loadRelationInto(records, relationName) {
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
- await this.loadHasMany(records, definition);
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
+ }
2113
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
+ }
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
- return;
2197
+ break;
2117
2198
  case "belongsTo":
2118
2199
  await this.loadBelongsTo(records, definition);
2119
- return;
2200
+ break;
2120
2201
  case "belongsToMany":
2121
2202
  await this.loadBelongsToMany(records, definition);
2122
- return;
2203
+ break;
2123
2204
  case "hasManyThrough":
2124
2205
  await this.loadHasManyThrough(records, definition);
2125
- return;
2206
+ break;
2126
2207
  case "morphMany":
2127
2208
  await this.loadMorphMany(records, definition);
2128
- return;
2209
+ break;
2129
2210
  case "morphTo":
2130
2211
  await this.loadMorphTo(records, definition);
2131
- return;
2212
+ break;
2213
+ }
2214
+ if (rest.length === 0) {
2215
+ return;
2132
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
+ }
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;
@@ -2445,14 +2551,65 @@ function SoftDeletes(Base) {
2445
2551
  // src/postgres.ts
2446
2552
  import { drizzle } from "drizzle-orm/postgres-js";
2447
2553
  import { migrate } from "drizzle-orm/postgres-js/migrator";
2448
- import { existsSync, readdirSync } from "fs";
2449
- import { resolve as resolve2 } from "path";
2554
+ import { resolve as resolve3 } from "path";
2450
2555
  import { fileURLToPath as fileURLToPath2 } from "url";
2451
2556
  import postgres from "postgres";
2452
2557
 
2558
+ // src/migration-utils.ts
2559
+ import { existsSync, readdirSync } from "fs";
2560
+ import { resolve } from "path";
2561
+ function hasDrizzleMigrations(migrationsFolder) {
2562
+ if (!existsSync(migrationsFolder)) {
2563
+ return false;
2564
+ }
2565
+ const entries = readdirSync(migrationsFolder, { withFileTypes: true });
2566
+ return entries.some(
2567
+ (entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))
2568
+ );
2569
+ }
2570
+ function warnIgnoredFlatSqlMigrations(migrationsFolder) {
2571
+ if (!existsSync(migrationsFolder)) {
2572
+ return;
2573
+ }
2574
+ const flatSqlFiles = readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name);
2575
+ if (flatSqlFiles.length > 0) {
2576
+ console.warn(
2577
+ `[guren/orm] Ignoring ${flatSqlFiles.length} loose .sql file(s) in ${migrationsFolder}: ${flatSqlFiles.join(", ")}.
2578
+ [guren/orm] Migrations must be generated with drizzle-kit (\`bun run db:make\`), which creates one folder per migration.`
2579
+ );
2580
+ }
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
+ }
2609
+
2453
2610
  // src/seeder.ts
2454
2611
  import { readdir } from "fs/promises";
2455
- import { extname, resolve } from "path";
2612
+ import { extname, resolve as resolve2 } from "path";
2456
2613
  import { fileURLToPath, pathToFileURL } from "url";
2457
2614
  var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".ts"]);
2458
2615
  function normalizeSeeder(candidate) {
@@ -2497,9 +2654,9 @@ async function loadSeederModule(path) {
2497
2654
  return void 0;
2498
2655
  }
2499
2656
  async function loadSeeders(directory) {
2500
- const root = directory instanceof URL ? fileURLToPath(directory) : resolve(directory);
2657
+ const root = directory instanceof URL ? fileURLToPath(directory) : resolve2(directory);
2501
2658
  const entries = await readdir(root, { withFileTypes: true });
2502
- const files = entries.filter((entry) => entry.isFile() && SUPPORTED_EXTENSIONS.has(extname(entry.name))).map((entry) => resolve(root, entry.name)).sort();
2659
+ const files = entries.filter((entry) => entry.isFile() && SUPPORTED_EXTENSIONS.has(extname(entry.name))).map((entry) => resolve2(root, entry.name)).sort();
2503
2660
  const seeders = [];
2504
2661
  for (const file of files) {
2505
2662
  const handler = await loadSeederModule(file);
@@ -2522,8 +2679,8 @@ function defineSeeder(handler) {
2522
2679
  // src/postgres.ts
2523
2680
  function createPostgresDatabase(options) {
2524
2681
  const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
2525
- const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath2(migrationsFolder) : resolve2(String(migrationsFolder));
2526
- const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath2(seedersFolder) : resolve2(String(seedersFolder));
2682
+ const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath2(migrationsFolder) : resolve3(String(migrationsFolder));
2683
+ const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath2(seedersFolder) : resolve3(String(seedersFolder));
2527
2684
  let migrationsPromise;
2528
2685
  let databasePromise;
2529
2686
  let client;
@@ -2541,6 +2698,7 @@ function createPostgresDatabase(options) {
2541
2698
  }
2542
2699
  const promise = (async () => {
2543
2700
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
2701
+ warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
2544
2702
  return;
2545
2703
  }
2546
2704
  const url = resolveConnectionString();
@@ -2600,34 +2758,61 @@ function createPostgresDatabase(options) {
2600
2758
  const db = await getDatabase();
2601
2759
  await runSeeders(db, resolvedSeedersFolder);
2602
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
+ }
2603
2796
  return {
2604
2797
  getDatabase,
2605
2798
  migrateDatabase: migrateOnce,
2606
2799
  closeDatabase,
2607
2800
  configureOrm,
2608
- seedDatabase
2801
+ seedDatabase,
2802
+ resetDatabase,
2803
+ migrationStatus
2609
2804
  };
2610
2805
  }
2611
- function hasDrizzleMigrations(migrationsFolder) {
2612
- if (!existsSync(migrationsFolder)) {
2613
- return false;
2614
- }
2615
- const entries = readdirSync(migrationsFolder, { withFileTypes: true });
2616
- return entries.some(
2617
- (entry) => entry.isDirectory() && existsSync(resolve2(migrationsFolder, entry.name, "migration.sql"))
2618
- );
2619
- }
2620
2806
 
2621
2807
  // src/mysql.ts
2622
2808
  import { drizzle as drizzle2 } from "drizzle-orm/mysql2";
2623
2809
  import { migrate as migrate2 } from "drizzle-orm/mysql2/migrator";
2624
- import { existsSync as existsSync2, readdirSync as readdirSync2 } from "fs";
2625
- import { resolve as resolve3 } from "path";
2810
+ import { resolve as resolve4 } from "path";
2626
2811
  import { fileURLToPath as fileURLToPath3 } from "url";
2627
2812
  function createMySqlDatabase(options) {
2628
2813
  const { migrationsFolder, connectionString, clientOptions, seedersFolder, relations } = options;
2629
- const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath3(migrationsFolder) : resolve3(String(migrationsFolder));
2630
- const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve3(String(seedersFolder));
2814
+ const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath3(migrationsFolder) : resolve4(String(migrationsFolder));
2815
+ const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
2631
2816
  let migrationsPromise;
2632
2817
  let databasePromise;
2633
2818
  let database2;
@@ -2644,7 +2829,8 @@ function createMySqlDatabase(options) {
2644
2829
  return migrationsPromise;
2645
2830
  }
2646
2831
  const promise = (async () => {
2647
- if (!hasDrizzleMigrations2(resolvedMigrationsFolder)) {
2832
+ if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
2833
+ warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
2648
2834
  return;
2649
2835
  }
2650
2836
  const url = resolveConnectionString();
@@ -2712,12 +2898,61 @@ function createMySqlDatabase(options) {
2712
2898
  const db = await getDatabase();
2713
2899
  await runSeeders(db, resolvedSeedersFolder);
2714
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
+ }
2715
2948
  return {
2716
2949
  getDatabase,
2717
2950
  migrateDatabase: migrateOnce,
2718
2951
  closeDatabase,
2719
2952
  configureOrm,
2720
- seedDatabase
2953
+ seedDatabase,
2954
+ resetDatabase,
2955
+ migrationStatus
2721
2956
  };
2722
2957
  }
2723
2958
  async function closeClient(db) {
@@ -2748,25 +2983,16 @@ async function closeClient(db) {
2748
2983
  function isPromiseLike2(value) {
2749
2984
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
2750
2985
  }
2751
- function hasDrizzleMigrations2(migrationsFolder) {
2752
- if (!existsSync2(migrationsFolder)) {
2753
- return false;
2754
- }
2755
- const entries = readdirSync2(migrationsFolder, { withFileTypes: true });
2756
- return entries.some(
2757
- (entry) => entry.isDirectory() && existsSync2(resolve3(migrationsFolder, entry.name, "migration.sql"))
2758
- );
2759
- }
2760
2986
 
2761
2987
  // src/sqlite.ts
2762
- import { existsSync as existsSync3, readdirSync as readdirSync3 } from "fs";
2763
- import { resolve as resolve4 } from "path";
2988
+ import { resolve as resolve5 } from "path";
2764
2989
  import { fileURLToPath as fileURLToPath4 } from "url";
2765
2990
  function createSqliteDatabase(options) {
2766
2991
  const { migrationsFolder, filename, seedersFolder, relations } = options;
2767
- const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve4(String(migrationsFolder));
2768
- const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) : resolve4(String(seedersFolder));
2992
+ const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
2993
+ const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath4(seedersFolder) : resolve5(String(seedersFolder));
2769
2994
  let db;
2995
+ let sqliteClient;
2770
2996
  let migrationsPromise;
2771
2997
  function resolveFilename() {
2772
2998
  const value = typeof filename === "function" ? filename() : filename;
@@ -2778,12 +3004,13 @@ function createSqliteDatabase(options) {
2778
3004
  const { mkdirSync } = await import("fs");
2779
3005
  const { dirname } = await import("path");
2780
3006
  try {
2781
- mkdirSync(dirname(resolve4(dbPath)), { recursive: true });
3007
+ mkdirSync(dirname(resolve5(dbPath)), { recursive: true });
2782
3008
  } catch {
2783
3009
  }
2784
3010
  const { Database } = await import("bun:sqlite");
2785
3011
  const sqlite = new Database(dbPath);
2786
3012
  sqlite.exec("PRAGMA journal_mode = WAL;");
3013
+ sqliteClient = sqlite;
2787
3014
  const { drizzle: drizzle3 } = await import("drizzle-orm/bun-sqlite");
2788
3015
  db = drizzle3({ client: sqlite, ...relations ? { relations } : {} });
2789
3016
  return db;
@@ -2791,7 +3018,8 @@ function createSqliteDatabase(options) {
2791
3018
  async function migrateOnce() {
2792
3019
  if (migrationsPromise) return migrationsPromise;
2793
3020
  migrationsPromise = (async () => {
2794
- if (!hasDrizzleMigrations3(resolvedMigrationsFolder)) {
3021
+ if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3022
+ warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
2795
3023
  return;
2796
3024
  }
2797
3025
  const database2 = await ensureDatabase2();
@@ -2814,6 +3042,33 @@ function createSqliteDatabase(options) {
2814
3042
  async closeDatabase() {
2815
3043
  if (!db) return;
2816
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);
2817
3072
  },
2818
3073
  async configureOrm() {
2819
3074
  const database2 = await ensureDatabase2();
@@ -2832,15 +3087,6 @@ function createSqliteDatabase(options) {
2832
3087
  }
2833
3088
  };
2834
3089
  }
2835
- function hasDrizzleMigrations3(migrationsFolder) {
2836
- if (!existsSync3(migrationsFolder)) {
2837
- return false;
2838
- }
2839
- const entries = readdirSync3(migrationsFolder, { withFileTypes: true });
2840
- return entries.some(
2841
- (entry) => entry.isDirectory() && existsSync3(resolve4(migrationsFolder, entry.name, "migration.sql"))
2842
- );
2843
- }
2844
3090
  export {
2845
3091
  DrizzleAdapter,
2846
3092
  GlobalScopeRegistry,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "1.0.0-rc.13",
3
+ "version": "1.0.0-rc.15",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {