@guren/orm 2.4.0 → 2.6.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 +185 -66
- package/dist/index.js +240 -119
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { SQL } from 'drizzle-orm';
|
|
2
2
|
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
3
3
|
import postgres from 'postgres';
|
|
4
|
-
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
5
4
|
import * as drizzle_orm_aws_data_api_pg from 'drizzle-orm/aws-data-api/pg';
|
|
6
5
|
import { AwsDataApiPgDatabase as AwsDataApiPgDatabase$1 } from 'drizzle-orm/aws-data-api/pg';
|
|
7
|
-
import { RDSDataClientConfig } from '@aws-sdk/client-rds-data';
|
|
8
6
|
import { SQLiteBunDatabase } from 'drizzle-orm/bun-sqlite';
|
|
7
|
+
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
8
|
+
import { RDSDataClientConfig } from '@aws-sdk/client-rds-data';
|
|
9
9
|
|
|
10
10
|
/** Accessor function: transforms a record field value after reading from DB. */
|
|
11
11
|
type AccessorFn<T = unknown> = (record: PlainObject) => T;
|
|
@@ -65,6 +65,17 @@ interface QueryBuilderOptions {
|
|
|
65
65
|
selectFields?: readonly string[];
|
|
66
66
|
trx?: unknown;
|
|
67
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* A callback that further constrains the query used to fetch an eager-loaded
|
|
70
|
+
* relation. Registered through the object form of {@link QueryBuilder.with}.
|
|
71
|
+
*/
|
|
72
|
+
type EagerLoadConstraint = (q: QueryBuilder) => void;
|
|
73
|
+
/**
|
|
74
|
+
* Constraint callbacks keyed by the relation path they constrain. A key names
|
|
75
|
+
* the exact level it applies to: `posts` constrains the head, `posts.comments`
|
|
76
|
+
* constrains the leaf.
|
|
77
|
+
*/
|
|
78
|
+
type EagerLoadConstraints = ReadonlyMap<string, EagerLoadConstraint>;
|
|
68
79
|
/**
|
|
69
80
|
* Fluent query builder for the Guren ORM.
|
|
70
81
|
*
|
|
@@ -192,6 +203,20 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
192
203
|
* Supports string names, arrays, dot notation for nested relations,
|
|
193
204
|
* and constraint callbacks.
|
|
194
205
|
*
|
|
206
|
+
* A constraint callback receives the query builder used to fetch that
|
|
207
|
+
* relation, and runs after the foreign-key filter is already on it, so a
|
|
208
|
+
* `where()` narrows that filter. Each object key constrains exactly the
|
|
209
|
+
* level it names, in any order: `posts` constrains the head,
|
|
210
|
+
* `posts.comments` constrains the leaf and leaves `posts` unfiltered.
|
|
211
|
+
*
|
|
212
|
+
* Three things behave differently than they may look:
|
|
213
|
+
* - `orWhere()` at the top level of a callback *widens* the query rather
|
|
214
|
+
* than narrowing it, because it ORs against the foreign-key filter. Group
|
|
215
|
+
* it (`q.where((g) => g.where(...).orWhere(...))`) to keep it contained.
|
|
216
|
+
* - `select()` must include the column the relation is keyed on, or the
|
|
217
|
+
* loader cannot match rows back to their parent and the relation is empty.
|
|
218
|
+
* - `limit()` applies to the single batched query, not per parent record.
|
|
219
|
+
*
|
|
195
220
|
* @example
|
|
196
221
|
* // Simple
|
|
197
222
|
* await User.where('active', true).with('posts').get()
|
|
@@ -201,8 +226,16 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
201
226
|
*
|
|
202
227
|
* // Nested (dot notation)
|
|
203
228
|
* await User.where('active', true).with('posts.comments').get()
|
|
229
|
+
*
|
|
230
|
+
* // Constrained
|
|
231
|
+
* await User.newQuery().with({ posts: (q) => q.where('published', true) }).get()
|
|
232
|
+
*
|
|
233
|
+
* // Constrained at both levels
|
|
234
|
+
* await User.newQuery()
|
|
235
|
+
* .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.orderBy('id') })
|
|
236
|
+
* .get()
|
|
204
237
|
*/
|
|
205
|
-
with(...relations: (string | Record<string,
|
|
238
|
+
with(...relations: (string | Record<string, EagerLoadConstraint>)[]): this;
|
|
206
239
|
/**
|
|
207
240
|
* Execute the query and return all matching records.
|
|
208
241
|
* @returns Array of matching records
|
|
@@ -313,8 +346,15 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
313
346
|
/**
|
|
314
347
|
* Load eager relations onto fetched results.
|
|
315
348
|
* Supports dot notation for nested relations at any depth
|
|
316
|
-
* (e.g., 'posts.comments.author') — the
|
|
317
|
-
* Model.
|
|
349
|
+
* (e.g., 'posts.comments.author') — the paths are delegated to
|
|
350
|
+
* Model.loadRelationsInto, which recurses through the relation chain.
|
|
351
|
+
* Constraint callbacks registered by the object form of `with()` travel
|
|
352
|
+
* alongside, keyed by the path segment each one constrains.
|
|
353
|
+
*
|
|
354
|
+
* The builder's `trx` goes with it: a relation loaded for rows read inside
|
|
355
|
+
* a transaction has to be read on that same handle, or the parents come
|
|
356
|
+
* from the transaction and their children from the pool — which on
|
|
357
|
+
* Postgres/MySQL means uncommitted parents get a null relation back.
|
|
318
358
|
*/
|
|
319
359
|
private readonly loadEagerRelations;
|
|
320
360
|
}
|
|
@@ -916,7 +956,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
916
956
|
* const post = await Post.findWith(1, 'author')
|
|
917
957
|
* const post = await Post.findWith(1, ['author', 'tags'])
|
|
918
958
|
*/
|
|
919
|
-
static findWith<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
|
|
959
|
+
static findWith<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
|
|
920
960
|
/**
|
|
921
961
|
* Find a record by primary key with eager-loaded relations, or throw.
|
|
922
962
|
*
|
|
@@ -931,7 +971,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
931
971
|
* const post = await Post.findWithOrFail(1, ['author', 'tags'])
|
|
932
972
|
* const post = await Post.findWithOrFail(1, 'comments.author') // nested
|
|
933
973
|
*/
|
|
934
|
-
static findWithOrFail<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>;
|
|
974
|
+
static findWithOrFail<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>;
|
|
935
975
|
/**
|
|
936
976
|
* Get the first record matching the conditions.
|
|
937
977
|
*
|
|
@@ -1211,7 +1251,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1211
1251
|
* // result.data - Users with their posts loaded
|
|
1212
1252
|
* // result.meta - Pagination metadata
|
|
1213
1253
|
*/
|
|
1214
|
-
static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T
|
|
1254
|
+
static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
1215
1255
|
/**
|
|
1216
1256
|
* Create a new record.
|
|
1217
1257
|
*
|
|
@@ -1309,7 +1349,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1309
1349
|
* // Nested relations via dot notation
|
|
1310
1350
|
* const usersWithPostComments = await User.with('posts.comments')
|
|
1311
1351
|
*/
|
|
1312
|
-
static with<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T
|
|
1352
|
+
static with<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
1313
1353
|
/**
|
|
1314
1354
|
* Fetch records with related record counts attached as `${name}Count`.
|
|
1315
1355
|
* Counts hasMany/hasOne/morphMany children per record without attaching
|
|
@@ -1319,21 +1359,43 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1319
1359
|
* const users = await User.withCount('posts')
|
|
1320
1360
|
* users[0].postsCount // number
|
|
1321
1361
|
*/
|
|
1322
|
-
static withCount<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T
|
|
1362
|
+
static withCount<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T> & RelationCountPick<K | readonly K[]>>>;
|
|
1323
1363
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1324
|
-
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
1364
|
+
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions): Promise<void>;
|
|
1325
1365
|
/**
|
|
1326
1366
|
* @internal Used by QueryBuilder for eager loading.
|
|
1327
1367
|
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
1368
|
+
*
|
|
1369
|
+
* Paths are grouped by their head segment so a relation shared by several
|
|
1370
|
+
* paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
|
|
1371
|
+
* independently would load `posts` twice, and the loaders assign fresh
|
|
1372
|
+
* spread copies — so the second pass would replace the very row objects the
|
|
1373
|
+
* first had already attached children to, and only the last path would
|
|
1374
|
+
* survive.
|
|
1375
|
+
*/
|
|
1376
|
+
static loadRelationsInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationNames: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1377
|
+
/**
|
|
1378
|
+
* @internal Public since it is reachable from generated code; kept for
|
|
1379
|
+
* backwards compatibility now that the eager loader walks whole path lists.
|
|
1380
|
+
* Internal callers should use {@link loadRelationsInto} instead.
|
|
1328
1381
|
*/
|
|
1329
|
-
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1382
|
+
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1383
|
+
/**
|
|
1384
|
+
* Load one relation level and recurse into the tails beneath it.
|
|
1385
|
+
*
|
|
1386
|
+
* `constraints` are keyed by the full path of the level each one constrains,
|
|
1387
|
+
* so `pathPrefix` accumulates the path walked so far as the recursion
|
|
1388
|
+
* descends: at `posts.comments` the leaf looks itself up under that whole
|
|
1389
|
+
* key, not under `comments`.
|
|
1390
|
+
*/
|
|
1391
|
+
protected static loadRelationLevel<T extends typeof Model>(this: T, records: Array<PlainObject>, head: string, tails: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1392
|
+
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1393
|
+
protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1394
|
+
protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1395
|
+
protected static loadBelongsToMany(records: Array<PlainObject>, definition: BelongsToManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1396
|
+
protected static loadHasManyThrough(records: Array<PlainObject>, definition: HasManyThroughRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1397
|
+
protected static loadMorphMany(records: Array<PlainObject>, definition: MorphManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1398
|
+
protected static loadMorphTo(records: Array<PlainObject>, definition: MorphToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1337
1399
|
}
|
|
1338
1400
|
type TRecordFor<T extends typeof Model> = T extends {
|
|
1339
1401
|
recordType: infer R;
|
|
@@ -1698,12 +1760,86 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
|
1698
1760
|
*/
|
|
1699
1761
|
declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
|
|
1700
1762
|
|
|
1763
|
+
/**
|
|
1764
|
+
* What one `migrateDatabase()` call had to work with. `db:migrate` reports
|
|
1765
|
+
* success off this rather than off the call returning: a folder with nothing
|
|
1766
|
+
* in it applies nothing, and saying "completed" there reads as a database that
|
|
1767
|
+
* is now up to date.
|
|
1768
|
+
*
|
|
1769
|
+
* It describes the run the driver memoized, not the folder as it stands now.
|
|
1770
|
+
* Migrations are single-flighted per handle, so a second call returns this same
|
|
1771
|
+
* summary without re-reading the folder — which is the pre-existing no-rerun
|
|
1772
|
+
* behaviour, faithfully reported.
|
|
1773
|
+
*/
|
|
1774
|
+
interface MigrationRunSummary {
|
|
1775
|
+
/** The folder the migrator read, absolute as the driver resolved it. */
|
|
1776
|
+
migrationsFolder: string;
|
|
1777
|
+
/** drizzle-kit migrations found there (one folder each, holding migration.sql). */
|
|
1778
|
+
migrationsFound: number;
|
|
1779
|
+
/**
|
|
1780
|
+
* Loose .sql files in that folder, which the drizzle migrator never runs.
|
|
1781
|
+
* Non-zero alongside `migrationsFound: 0` means the folder is not empty but
|
|
1782
|
+
* holds nothing to apply, which is a different problem from having generated
|
|
1783
|
+
* no migrations yet.
|
|
1784
|
+
*/
|
|
1785
|
+
looseSqlFiles: number;
|
|
1786
|
+
}
|
|
1701
1787
|
interface MigrationStatusEntry {
|
|
1702
1788
|
name: string;
|
|
1703
1789
|
applied: boolean;
|
|
1704
1790
|
appliedAt: Date | null;
|
|
1705
1791
|
}
|
|
1706
1792
|
|
|
1793
|
+
/**
|
|
1794
|
+
* The context a seeder receives. `db` is the drizzle database the app
|
|
1795
|
+
* configured, so its type depends on the dialect: annotate the seeder with the
|
|
1796
|
+
* matching alias below (or pass the driver's own database type) whenever the
|
|
1797
|
+
* app is not on PostgreSQL.
|
|
1798
|
+
*
|
|
1799
|
+
* The type parameter defaults to `PostgresJsDatabase` for backwards
|
|
1800
|
+
* compatibility — seeders written before this was generic keep compiling.
|
|
1801
|
+
*/
|
|
1802
|
+
interface SeederContext<TDatabase = PostgresJsDatabase> {
|
|
1803
|
+
db: TDatabase;
|
|
1804
|
+
}
|
|
1805
|
+
type SeederHandler<TDatabase = PostgresJsDatabase> = (context: SeederContext<TDatabase>) => unknown;
|
|
1806
|
+
/** Seeder context for apps created with `createPostgresDatabase()`. */
|
|
1807
|
+
type PostgresSeederContext = SeederContext<PostgresJsDatabase>;
|
|
1808
|
+
/** Seeder context for apps created with `createMySqlDatabase()`. */
|
|
1809
|
+
type MySqlSeederContext = SeederContext<MySql2Database>;
|
|
1810
|
+
/** Seeder context for apps created with `createSqliteDatabase()`. */
|
|
1811
|
+
type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
|
|
1812
|
+
/** Seeder context for apps created with `createAwsDataApiDatabase()`. */
|
|
1813
|
+
type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase$1>;
|
|
1814
|
+
/**
|
|
1815
|
+
* What one `runSeeders()` call had to work with. `db:seed` reports success off
|
|
1816
|
+
* this rather than off the call returning: a folder with no seeders in it seeds
|
|
1817
|
+
* nothing, and saying "executed" there reads as a database that now holds the
|
|
1818
|
+
* rows the seeders would have written.
|
|
1819
|
+
*/
|
|
1820
|
+
interface SeederRunSummary {
|
|
1821
|
+
/** The folder that was read, absolute as the driver resolved it. */
|
|
1822
|
+
seedersFolder: string;
|
|
1823
|
+
/** How many seeders ran. They run in the order their files sorted. */
|
|
1824
|
+
seedersRan: number;
|
|
1825
|
+
/**
|
|
1826
|
+
* Files with a seeder extension that exported nothing runnable, so they were
|
|
1827
|
+
* skipped. Non-zero alongside `seedersRan: 0` means the folder is not empty
|
|
1828
|
+
* but holds nothing to run — a different problem from having written no
|
|
1829
|
+
* seeder yet, and one `make:seeder` would not solve.
|
|
1830
|
+
*/
|
|
1831
|
+
filesWithoutSeeder: number;
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* Seeders are loaded as modules, so the dialect they were written against is
|
|
1835
|
+
* unknowable here. `TDatabase` is the caller stating which database it will
|
|
1836
|
+
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
1837
|
+
*/
|
|
1838
|
+
declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
|
|
1839
|
+
/** Runs every seeder in `directory` and reports what the folder held. */
|
|
1840
|
+
declare function runSeeders<TDatabase>(db: TDatabase, directory: string | URL): Promise<SeederRunSummary>;
|
|
1841
|
+
declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHandler<TDatabase>): SeederHandler<TDatabase>;
|
|
1842
|
+
|
|
1707
1843
|
type ConnectionResolver$3 = string | (() => string | undefined);
|
|
1708
1844
|
interface PostgresDatabaseOptions {
|
|
1709
1845
|
migrationsFolder: string | URL;
|
|
@@ -1719,12 +1855,14 @@ interface PostgresDatabaseOptions {
|
|
|
1719
1855
|
}
|
|
1720
1856
|
interface PostgresDatabase {
|
|
1721
1857
|
getDatabase(): Promise<PostgresJsDatabase>;
|
|
1722
|
-
|
|
1858
|
+
/** Applies pending drizzle-kit migrations and reports what the folder held. */
|
|
1859
|
+
migrateDatabase(): Promise<MigrationRunSummary>;
|
|
1723
1860
|
closeDatabase(): Promise<void>;
|
|
1724
1861
|
configureOrm(): Promise<void>;
|
|
1725
|
-
|
|
1862
|
+
/** Runs every seeder in the configured folder and reports what it held. */
|
|
1863
|
+
seedDatabase(): Promise<SeederRunSummary>;
|
|
1726
1864
|
/** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1727
|
-
resetDatabase(): Promise<
|
|
1865
|
+
resetDatabase(): Promise<MigrationRunSummary>;
|
|
1728
1866
|
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1729
1867
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1730
1868
|
}
|
|
@@ -1746,12 +1884,14 @@ interface MySqlDatabaseOptions {
|
|
|
1746
1884
|
}
|
|
1747
1885
|
interface MySqlDatabase {
|
|
1748
1886
|
getDatabase(): Promise<MySql2Database>;
|
|
1749
|
-
|
|
1887
|
+
/** Applies pending drizzle-kit migrations and reports what the folder held. */
|
|
1888
|
+
migrateDatabase(): Promise<MigrationRunSummary>;
|
|
1750
1889
|
closeDatabase(): Promise<void>;
|
|
1751
1890
|
configureOrm(): Promise<void>;
|
|
1752
|
-
|
|
1891
|
+
/** Runs every seeder in the configured folder and reports what it held. */
|
|
1892
|
+
seedDatabase(): Promise<SeederRunSummary>;
|
|
1753
1893
|
/** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1754
|
-
resetDatabase(): Promise<
|
|
1894
|
+
resetDatabase(): Promise<MigrationRunSummary>;
|
|
1755
1895
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1756
1896
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1757
1897
|
}
|
|
@@ -1772,12 +1912,19 @@ interface SqliteDatabaseOptions {
|
|
|
1772
1912
|
}
|
|
1773
1913
|
interface SqliteDatabase {
|
|
1774
1914
|
getDatabase(): Promise<unknown>;
|
|
1775
|
-
|
|
1915
|
+
/** Applies pending drizzle-kit migrations and reports what the folder held. */
|
|
1916
|
+
migrateDatabase(): Promise<MigrationRunSummary>;
|
|
1776
1917
|
closeDatabase(): Promise<void>;
|
|
1777
1918
|
configureOrm(): Promise<void>;
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1919
|
+
/** Runs every seeder in the configured folder and reports what it held. */
|
|
1920
|
+
seedDatabase(): Promise<SeederRunSummary>;
|
|
1921
|
+
/**
|
|
1922
|
+
* Drops every table and view (including the drizzle migration tracker), then
|
|
1923
|
+
* re-applies migrations — same end state as `guren db:reset`. Resolves
|
|
1924
|
+
* undefined only when a concurrent `closeDatabase()` left nothing to drop, so
|
|
1925
|
+
* there was no migration run to report.
|
|
1926
|
+
*/
|
|
1927
|
+
resetDatabase(): Promise<MigrationRunSummary | undefined>;
|
|
1781
1928
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1782
1929
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1783
1930
|
}
|
|
@@ -1806,13 +1953,13 @@ interface D1DatabaseOptions {
|
|
|
1806
1953
|
interface D1DatabaseHandle {
|
|
1807
1954
|
getDatabase(): Promise<unknown>;
|
|
1808
1955
|
/** Always throws: D1 migrations are applied with `wrangler d1 migrations apply`, never at runtime. */
|
|
1809
|
-
migrateDatabase(): Promise<
|
|
1956
|
+
migrateDatabase(): Promise<never>;
|
|
1810
1957
|
closeDatabase(): Promise<void>;
|
|
1811
1958
|
configureOrm(): Promise<void>;
|
|
1812
1959
|
/** Always throws: seed with SQL through `wrangler d1 execute`. */
|
|
1813
|
-
seedDatabase(): Promise<
|
|
1960
|
+
seedDatabase(): Promise<never>;
|
|
1814
1961
|
/** Always throws: recreate the database with wrangler instead. */
|
|
1815
|
-
resetDatabase(): Promise<
|
|
1962
|
+
resetDatabase(): Promise<never>;
|
|
1816
1963
|
/** Always throws: wrangler's tracker is authoritative — use `wrangler d1 migrations list`. */
|
|
1817
1964
|
migrationStatus(): Promise<never>;
|
|
1818
1965
|
}
|
|
@@ -1853,47 +2000,19 @@ interface AwsDataApiDatabaseOptions {
|
|
|
1853
2000
|
}
|
|
1854
2001
|
interface AwsDataApiDatabase {
|
|
1855
2002
|
getDatabase(): Promise<AwsDataApiPgDatabase>;
|
|
1856
|
-
|
|
2003
|
+
/** Applies pending drizzle-kit migrations and reports what the folder held. */
|
|
2004
|
+
migrateDatabase(): Promise<MigrationRunSummary>;
|
|
1857
2005
|
closeDatabase(): Promise<void>;
|
|
1858
2006
|
configureOrm(): Promise<void>;
|
|
1859
|
-
|
|
2007
|
+
/** Runs every seeder in the configured folder and reports what it held. */
|
|
2008
|
+
seedDatabase(): Promise<SeederRunSummary>;
|
|
1860
2009
|
/** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1861
|
-
resetDatabase(): Promise<
|
|
2010
|
+
resetDatabase(): Promise<MigrationRunSummary>;
|
|
1862
2011
|
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1863
2012
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1864
2013
|
}
|
|
1865
2014
|
declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
|
|
1866
2015
|
|
|
1867
|
-
/**
|
|
1868
|
-
* The context a seeder receives. `db` is the drizzle database the app
|
|
1869
|
-
* configured, so its type depends on the dialect: annotate the seeder with the
|
|
1870
|
-
* matching alias below (or pass the driver's own database type) whenever the
|
|
1871
|
-
* app is not on PostgreSQL.
|
|
1872
|
-
*
|
|
1873
|
-
* The type parameter defaults to `PostgresJsDatabase` for backwards
|
|
1874
|
-
* compatibility — seeders written before this was generic keep compiling.
|
|
1875
|
-
*/
|
|
1876
|
-
interface SeederContext<TDatabase = PostgresJsDatabase> {
|
|
1877
|
-
db: TDatabase;
|
|
1878
|
-
}
|
|
1879
|
-
type SeederHandler<TDatabase = PostgresJsDatabase> = (context: SeederContext<TDatabase>) => unknown;
|
|
1880
|
-
/** Seeder context for apps created with `createPostgresDatabase()`. */
|
|
1881
|
-
type PostgresSeederContext = SeederContext<PostgresJsDatabase>;
|
|
1882
|
-
/** Seeder context for apps created with `createMySqlDatabase()`. */
|
|
1883
|
-
type MySqlSeederContext = SeederContext<MySql2Database>;
|
|
1884
|
-
/** Seeder context for apps created with `createSqliteDatabase()`. */
|
|
1885
|
-
type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
|
|
1886
|
-
/** Seeder context for apps created with `createAwsDataApiDatabase()`. */
|
|
1887
|
-
type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase$1>;
|
|
1888
|
-
/**
|
|
1889
|
-
* Seeders are loaded as modules, so the dialect they were written against is
|
|
1890
|
-
* unknowable here. `TDatabase` is the caller stating which database it will
|
|
1891
|
-
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
1892
|
-
*/
|
|
1893
|
-
declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
|
|
1894
|
-
declare function runSeeders<TDatabase>(db: TDatabase, directory: string | URL): Promise<void>;
|
|
1895
|
-
declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHandler<TDatabase>): SeederHandler<TDatabase>;
|
|
1896
|
-
|
|
1897
2016
|
/**
|
|
1898
2017
|
* Serialize a model record for API/JSON output.
|
|
1899
2018
|
*
|
|
@@ -1908,4 +2027,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1908
2027
|
/** Serialize an array of records. */
|
|
1909
2028
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1910
2029
|
|
|
1911
|
-
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 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 MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, 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 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 };
|
|
2030
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -512,7 +512,6 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
512
512
|
adapter;
|
|
513
513
|
eagerLoad = [];
|
|
514
514
|
eagerLoadConstraints = /* @__PURE__ */ new Map();
|
|
515
|
-
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
516
515
|
constructor(modelClass, options = {}) {
|
|
517
516
|
this.modelClass = modelClass;
|
|
518
517
|
this.table = modelClass.resolveTable();
|
|
@@ -667,6 +666,20 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
667
666
|
* Supports string names, arrays, dot notation for nested relations,
|
|
668
667
|
* and constraint callbacks.
|
|
669
668
|
*
|
|
669
|
+
* A constraint callback receives the query builder used to fetch that
|
|
670
|
+
* relation, and runs after the foreign-key filter is already on it, so a
|
|
671
|
+
* `where()` narrows that filter. Each object key constrains exactly the
|
|
672
|
+
* level it names, in any order: `posts` constrains the head,
|
|
673
|
+
* `posts.comments` constrains the leaf and leaves `posts` unfiltered.
|
|
674
|
+
*
|
|
675
|
+
* Three things behave differently than they may look:
|
|
676
|
+
* - `orWhere()` at the top level of a callback *widens* the query rather
|
|
677
|
+
* than narrowing it, because it ORs against the foreign-key filter. Group
|
|
678
|
+
* it (`q.where((g) => g.where(...).orWhere(...))`) to keep it contained.
|
|
679
|
+
* - `select()` must include the column the relation is keyed on, or the
|
|
680
|
+
* loader cannot match rows back to their parent and the relation is empty.
|
|
681
|
+
* - `limit()` applies to the single batched query, not per parent record.
|
|
682
|
+
*
|
|
670
683
|
* @example
|
|
671
684
|
* // Simple
|
|
672
685
|
* await User.where('active', true).with('posts').get()
|
|
@@ -676,6 +689,14 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
676
689
|
*
|
|
677
690
|
* // Nested (dot notation)
|
|
678
691
|
* await User.where('active', true).with('posts.comments').get()
|
|
692
|
+
*
|
|
693
|
+
* // Constrained
|
|
694
|
+
* await User.newQuery().with({ posts: (q) => q.where('published', true) }).get()
|
|
695
|
+
*
|
|
696
|
+
* // Constrained at both levels
|
|
697
|
+
* await User.newQuery()
|
|
698
|
+
* .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.orderBy('id') })
|
|
699
|
+
* .get()
|
|
679
700
|
*/
|
|
680
701
|
with(...relations) {
|
|
681
702
|
for (const rel of relations) {
|
|
@@ -708,11 +729,12 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
708
729
|
async first() {
|
|
709
730
|
const prev = this.options.limitValue;
|
|
710
731
|
this.options.limitValue = 1;
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
732
|
+
try {
|
|
733
|
+
const results = await this.get();
|
|
734
|
+
return results[0] ?? null;
|
|
735
|
+
} finally {
|
|
736
|
+
this.options.limitValue = prev;
|
|
737
|
+
}
|
|
716
738
|
}
|
|
717
739
|
/**
|
|
718
740
|
* Execute the query and return the first matching record, or throw.
|
|
@@ -754,9 +776,13 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
754
776
|
const prevOffset = this.options.offsetValue;
|
|
755
777
|
this.options.limitValue = sanitizedPerPage;
|
|
756
778
|
this.options.offsetValue = offset;
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
779
|
+
let data;
|
|
780
|
+
try {
|
|
781
|
+
data = await this.get();
|
|
782
|
+
} finally {
|
|
783
|
+
this.options.limitValue = prevLimit;
|
|
784
|
+
this.options.offsetValue = prevOffset;
|
|
785
|
+
}
|
|
760
786
|
const from = total === 0 ? 0 : offset + 1;
|
|
761
787
|
const to = total === 0 ? 0 : offset + data.length;
|
|
762
788
|
const meta = {
|
|
@@ -952,16 +978,25 @@ var QueryBuilder = class _QueryBuilder {
|
|
|
952
978
|
/**
|
|
953
979
|
* Load eager relations onto fetched results.
|
|
954
980
|
* Supports dot notation for nested relations at any depth
|
|
955
|
-
* (e.g., 'posts.comments.author') — the
|
|
956
|
-
* Model.
|
|
981
|
+
* (e.g., 'posts.comments.author') — the paths are delegated to
|
|
982
|
+
* Model.loadRelationsInto, which recurses through the relation chain.
|
|
983
|
+
* Constraint callbacks registered by the object form of `with()` travel
|
|
984
|
+
* alongside, keyed by the path segment each one constrains.
|
|
985
|
+
*
|
|
986
|
+
* The builder's `trx` goes with it: a relation loaded for rows read inside
|
|
987
|
+
* a transaction has to be read on that same handle, or the parents come
|
|
988
|
+
* from the transaction and their children from the pool — which on
|
|
989
|
+
* Postgres/MySQL means uncommitted parents get a null relation back.
|
|
957
990
|
*/
|
|
958
991
|
loadEagerRelations = async (results) => {
|
|
959
992
|
if (this.eagerLoad.length === 0 || results.length === 0) return results;
|
|
960
993
|
const copies = results.map((r) => ({ ...r }));
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
994
|
+
await this.modelClass.loadRelationsInto(
|
|
995
|
+
copies,
|
|
996
|
+
this.eagerLoad,
|
|
997
|
+
{ trx: this.options.trx },
|
|
998
|
+
this.eagerLoadConstraints
|
|
999
|
+
);
|
|
965
1000
|
return copies;
|
|
966
1001
|
};
|
|
967
1002
|
};
|
|
@@ -1572,29 +1607,25 @@ var Model = class _Model {
|
|
|
1572
1607
|
}
|
|
1573
1608
|
return record;
|
|
1574
1609
|
}
|
|
1575
|
-
static async findWith(id, relations, key) {
|
|
1576
|
-
const record = await this.find(id, key);
|
|
1610
|
+
static async findWith(id, relations, key, queryOptions) {
|
|
1611
|
+
const record = await this.find(id, key, queryOptions);
|
|
1577
1612
|
if (record == null) return null;
|
|
1578
1613
|
const relationList = normalizeRelations(relations);
|
|
1579
1614
|
if (relationList.length === 0) {
|
|
1580
1615
|
return record;
|
|
1581
1616
|
}
|
|
1582
1617
|
const copy = { ...record };
|
|
1583
|
-
|
|
1584
|
-
await this.loadRelationInto([copy], rel);
|
|
1585
|
-
}
|
|
1618
|
+
await this.loadRelationsInto([copy], relationList, queryOptions);
|
|
1586
1619
|
return copy;
|
|
1587
1620
|
}
|
|
1588
|
-
static async findWithOrFail(id, relations, key) {
|
|
1589
|
-
const record = await this.findOrFail(id, key);
|
|
1621
|
+
static async findWithOrFail(id, relations, key, queryOptions) {
|
|
1622
|
+
const record = await this.findOrFail(id, key, queryOptions);
|
|
1590
1623
|
const relationList = normalizeRelations(relations);
|
|
1591
1624
|
if (relationList.length === 0) {
|
|
1592
1625
|
return record;
|
|
1593
1626
|
}
|
|
1594
1627
|
const copy = { ...record };
|
|
1595
|
-
|
|
1596
|
-
await this.loadRelationInto([copy], rel);
|
|
1597
|
-
}
|
|
1628
|
+
await this.loadRelationsInto([copy], relationList, queryOptions);
|
|
1598
1629
|
return copy;
|
|
1599
1630
|
}
|
|
1600
1631
|
/**
|
|
@@ -2034,16 +2065,14 @@ var Model = class _Model {
|
|
|
2034
2065
|
};
|
|
2035
2066
|
return { data, meta };
|
|
2036
2067
|
}
|
|
2037
|
-
static async withPaginate(relations, options = {}) {
|
|
2038
|
-
const result = await this.paginate(options);
|
|
2068
|
+
static async withPaginate(relations, options = {}, queryOptions) {
|
|
2069
|
+
const result = await this.paginate(options, queryOptions);
|
|
2039
2070
|
const relationList = normalizeRelations(relations);
|
|
2040
2071
|
if (relationList.length === 0 || result.data.length === 0) {
|
|
2041
2072
|
return result;
|
|
2042
2073
|
}
|
|
2043
2074
|
const records = result.data.map((record) => ({ ...record }));
|
|
2044
|
-
|
|
2045
|
-
await this.loadRelationInto(records, relationName);
|
|
2046
|
-
}
|
|
2075
|
+
await this.loadRelationsInto(records, relationList, queryOptions);
|
|
2047
2076
|
return {
|
|
2048
2077
|
data: records,
|
|
2049
2078
|
meta: result.meta
|
|
@@ -2249,8 +2278,8 @@ var Model = class _Model {
|
|
|
2249
2278
|
}
|
|
2250
2279
|
return fallbackBuilder.from(table);
|
|
2251
2280
|
}
|
|
2252
|
-
static async with(relations, where) {
|
|
2253
|
-
const records = where ? await this.where(where) : await this.all();
|
|
2281
|
+
static async with(relations, where, queryOptions) {
|
|
2282
|
+
const records = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
|
|
2254
2283
|
if (!records.length) {
|
|
2255
2284
|
return records;
|
|
2256
2285
|
}
|
|
@@ -2259,25 +2288,23 @@ var Model = class _Model {
|
|
|
2259
2288
|
return records;
|
|
2260
2289
|
}
|
|
2261
2290
|
const copies = records.map((record) => ({ ...record }));
|
|
2262
|
-
|
|
2263
|
-
await this.loadRelationInto(copies, relationName);
|
|
2264
|
-
}
|
|
2291
|
+
await this.loadRelationsInto(copies, relationList, queryOptions);
|
|
2265
2292
|
return copies;
|
|
2266
2293
|
}
|
|
2267
|
-
static async withCount(relations, where) {
|
|
2268
|
-
const records = where ? await this.where(where) : await this.all();
|
|
2294
|
+
static async withCount(relations, where, queryOptions) {
|
|
2295
|
+
const records = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
|
|
2269
2296
|
if (!records.length) {
|
|
2270
2297
|
return records;
|
|
2271
2298
|
}
|
|
2272
2299
|
const relationList = normalizeRelations(relations);
|
|
2273
2300
|
const copies = records.map((record) => ({ ...record }));
|
|
2274
2301
|
for (const relationName of relationList) {
|
|
2275
|
-
await this.loadRelationCountInto(copies, relationName);
|
|
2302
|
+
await this.loadRelationCountInto(copies, relationName, queryOptions);
|
|
2276
2303
|
}
|
|
2277
2304
|
return copies;
|
|
2278
2305
|
}
|
|
2279
2306
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
2280
|
-
static async loadRelationCountInto(records, relationName) {
|
|
2307
|
+
static async loadRelationCountInto(records, relationName, queryOptions) {
|
|
2281
2308
|
if (relationName.includes(".")) {
|
|
2282
2309
|
throw new Error(`${this.name}: withCount does not support nested relation "${relationName}".`);
|
|
2283
2310
|
}
|
|
@@ -2296,7 +2323,7 @@ var Model = class _Model {
|
|
|
2296
2323
|
);
|
|
2297
2324
|
const counts = /* @__PURE__ */ new Map();
|
|
2298
2325
|
if (values.length > 0) {
|
|
2299
|
-
const relatedRecords = await related.where({ [foreignKey]: values });
|
|
2326
|
+
const relatedRecords = await related.newQuery(queryOptions).where({ [foreignKey]: values });
|
|
2300
2327
|
for (const item of relatedRecords) {
|
|
2301
2328
|
const key = item[foreignKey];
|
|
2302
2329
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
@@ -2309,7 +2336,7 @@ var Model = class _Model {
|
|
|
2309
2336
|
}
|
|
2310
2337
|
case "morphMany": {
|
|
2311
2338
|
const withRelation = records.map((record) => ({ ...record }));
|
|
2312
|
-
await this.loadRelationInto(withRelation, relationName);
|
|
2339
|
+
await this.loadRelationInto(withRelation, relationName, queryOptions);
|
|
2313
2340
|
for (const [index, record] of records.entries()) {
|
|
2314
2341
|
const value = withRelation[index]?.[relationName];
|
|
2315
2342
|
record[countField] = Array.isArray(value) ? value.length : 0;
|
|
@@ -2324,7 +2351,7 @@ var Model = class _Model {
|
|
|
2324
2351
|
);
|
|
2325
2352
|
const ownerKeys = /* @__PURE__ */ new Set();
|
|
2326
2353
|
if (values.length > 0) {
|
|
2327
|
-
const owners = await related.where({ [ownerKey]: values });
|
|
2354
|
+
const owners = await related.newQuery(queryOptions).where({ [ownerKey]: values });
|
|
2328
2355
|
for (const owner of owners) {
|
|
2329
2356
|
ownerKeys.add(owner[ownerKey]);
|
|
2330
2357
|
}
|
|
@@ -2344,37 +2371,79 @@ var Model = class _Model {
|
|
|
2344
2371
|
/**
|
|
2345
2372
|
* @internal Used by QueryBuilder for eager loading.
|
|
2346
2373
|
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
2374
|
+
*
|
|
2375
|
+
* Paths are grouped by their head segment so a relation shared by several
|
|
2376
|
+
* paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
|
|
2377
|
+
* independently would load `posts` twice, and the loaders assign fresh
|
|
2378
|
+
* spread copies — so the second pass would replace the very row objects the
|
|
2379
|
+
* first had already attached children to, and only the last path would
|
|
2380
|
+
* survive.
|
|
2381
|
+
*/
|
|
2382
|
+
static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
|
|
2383
|
+
if (relationNames.length === 0) return;
|
|
2384
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2385
|
+
for (const path of relationNames) {
|
|
2386
|
+
const [head, ...rest] = path.split(".");
|
|
2387
|
+
const tails = groups.get(head) ?? [];
|
|
2388
|
+
groups.set(head, tails);
|
|
2389
|
+
if (rest.length > 0) {
|
|
2390
|
+
const tail = rest.join(".");
|
|
2391
|
+
if (!tails.includes(tail)) {
|
|
2392
|
+
tails.push(tail);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
for (const [head, tails] of groups) {
|
|
2397
|
+
await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* @internal Public since it is reachable from generated code; kept for
|
|
2402
|
+
* backwards compatibility now that the eager loader walks whole path lists.
|
|
2403
|
+
* Internal callers should use {@link loadRelationsInto} instead.
|
|
2347
2404
|
*/
|
|
2348
|
-
static async loadRelationInto(records, relationName) {
|
|
2349
|
-
|
|
2405
|
+
static async loadRelationInto(records, relationName, queryOptions, constraints, pathPrefix = "") {
|
|
2406
|
+
await this.loadRelationsInto(records, [relationName], queryOptions, constraints, pathPrefix);
|
|
2407
|
+
}
|
|
2408
|
+
/**
|
|
2409
|
+
* Load one relation level and recurse into the tails beneath it.
|
|
2410
|
+
*
|
|
2411
|
+
* `constraints` are keyed by the full path of the level each one constrains,
|
|
2412
|
+
* so `pathPrefix` accumulates the path walked so far as the recursion
|
|
2413
|
+
* descends: at `posts.comments` the leaf looks itself up under that whole
|
|
2414
|
+
* key, not under `comments`.
|
|
2415
|
+
*/
|
|
2416
|
+
static async loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix = "") {
|
|
2350
2417
|
const definition = this.getRelationDefinition(head);
|
|
2351
2418
|
if (!definition) {
|
|
2352
2419
|
throw new Error(`${this.name}: unknown relation "${head}".`);
|
|
2353
2420
|
}
|
|
2421
|
+
const currentPath = pathPrefix ? `${pathPrefix}.${head}` : head;
|
|
2422
|
+
const constraint = constraints?.get(currentPath);
|
|
2354
2423
|
switch (definition.type) {
|
|
2355
2424
|
case "hasMany":
|
|
2356
|
-
await this.loadHasMany(records, definition);
|
|
2425
|
+
await this.loadHasMany(records, definition, queryOptions, constraint);
|
|
2357
2426
|
break;
|
|
2358
2427
|
case "hasOne":
|
|
2359
|
-
await this.loadHasOne(records, definition);
|
|
2428
|
+
await this.loadHasOne(records, definition, queryOptions, constraint);
|
|
2360
2429
|
break;
|
|
2361
2430
|
case "belongsTo":
|
|
2362
|
-
await this.loadBelongsTo(records, definition);
|
|
2431
|
+
await this.loadBelongsTo(records, definition, queryOptions, constraint);
|
|
2363
2432
|
break;
|
|
2364
2433
|
case "belongsToMany":
|
|
2365
|
-
await this.loadBelongsToMany(records, definition);
|
|
2434
|
+
await this.loadBelongsToMany(records, definition, queryOptions, constraint);
|
|
2366
2435
|
break;
|
|
2367
2436
|
case "hasManyThrough":
|
|
2368
|
-
await this.loadHasManyThrough(records, definition);
|
|
2437
|
+
await this.loadHasManyThrough(records, definition, queryOptions, constraint);
|
|
2369
2438
|
break;
|
|
2370
2439
|
case "morphMany":
|
|
2371
|
-
await this.loadMorphMany(records, definition);
|
|
2440
|
+
await this.loadMorphMany(records, definition, queryOptions, constraint);
|
|
2372
2441
|
break;
|
|
2373
2442
|
case "morphTo":
|
|
2374
|
-
await this.loadMorphTo(records, definition);
|
|
2443
|
+
await this.loadMorphTo(records, definition, queryOptions, constraint);
|
|
2375
2444
|
break;
|
|
2376
2445
|
}
|
|
2377
|
-
if (
|
|
2446
|
+
if (tails.length === 0) {
|
|
2378
2447
|
return;
|
|
2379
2448
|
}
|
|
2380
2449
|
if (definition.type === "morphTo") {
|
|
@@ -2398,24 +2467,24 @@ var Model = class _Model {
|
|
|
2398
2467
|
return;
|
|
2399
2468
|
}
|
|
2400
2469
|
const related = await resolveModelReference(definition.related);
|
|
2401
|
-
await related.
|
|
2470
|
+
await related.loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
|
|
2402
2471
|
}
|
|
2403
|
-
static async loadHasMany(records, definition) {
|
|
2472
|
+
static async loadHasMany(records, definition, queryOptions, constraint) {
|
|
2404
2473
|
const { foreignKey, localKey, name } = definition;
|
|
2405
2474
|
const related = await resolveModelReference(definition.related);
|
|
2406
|
-
await loadRelationData(records, name, related, localKey, foreignKey, true);
|
|
2475
|
+
await loadRelationData(records, name, related, localKey, foreignKey, true, queryOptions, constraint);
|
|
2407
2476
|
}
|
|
2408
|
-
static async loadHasOne(records, definition) {
|
|
2477
|
+
static async loadHasOne(records, definition, queryOptions, constraint) {
|
|
2409
2478
|
const { foreignKey, localKey, name } = definition;
|
|
2410
2479
|
const related = await resolveModelReference(definition.related);
|
|
2411
|
-
await loadRelationData(records, name, related, localKey, foreignKey, false);
|
|
2480
|
+
await loadRelationData(records, name, related, localKey, foreignKey, false, queryOptions, constraint);
|
|
2412
2481
|
}
|
|
2413
|
-
static async loadBelongsTo(records, definition) {
|
|
2482
|
+
static async loadBelongsTo(records, definition, queryOptions, constraint) {
|
|
2414
2483
|
const { foreignKey, ownerKey, name } = definition;
|
|
2415
2484
|
const related = await resolveModelReference(definition.related);
|
|
2416
|
-
await loadRelationData(records, name, related, foreignKey, ownerKey, false);
|
|
2485
|
+
await loadRelationData(records, name, related, foreignKey, ownerKey, false, queryOptions, constraint);
|
|
2417
2486
|
}
|
|
2418
|
-
static async loadBelongsToMany(records, definition) {
|
|
2487
|
+
static async loadBelongsToMany(records, definition, queryOptions, constraint) {
|
|
2419
2488
|
const { pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, name } = definition;
|
|
2420
2489
|
const related = await resolveModelReference(definition.related);
|
|
2421
2490
|
const parentValues = Array.from(
|
|
@@ -2430,7 +2499,7 @@ var Model = class _Model {
|
|
|
2430
2499
|
const adapter = this.getAdapter();
|
|
2431
2500
|
const pivotRows = await adapter.findMany(pivotTable, {
|
|
2432
2501
|
where: { [foreignPivotKey]: parentValues }
|
|
2433
|
-
});
|
|
2502
|
+
}, queryOptions);
|
|
2434
2503
|
const pivotMap = /* @__PURE__ */ new Map();
|
|
2435
2504
|
const allRelatedIds = /* @__PURE__ */ new Set();
|
|
2436
2505
|
for (const row of pivotRows) {
|
|
@@ -2446,9 +2515,10 @@ var Model = class _Model {
|
|
|
2446
2515
|
}
|
|
2447
2516
|
return;
|
|
2448
2517
|
}
|
|
2449
|
-
const relatedRecords = await
|
|
2450
|
-
[relatedKey]: Array.from(allRelatedIds)
|
|
2451
|
-
|
|
2518
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2519
|
+
related.newQuery(queryOptions).where({ [relatedKey]: Array.from(allRelatedIds) }),
|
|
2520
|
+
constraint
|
|
2521
|
+
);
|
|
2452
2522
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
2453
2523
|
for (const item of relatedRecords) {
|
|
2454
2524
|
relatedMap.set(item[relatedKey], { ...item });
|
|
@@ -2463,7 +2533,7 @@ var Model = class _Model {
|
|
|
2463
2533
|
record[name] = relatedIds.map((id) => relatedMap.get(id)).filter((item) => item != null);
|
|
2464
2534
|
}
|
|
2465
2535
|
}
|
|
2466
|
-
static async loadHasManyThrough(records, definition) {
|
|
2536
|
+
static async loadHasManyThrough(records, definition, queryOptions, constraint) {
|
|
2467
2537
|
const { firstKey, secondKey, localKey, secondLocalKey, name } = definition;
|
|
2468
2538
|
const related = await resolveModelReference(definition.related);
|
|
2469
2539
|
const through = await resolveModelReference(definition.through);
|
|
@@ -2476,7 +2546,7 @@ var Model = class _Model {
|
|
|
2476
2546
|
}
|
|
2477
2547
|
return;
|
|
2478
2548
|
}
|
|
2479
|
-
const throughRecords = await through.where({
|
|
2549
|
+
const throughRecords = await through.newQuery(queryOptions).where({
|
|
2480
2550
|
[firstKey]: localValues
|
|
2481
2551
|
});
|
|
2482
2552
|
const throughMap = /* @__PURE__ */ new Map();
|
|
@@ -2494,9 +2564,10 @@ var Model = class _Model {
|
|
|
2494
2564
|
}
|
|
2495
2565
|
return;
|
|
2496
2566
|
}
|
|
2497
|
-
const relatedRecords = await
|
|
2498
|
-
[secondKey]: Array.from(allThroughIds)
|
|
2499
|
-
|
|
2567
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2568
|
+
related.newQuery(queryOptions).where({ [secondKey]: Array.from(allThroughIds) }),
|
|
2569
|
+
constraint
|
|
2570
|
+
);
|
|
2500
2571
|
const relatedByKey = /* @__PURE__ */ new Map();
|
|
2501
2572
|
for (const item of relatedRecords) {
|
|
2502
2573
|
const key = item[secondKey];
|
|
@@ -2518,7 +2589,7 @@ var Model = class _Model {
|
|
|
2518
2589
|
record[name] = items;
|
|
2519
2590
|
}
|
|
2520
2591
|
}
|
|
2521
|
-
static async loadMorphMany(records, definition) {
|
|
2592
|
+
static async loadMorphMany(records, definition, queryOptions, constraint) {
|
|
2522
2593
|
const { morphName, localKey, name } = definition;
|
|
2523
2594
|
const related = await resolveModelReference(definition.related);
|
|
2524
2595
|
const typeColumn = `${morphName}Type`;
|
|
@@ -2531,12 +2602,13 @@ var Model = class _Model {
|
|
|
2531
2602
|
for (const record of records) record[name] = [];
|
|
2532
2603
|
return;
|
|
2533
2604
|
}
|
|
2534
|
-
const allRelated = await
|
|
2535
|
-
[typeColumn]: parentType,
|
|
2536
|
-
|
|
2537
|
-
|
|
2605
|
+
const allRelated = await applyEagerConstraint(
|
|
2606
|
+
related.newQuery(queryOptions).where({ [typeColumn]: parentType, [idColumn]: localValues }),
|
|
2607
|
+
constraint
|
|
2608
|
+
);
|
|
2538
2609
|
const map = /* @__PURE__ */ new Map();
|
|
2539
2610
|
for (const item of allRelated) {
|
|
2611
|
+
if (item[typeColumn] !== parentType) continue;
|
|
2540
2612
|
const key = item[idColumn];
|
|
2541
2613
|
if (!map.has(key)) map.set(key, []);
|
|
2542
2614
|
map.get(key).push({ ...item });
|
|
@@ -2546,7 +2618,7 @@ var Model = class _Model {
|
|
|
2546
2618
|
record[name] = key != null ? map.get(key) ?? [] : [];
|
|
2547
2619
|
}
|
|
2548
2620
|
}
|
|
2549
|
-
static async loadMorphTo(records, definition) {
|
|
2621
|
+
static async loadMorphTo(records, definition, queryOptions, constraint) {
|
|
2550
2622
|
const { morphName, name } = definition;
|
|
2551
2623
|
const typeColumn = `${morphName}Type`;
|
|
2552
2624
|
const idColumn = `${morphName}Id`;
|
|
@@ -2564,7 +2636,10 @@ var Model = class _Model {
|
|
|
2564
2636
|
const modelClass = morphMap[type];
|
|
2565
2637
|
if (!modelClass) continue;
|
|
2566
2638
|
const uniqueIds = Array.from(new Set(ids));
|
|
2567
|
-
const results = await
|
|
2639
|
+
const results = await applyEagerConstraint(
|
|
2640
|
+
modelClass.newQuery(queryOptions).where({ id: uniqueIds }),
|
|
2641
|
+
constraint
|
|
2642
|
+
);
|
|
2568
2643
|
const idMap = /* @__PURE__ */ new Map();
|
|
2569
2644
|
for (const r of results) idMap.set(r.id, { ...r });
|
|
2570
2645
|
resolved.set(type, idMap);
|
|
@@ -2580,7 +2655,11 @@ var Model = class _Model {
|
|
|
2580
2655
|
}
|
|
2581
2656
|
}
|
|
2582
2657
|
};
|
|
2583
|
-
async function
|
|
2658
|
+
async function applyEagerConstraint(query, constraint) {
|
|
2659
|
+
constraint?.(query);
|
|
2660
|
+
return await query;
|
|
2661
|
+
}
|
|
2662
|
+
async function loadRelationData(records, name, related, parentKey, relatedKey, isArray, queryOptions, constraint) {
|
|
2584
2663
|
const values = Array.from(
|
|
2585
2664
|
new Set(records.map((r) => r[parentKey]).filter((v) => v != null))
|
|
2586
2665
|
);
|
|
@@ -2590,7 +2669,10 @@ async function loadRelationData(records, name, related, parentKey, relatedKey, i
|
|
|
2590
2669
|
}
|
|
2591
2670
|
return;
|
|
2592
2671
|
}
|
|
2593
|
-
const relatedRecords = await
|
|
2672
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2673
|
+
related.newQuery(queryOptions).where({ [relatedKey]: values }),
|
|
2674
|
+
constraint
|
|
2675
|
+
);
|
|
2594
2676
|
const map = /* @__PURE__ */ new Map();
|
|
2595
2677
|
for (const item of relatedRecords) {
|
|
2596
2678
|
const key = item[relatedKey];
|
|
@@ -2880,26 +2962,29 @@ function releaseActiveConnection(key, teardown) {
|
|
|
2880
2962
|
// src/migration-utils.ts
|
|
2881
2963
|
import { existsSync, readdirSync } from "fs";
|
|
2882
2964
|
import { resolve } from "path";
|
|
2883
|
-
function
|
|
2965
|
+
function inspectMigrationsFolder(migrationsFolder) {
|
|
2884
2966
|
if (!existsSync(migrationsFolder)) {
|
|
2885
|
-
return
|
|
2967
|
+
return { migrationsFolder, migrationsFound: 0, looseSqlFiles: 0 };
|
|
2886
2968
|
}
|
|
2887
2969
|
const entries = readdirSync(migrationsFolder, { withFileTypes: true });
|
|
2888
|
-
return
|
|
2889
|
-
|
|
2890
|
-
|
|
2970
|
+
return {
|
|
2971
|
+
migrationsFolder,
|
|
2972
|
+
migrationsFound: entries.filter(
|
|
2973
|
+
(entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))
|
|
2974
|
+
).length,
|
|
2975
|
+
looseSqlFiles: entries.filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).length
|
|
2976
|
+
};
|
|
2891
2977
|
}
|
|
2892
|
-
function
|
|
2893
|
-
if (
|
|
2894
|
-
return;
|
|
2978
|
+
function noMigrationsToRun(summary) {
|
|
2979
|
+
if (summary.looseSqlFiles === 0) {
|
|
2980
|
+
return summary;
|
|
2895
2981
|
}
|
|
2896
|
-
const flatSqlFiles = readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name);
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
`[guren/orm] Ignoring ${flatSqlFiles.length} loose .sql file(s) in ${migrationsFolder}: ${flatSqlFiles.join(", ")}.
|
|
2982
|
+
const flatSqlFiles = readdirSync(summary.migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".sql")).map((entry) => entry.name);
|
|
2983
|
+
console.warn(
|
|
2984
|
+
`[guren/orm] Ignoring ${flatSqlFiles.length} loose .sql file(s) in ${summary.migrationsFolder}: ${flatSqlFiles.join(", ")}.
|
|
2900
2985
|
[guren/orm] Migrations must be generated with drizzle-kit (\`bun run db:make\`), which creates one folder per migration.`
|
|
2901
|
-
|
|
2902
|
-
|
|
2986
|
+
);
|
|
2987
|
+
return summary;
|
|
2903
2988
|
}
|
|
2904
2989
|
var PRE_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2905
2990
|
"CONNECT_TIMEOUT",
|
|
@@ -3004,6 +3089,10 @@ import { readdir } from "fs/promises";
|
|
|
3004
3089
|
import { extname, resolve as resolve2 } from "path";
|
|
3005
3090
|
import { fileURLToPath, pathToFileURL } from "url";
|
|
3006
3091
|
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".ts"]);
|
|
3092
|
+
var DECLARATION_SUFFIXES = [".d.ts", ".d.mts", ".d.cts"];
|
|
3093
|
+
function isSeederCandidate(name) {
|
|
3094
|
+
return SUPPORTED_EXTENSIONS.has(extname(name)) && !DECLARATION_SUFFIXES.some((suffix) => name.endsWith(suffix));
|
|
3095
|
+
}
|
|
3007
3096
|
function normalizeSeeder(candidate) {
|
|
3008
3097
|
if (!candidate) {
|
|
3009
3098
|
return void 0;
|
|
@@ -3045,10 +3134,18 @@ async function loadSeederModule(path) {
|
|
|
3045
3134
|
}
|
|
3046
3135
|
return void 0;
|
|
3047
3136
|
}
|
|
3048
|
-
async function
|
|
3137
|
+
async function collectSeeders(directory) {
|
|
3049
3138
|
const root = directory instanceof URL ? fileURLToPath(directory) : resolve2(directory);
|
|
3050
|
-
|
|
3051
|
-
|
|
3139
|
+
let entries;
|
|
3140
|
+
try {
|
|
3141
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
3142
|
+
} catch (error) {
|
|
3143
|
+
if (error?.code !== "ENOENT") {
|
|
3144
|
+
throw error;
|
|
3145
|
+
}
|
|
3146
|
+
return { root, seeders: [], filesWithoutSeeder: 0 };
|
|
3147
|
+
}
|
|
3148
|
+
const files = entries.filter((entry) => entry.isFile() && isSeederCandidate(entry.name)).map((entry) => resolve2(root, entry.name)).sort();
|
|
3052
3149
|
const seeders = [];
|
|
3053
3150
|
for (const file of files) {
|
|
3054
3151
|
const handler = await loadSeederModule(file);
|
|
@@ -3056,13 +3153,17 @@ async function loadSeeders(directory) {
|
|
|
3056
3153
|
seeders.push(handler);
|
|
3057
3154
|
}
|
|
3058
3155
|
}
|
|
3059
|
-
return seeders;
|
|
3156
|
+
return { root, seeders, filesWithoutSeeder: files.length - seeders.length };
|
|
3157
|
+
}
|
|
3158
|
+
async function loadSeeders(directory) {
|
|
3159
|
+
return (await collectSeeders(directory)).seeders;
|
|
3060
3160
|
}
|
|
3061
3161
|
async function runSeeders(db, directory) {
|
|
3062
|
-
const seeders = await
|
|
3162
|
+
const { root, seeders, filesWithoutSeeder } = await collectSeeders(directory);
|
|
3063
3163
|
for (const handler of seeders) {
|
|
3064
3164
|
await handler({ db });
|
|
3065
3165
|
}
|
|
3166
|
+
return { seedersFolder: root, seedersRan: seeders.length, filesWithoutSeeder };
|
|
3066
3167
|
}
|
|
3067
3168
|
function defineSeeder(handler) {
|
|
3068
3169
|
return handler;
|
|
@@ -3124,9 +3225,9 @@ function createPostgresDatabase(options) {
|
|
|
3124
3225
|
const migrations = singleFlight(async () => {
|
|
3125
3226
|
let endpoint;
|
|
3126
3227
|
try {
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
return;
|
|
3228
|
+
const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
|
|
3229
|
+
if (summary.migrationsFound === 0) {
|
|
3230
|
+
return noMigrationsToRun(summary);
|
|
3130
3231
|
}
|
|
3131
3232
|
const { drizzle, migrate, postgres: postgresFactory } = await loadPostgresModules();
|
|
3132
3233
|
const url = resolveConnectionString();
|
|
@@ -3141,6 +3242,7 @@ function createPostgresDatabase(options) {
|
|
|
3141
3242
|
} finally {
|
|
3142
3243
|
await migrationClient.end({ timeout: 0 });
|
|
3143
3244
|
}
|
|
3245
|
+
return summary;
|
|
3144
3246
|
} catch (error) {
|
|
3145
3247
|
throw migrationFailure(error, endpoint);
|
|
3146
3248
|
}
|
|
@@ -3189,7 +3291,7 @@ function createPostgresDatabase(options) {
|
|
|
3189
3291
|
}
|
|
3190
3292
|
const db = await database2.get();
|
|
3191
3293
|
try {
|
|
3192
|
-
await runSeeders(db, resolvedSeedersFolder);
|
|
3294
|
+
return await runSeeders(db, resolvedSeedersFolder);
|
|
3193
3295
|
} catch (error) {
|
|
3194
3296
|
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
3195
3297
|
}
|
|
@@ -3216,7 +3318,7 @@ function createPostgresDatabase(options) {
|
|
|
3216
3318
|
await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
|
|
3217
3319
|
});
|
|
3218
3320
|
migrations.reset();
|
|
3219
|
-
|
|
3321
|
+
return migrations.get();
|
|
3220
3322
|
}
|
|
3221
3323
|
async function migrationStatus() {
|
|
3222
3324
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3282,9 +3384,9 @@ function createMySqlDatabase(options) {
|
|
|
3282
3384
|
const migrations = singleFlight(async () => {
|
|
3283
3385
|
let endpoint;
|
|
3284
3386
|
try {
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
return;
|
|
3387
|
+
const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
|
|
3388
|
+
if (summary.migrationsFound === 0) {
|
|
3389
|
+
return noMigrationsToRun(summary);
|
|
3288
3390
|
}
|
|
3289
3391
|
const { drizzle, migrate, createPool } = await loadMySqlModules();
|
|
3290
3392
|
const url = resolveConnectionString();
|
|
@@ -3299,6 +3401,7 @@ function createMySqlDatabase(options) {
|
|
|
3299
3401
|
} finally {
|
|
3300
3402
|
await closePool(migrationClient);
|
|
3301
3403
|
}
|
|
3404
|
+
return summary;
|
|
3302
3405
|
} catch (error) {
|
|
3303
3406
|
throw migrationFailure(error, endpoint);
|
|
3304
3407
|
}
|
|
@@ -3344,7 +3447,7 @@ function createMySqlDatabase(options) {
|
|
|
3344
3447
|
}
|
|
3345
3448
|
const db = await database2.get();
|
|
3346
3449
|
try {
|
|
3347
|
-
await runSeeders(db, resolvedSeedersFolder);
|
|
3450
|
+
return await runSeeders(db, resolvedSeedersFolder);
|
|
3348
3451
|
} catch (error) {
|
|
3349
3452
|
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
3350
3453
|
}
|
|
@@ -3383,7 +3486,7 @@ function createMySqlDatabase(options) {
|
|
|
3383
3486
|
}
|
|
3384
3487
|
});
|
|
3385
3488
|
migrations.reset();
|
|
3386
|
-
|
|
3489
|
+
return migrations.get();
|
|
3387
3490
|
}
|
|
3388
3491
|
async function migrationStatus() {
|
|
3389
3492
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3424,6 +3527,13 @@ import { fileURLToPath as fileURLToPath4 } from "url";
|
|
|
3424
3527
|
function isInMemory(dbPath) {
|
|
3425
3528
|
return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
|
|
3426
3529
|
}
|
|
3530
|
+
var CONNECTION_URI = /^(?!file:)[a-z][a-z0-9+.-]+:\/\//i;
|
|
3531
|
+
function assertNotConnectionUri(dbPath, source) {
|
|
3532
|
+
if (!CONNECTION_URI.test(dbPath)) return;
|
|
3533
|
+
throw new Error(
|
|
3534
|
+
`createSqliteDatabase() received a connection URI where it expects a file path: ${dbPath} (from ${source}). Left alone it would be created as a directory tree and migrated into silently. Pass a path such as "./data/guren.db", or ":memory:".`
|
|
3535
|
+
);
|
|
3536
|
+
}
|
|
3427
3537
|
function createSqliteDatabase(options) {
|
|
3428
3538
|
const { migrationsFolder, filename, seedersFolder, relations } = options;
|
|
3429
3539
|
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
|
|
@@ -3433,7 +3543,16 @@ function createSqliteDatabase(options) {
|
|
|
3433
3543
|
const callSite = new Error().stack;
|
|
3434
3544
|
function resolveFilename() {
|
|
3435
3545
|
const value = typeof filename === "function" ? filename() : filename;
|
|
3436
|
-
|
|
3546
|
+
if (value != null) {
|
|
3547
|
+
assertNotConnectionUri(value, 'the "filename" option');
|
|
3548
|
+
return value;
|
|
3549
|
+
}
|
|
3550
|
+
const fromEnv = process.env.DATABASE_URL;
|
|
3551
|
+
if (fromEnv != null) {
|
|
3552
|
+
assertNotConnectionUri(fromEnv, "DATABASE_URL");
|
|
3553
|
+
return fromEnv;
|
|
3554
|
+
}
|
|
3555
|
+
return "./data/guren.db";
|
|
3437
3556
|
}
|
|
3438
3557
|
const database2 = singleFlight(async () => {
|
|
3439
3558
|
const dbPath = resolveFilename();
|
|
@@ -3471,13 +3590,14 @@ function createSqliteDatabase(options) {
|
|
|
3471
3590
|
}
|
|
3472
3591
|
const migrations = singleFlight(async () => {
|
|
3473
3592
|
try {
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
return;
|
|
3593
|
+
const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
|
|
3594
|
+
if (summary.migrationsFound === 0) {
|
|
3595
|
+
return noMigrationsToRun(summary);
|
|
3477
3596
|
}
|
|
3478
3597
|
const db = await database2.get();
|
|
3479
3598
|
const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
|
|
3480
3599
|
await migrate(db, { migrationsFolder: resolvedMigrationsFolder });
|
|
3600
|
+
return summary;
|
|
3481
3601
|
} catch (error) {
|
|
3482
3602
|
throw migrationFailure(error);
|
|
3483
3603
|
}
|
|
@@ -3491,7 +3611,7 @@ function createSqliteDatabase(options) {
|
|
|
3491
3611
|
closeDatabase,
|
|
3492
3612
|
async resetDatabase() {
|
|
3493
3613
|
await database2.get();
|
|
3494
|
-
if (!sqliteClient) return;
|
|
3614
|
+
if (!sqliteClient) return void 0;
|
|
3495
3615
|
const objects = sqliteClient.query(
|
|
3496
3616
|
"SELECT name, type FROM main.sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'"
|
|
3497
3617
|
).all();
|
|
@@ -3505,7 +3625,7 @@ function createSqliteDatabase(options) {
|
|
|
3505
3625
|
sqliteClient.exec("PRAGMA foreign_keys = ON;");
|
|
3506
3626
|
}
|
|
3507
3627
|
migrations.reset();
|
|
3508
|
-
|
|
3628
|
+
return migrations.get();
|
|
3509
3629
|
},
|
|
3510
3630
|
async migrationStatus() {
|
|
3511
3631
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3530,7 +3650,7 @@ function createSqliteDatabase(options) {
|
|
|
3530
3650
|
}
|
|
3531
3651
|
const db = await database2.get();
|
|
3532
3652
|
try {
|
|
3533
|
-
await runSeeders(db, resolvedSeedersFolder);
|
|
3653
|
+
return await runSeeders(db, resolvedSeedersFolder);
|
|
3534
3654
|
} catch (error) {
|
|
3535
3655
|
throw seedFailure(error);
|
|
3536
3656
|
}
|
|
@@ -3639,12 +3759,13 @@ function createAwsDataApiDatabase(options) {
|
|
|
3639
3759
|
}
|
|
3640
3760
|
const migrations = singleFlight(async () => {
|
|
3641
3761
|
try {
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
return;
|
|
3762
|
+
const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
|
|
3763
|
+
if (summary.migrationsFound === 0) {
|
|
3764
|
+
return noMigrationsToRun(summary);
|
|
3645
3765
|
}
|
|
3646
3766
|
const { migrate } = await loadAwsDataApiModules();
|
|
3647
3767
|
await withAdminDb((db) => migrate(db, { migrationsFolder: resolvedMigrationsFolder }));
|
|
3768
|
+
return summary;
|
|
3648
3769
|
} catch (error) {
|
|
3649
3770
|
const reason = error instanceof Error ? error.message : String(error);
|
|
3650
3771
|
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
@@ -3689,7 +3810,7 @@ function createAwsDataApiDatabase(options) {
|
|
|
3689
3810
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createAwsDataApiDatabase().');
|
|
3690
3811
|
}
|
|
3691
3812
|
const db = await databaseHandle.get();
|
|
3692
|
-
|
|
3813
|
+
return runSeeders(db, resolvedSeedersFolder);
|
|
3693
3814
|
}
|
|
3694
3815
|
async function withAdminDb(callback) {
|
|
3695
3816
|
const { drizzle } = await loadAwsDataApiModules();
|
|
@@ -3708,7 +3829,7 @@ function createAwsDataApiDatabase(options) {
|
|
|
3708
3829
|
await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
|
|
3709
3830
|
});
|
|
3710
3831
|
migrations.reset();
|
|
3711
|
-
|
|
3832
|
+
return migrations.get();
|
|
3712
3833
|
}
|
|
3713
3834
|
async function migrationStatus() {
|
|
3714
3835
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|