@guren/orm 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +161 -53
  2. package/dist/index.js +456 -132
  3. package/package.json +6 -1
package/dist/index.d.ts CHANGED
@@ -2,6 +2,10 @@ import { SQL } from 'drizzle-orm';
2
2
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
3
3
  import postgres from 'postgres';
4
4
  import { MySql2Database } from 'drizzle-orm/mysql2';
5
+ import * as drizzle_orm_aws_data_api_pg from 'drizzle-orm/aws-data-api/pg';
6
+ import { AwsDataApiPgDatabase as AwsDataApiPgDatabase$1 } from 'drizzle-orm/aws-data-api/pg';
7
+ import { RDSDataClientConfig } from '@aws-sdk/client-rds-data';
8
+ import { SQLiteBunDatabase } from 'drizzle-orm/bun-sqlite';
5
9
 
6
10
  /** Accessor function: transforms a record field value after reading from DB. */
7
11
  type AccessorFn<T = unknown> = (record: PlainObject) => T;
@@ -213,8 +217,11 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
213
217
  *
214
218
  * Mass-assignment protection applies exactly as in `Model.update()`:
215
219
  * with a `fillable` allowlist, out-of-allowlist keys throw a
216
- * MassAssignmentException. Note that bulk updates skip model hooks,
217
- * observers, mutators, and casts by design.
220
+ * MassAssignmentException. The payload also runs through the same
221
+ * persistence preparation as `Model.update()` — mutators, casts, and
222
+ * `preparePersistencePayload` overrides (e.g. password hashing on
223
+ * authenticatable models). Per-record hooks and observers are still
224
+ * skipped by design.
218
225
  *
219
226
  * @param data - Data to set on matching records
220
227
  * @returns The updated record (adapter-dependent)
@@ -506,10 +513,14 @@ type SelectFrom<TDatabase> = TDatabase extends {
506
513
  * CRUD, querying, pagination, and eager-loading of relationships.
507
514
  *
508
515
  * @example
509
- * // Define a model
510
- * class User extends Model<UserRecord> {
516
+ * // Define a model — recordType/createType are inferred from the Drizzle table
517
+ * class User extends defineModel(users) {}
518
+ *
519
+ * // Or, when extending Model directly, redeclare the type markers
520
+ * class LegacyUser extends Model<UserRecord> {
511
521
  * static override table = users // Drizzle table
512
- * static override readonly recordType = {} as UserRecord
522
+ * declare static readonly recordType: UserRecord
523
+ * declare static readonly createType: NewUserRecord
513
524
  * }
514
525
  *
515
526
  * // Query records
@@ -532,9 +543,9 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
532
543
  protected static ormAdapter: ORMAdapter;
533
544
  /** The database table (e.g., Drizzle table schema). */
534
545
  protected static table: unknown;
535
- /** Type marker for TypeScript inference. Define as `{} as YourRecordType`. */
546
+ /** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
536
547
  static readonly recordType: unknown;
537
- /** Type marker for insert/update payload inference. Define as `{} as typeof table.$inferInsert`. */
548
+ /** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
538
549
  static readonly createType: unknown;
539
550
  protected static relationDefinitions?: Map<string, RelationDefinition>;
540
551
  /** Type marker for relation types. Define relation types here for type inference. */
@@ -595,8 +606,11 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
595
606
  * containing any other key throws a MassAssignmentException so bugs
596
607
  * (and injection attempts) surface immediately instead of being
597
608
  * silently discarded. Use `forceCreate()` / `forceUpdate()` for
598
- * trusted server-side data, or set `strictFillable = false` to
599
- * restore silent discarding.
609
+ * trusted server-side data.
610
+ *
611
+ * The primary key (`id`) is always silently stripped from mass-assignment
612
+ * input, and fields returned by `deniedFields()` always throw — neither
613
+ * depends on `fillable`.
600
614
  *
601
615
  * @example
602
616
  * class User extends Model<UserRecord> {
@@ -605,21 +619,14 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
605
619
  */
606
620
  static fillable?: string[];
607
621
  /**
608
- * When `fillable` is set, controls what happens to input fields outside
609
- * the allowlist: `true` (default) throws a MassAssignmentException,
610
- * `false` silently discards them (pre-1.0 behavior).
622
+ * Fields that can never be mass-assigned, resolved at call time so
623
+ * subclasses can derive them from their own configuration (e.g.
624
+ * `AuthenticatableModel` contributes its resolved password-hash and
625
+ * remember-token columns). Input containing any of these throws a
626
+ * MassAssignmentException regardless of `fillable` — use
627
+ * `forceCreate()` / `forceUpdate()` for trusted server-side values.
611
628
  */
612
- static strictFillable?: boolean;
613
- /**
614
- * Blacklist of fields excluded from mass assignment.
615
- * Defaults to `['id']`. Ignored if `fillable` is set.
616
- *
617
- * @example
618
- * class Post extends Model<PostRecord> {
619
- * static guarded = ['id', 'createdAt']
620
- * }
621
- */
622
- static guarded?: string[];
629
+ protected static deniedFields(): string[];
623
630
  /**
624
631
  * Accessor functions for computed/virtual attributes.
625
632
  * Applied after reading records from the database.
@@ -765,14 +772,19 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
765
772
  /**
766
773
  * Filter input data based on mass assignment protection rules.
767
774
  *
768
- * If `fillable` is defined, only fields listed in `fillable` are kept.
769
- * Otherwise, fields listed in `guarded` (default: `['id']`) are removed.
775
+ * Applied in order: fields returned by `deniedFields()` throw a
776
+ * MassAssignmentException (checked on the raw input, so no other rule
777
+ * can silently swallow them); the primary key (`id`) is silently
778
+ * stripped; when `fillable` is defined, any remaining field outside it
779
+ * throws and only listed fields are kept.
770
780
  *
771
781
  * @param data - The input data to filter
772
782
  * @returns Filtered data safe for mass assignment
773
783
  */
774
784
  static filterFillable(data: PlainObject): PlainObject;
775
785
  protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
786
+ /** @internal Lets QueryBuilder bulk updates run the same payload preparation as `Model.update()`. */
787
+ static prepareBulkPersistencePayload(data: PlainObject): Promise<PlainObject>;
776
788
  protected static getRelationDefinitions(): Map<string, RelationDefinition>;
777
789
  /** @internal */
778
790
  static getRelationDefinition(name: string): RelationDefinition | undefined;
@@ -1356,22 +1368,48 @@ type MorphToRelationResult = PlainObject | null;
1356
1368
  type MorphToRecord = PlainObject | null;
1357
1369
  /** Utility type: model record with specified relations merged. */
1358
1370
  type WithRelations<T extends typeof Model, K extends RelationPath<T> | readonly RelationPath<T>[]> = TRecordFor<T> & RelationTypePick<T, K>;
1359
- type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model = typeof Model, TCreate extends PlainObject = InferModelInsert<TTable> & TCreateFor<TBase>> = TBase & {
1371
+ type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model, TCreate extends PlainObject> = TBase & {
1360
1372
  readonly table: TTable;
1361
1373
  readonly recordType: InferModelRecord<TTable>;
1362
1374
  readonly createType: TCreate;
1363
1375
  };
1376
+ /** A key that can appear in a model's create payload: a table column, or a named field its base contributes. */
1377
+ type CreateKey<TTable extends TableShape, TBase extends typeof Model> = keyof InferModelInsert<TTable> | keyof TCreateFor<TBase>;
1378
+ type CreateShape<TTable extends TableShape, TBase extends typeof Model, TOptional extends keyof InferModelInsert<TTable>, TRequire extends CreateKey<TTable, TBase>> = Partial<Pick<InferModelInsert<TTable>, TOptional>> & Omit<InferModelInsert<TTable>, TOptional> & TCreateFor<TBase> & Required<Pick<InferModelInsert<TTable> & TCreateFor<TBase>, TRequire & keyof (InferModelInsert<TTable> & TCreateFor<TBase>)>>;
1364
1379
  /**
1365
1380
  * Create a table-backed model base class from a Drizzle table.
1366
1381
  *
1382
+ * `recordType` and `createType` are inferred from the table. The inferred
1383
+ * createType requires every non-defaulted column, which is not always the
1384
+ * payload a model accepts: `AuthenticatableModel` hashes a plain `password`
1385
+ * into `passwordHash`, so a user model wants the column optional and the
1386
+ * virtual field required. `optionalOnCreate` and `requireOnCreate` reshape the
1387
+ * inferred type without any cast.
1388
+ *
1367
1389
  * @example
1368
1390
  * export class Post extends defineModel(posts) {}
1369
- * export class User extends defineModel(users, { base: AuthenticatableModel }) {}
1391
+ *
1392
+ * export class User extends defineModel(users, {
1393
+ * base: AuthenticatableModel,
1394
+ * optionalOnCreate: ['passwordHash'],
1395
+ * requireOnCreate: ['password'],
1396
+ * }) {}
1370
1397
  */
1371
- declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, TCreate extends PlainObject = InferModelInsert<TTable> & TCreateFor<TBase>>(table: TTable, options?: {
1398
+ declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, const TOptional extends keyof InferModelInsert<TTable> = never, const TRequire extends CreateKey<TTable, TBase> = never>(table: TTable, options?: {
1372
1399
  base?: TBase;
1373
- createType?: TCreate;
1374
- }): ModelClassWithTable<TTable, TBase, TCreate>;
1400
+ /**
1401
+ * Columns the model fills in itself, so callers need not pass them.
1402
+ * Type-level only.
1403
+ */
1404
+ optionalOnCreate?: readonly TOptional[];
1405
+ /**
1406
+ * Fields to make required on the create payload. Accepts table columns
1407
+ * (Drizzle marks defaulted ones optional) and named fields contributed by
1408
+ * `base`, such as `AuthenticatableModel`'s virtual `password`.
1409
+ * Type-level only.
1410
+ */
1411
+ requireOnCreate?: readonly TRequire[];
1412
+ }): ModelClassWithTable<TTable, TBase, CreateShape<TTable, TBase, TOptional, TRequire>>;
1375
1413
 
1376
1414
  /**
1377
1415
  * Exception thrown when a model is not found via findOrFail or firstOrFail.
@@ -1387,15 +1425,24 @@ declare class ModelNotFoundException extends Error {
1387
1425
  }
1388
1426
 
1389
1427
  /**
1390
- * Thrown when mass assignment receives fields outside the model's
1391
- * `fillable` allowlist. Silently discarding them hides bugs (a typo'd
1392
- * fillable entry surfaces as a NOT NULL violation much later) and can
1393
- * mask injection attempts, so strict models fail loudly instead.
1428
+ * Thrown when mass assignment receives fields it must not write. Silently
1429
+ * discarding them hides bugs (a typo'd fillable entry surfaces as a NOT NULL
1430
+ * violation much later) and can mask injection attempts, so models fail
1431
+ * loudly instead.
1432
+ *
1433
+ * `reason` distinguishes the two rules that throw:
1434
+ * - `'not-fillable'` — the field is outside the model's `fillable` allowlist.
1435
+ * - `'denied'` — the field is in the model's `deniedFields()` (e.g. a
1436
+ * credential column on an authenticatable model) and can never be
1437
+ * mass-assigned, `fillable` notwithstanding.
1394
1438
  */
1395
1439
  declare class MassAssignmentException extends Error {
1396
1440
  readonly model: string;
1397
1441
  readonly fields: string[];
1398
- constructor(model: string, fields: string[]);
1442
+ readonly reason: 'not-fillable' | 'denied';
1443
+ constructor(model: string, fields: string[], options?: {
1444
+ reason?: 'not-fillable' | 'denied';
1445
+ });
1399
1446
  }
1400
1447
 
1401
1448
  /**
@@ -1423,9 +1470,7 @@ interface SoftDeletesStatic {
1423
1470
  * records via a global scope named 'softDelete'.
1424
1471
  *
1425
1472
  * @example
1426
- * class Post extends SoftDeletes(Model)<PostRecord> {
1427
- * static table = posts
1428
- * }
1473
+ * class Post extends SoftDeletes(defineModel(posts)) {}
1429
1474
  *
1430
1475
  * // Soft delete a record (sets deletedAt)
1431
1476
  * await Post.delete({ id: 1 })
@@ -1513,10 +1558,10 @@ interface MigrationStatusEntry {
1513
1558
  appliedAt: Date | null;
1514
1559
  }
1515
1560
 
1516
- type ConnectionResolver$2 = string | (() => string | undefined);
1561
+ type ConnectionResolver$3 = string | (() => string | undefined);
1517
1562
  interface PostgresDatabaseOptions {
1518
1563
  migrationsFolder: string | URL;
1519
- connectionString?: ConnectionResolver$2;
1564
+ connectionString?: ConnectionResolver$3;
1520
1565
  clientOptions?: postgres.Options<Record<string, never>>;
1521
1566
  seedersFolder?: string | URL;
1522
1567
  /**
@@ -1539,11 +1584,11 @@ interface PostgresDatabase {
1539
1584
  }
1540
1585
  declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
1541
1586
 
1542
- type ConnectionResolver$1 = string | (() => string | undefined);
1587
+ type ConnectionResolver$2 = string | (() => string | undefined);
1543
1588
  type MySqlConnectionOptions = Record<string, unknown>;
1544
1589
  interface MySqlDatabaseOptions {
1545
1590
  migrationsFolder: string | URL;
1546
- connectionString?: ConnectionResolver$1;
1591
+ connectionString?: ConnectionResolver$2;
1547
1592
  clientOptions?: MySqlConnectionOptions;
1548
1593
  seedersFolder?: string | URL;
1549
1594
  /**
@@ -1559,18 +1604,18 @@ interface MySqlDatabase {
1559
1604
  closeDatabase(): Promise<void>;
1560
1605
  configureOrm(): Promise<void>;
1561
1606
  seedDatabase(): Promise<void>;
1562
- /** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1607
+ /** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1563
1608
  resetDatabase(): Promise<void>;
1564
1609
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1565
1610
  migrationStatus(): Promise<MigrationStatusEntry[]>;
1566
1611
  }
1567
1612
  declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
1568
1613
 
1569
- type ConnectionResolver = string | (() => string | undefined);
1614
+ type ConnectionResolver$1 = string | (() => string | undefined);
1570
1615
  interface SqliteDatabaseOptions {
1571
1616
  migrationsFolder: string | URL;
1572
1617
  /** Path to the SQLite database file. Defaults to `./data/guren.db`. */
1573
- filename?: ConnectionResolver;
1618
+ filename?: ConnectionResolver$1;
1574
1619
  seedersFolder?: string | URL;
1575
1620
  /**
1576
1621
  * Drizzle relations for RQB v2 (`db.query.*`).
@@ -1585,7 +1630,7 @@ interface SqliteDatabase {
1585
1630
  closeDatabase(): Promise<void>;
1586
1631
  configureOrm(): Promise<void>;
1587
1632
  seedDatabase(): Promise<void>;
1588
- /** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1633
+ /** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
1589
1634
  resetDatabase(): Promise<void>;
1590
1635
  /** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
1591
1636
  migrationStatus(): Promise<MigrationStatusEntry[]>;
@@ -1632,13 +1677,76 @@ interface D1DatabaseHandle {
1632
1677
  */
1633
1678
  declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1634
1679
 
1635
- interface SeederContext {
1636
- db: PostgresJsDatabase;
1680
+ type ConnectionResolver = string | (() => string | undefined);
1681
+ type AwsDataApiPgDatabase = drizzle_orm_aws_data_api_pg.AwsDataApiPgDatabase;
1682
+ interface AwsDataApiDatabaseOptions {
1683
+ migrationsFolder: string | URL;
1684
+ /** Database name. Falls back to the DATABASE_NAME environment variable. */
1685
+ database?: ConnectionResolver;
1686
+ /** Aurora cluster ARN. Falls back to the DATABASE_RESOURCE_ARN environment variable. */
1687
+ resourceArn?: ConnectionResolver;
1688
+ /** Secrets Manager secret ARN holding the credentials. Falls back to the DATABASE_SECRET_ARN environment variable. */
1689
+ secretArn?: ConnectionResolver;
1690
+ /** Extra RDSDataClient configuration (region, credentials, ...). */
1691
+ clientOptions?: RDSDataClientConfig;
1692
+ /**
1693
+ * Run pending migrations on the first `getDatabase()` call, like the other
1694
+ * database factories do. Off by default: on Lambda that check runs on every
1695
+ * cold start and costs several serialized Data API round trips before the
1696
+ * first query. Run migrations out of band instead — `db:migrate` locally,
1697
+ * or the console handler (`{"command": "db:migrate"}`) once deployed.
1698
+ */
1699
+ migrateOnStart?: boolean;
1700
+ seedersFolder?: string | URL;
1701
+ /**
1702
+ * Drizzle relations for RQB v2 (`db.query.*`).
1703
+ * Build with `defineRelations(schema, ...)` from `drizzle-orm`,
1704
+ * or with `relations()` from `drizzle-orm/_relations` for the RQB v1 partial-upgrade path.
1705
+ */
1706
+ relations?: Record<string, unknown>;
1707
+ }
1708
+ interface AwsDataApiDatabase {
1709
+ getDatabase(): Promise<AwsDataApiPgDatabase>;
1710
+ migrateDatabase(): Promise<void>;
1711
+ closeDatabase(): Promise<void>;
1712
+ configureOrm(): Promise<void>;
1713
+ seedDatabase(): Promise<void>;
1714
+ /** Drops the public schema (and the drizzle tracker schema) so migrations can be re-applied from scratch. */
1715
+ resetDatabase(): Promise<void>;
1716
+ /** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
1717
+ migrationStatus(): Promise<MigrationStatusEntry[]>;
1718
+ }
1719
+ declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
1720
+
1721
+ /**
1722
+ * The context a seeder receives. `db` is the drizzle database the app
1723
+ * configured, so its type depends on the dialect: annotate the seeder with the
1724
+ * matching alias below (or pass the driver's own database type) whenever the
1725
+ * app is not on PostgreSQL.
1726
+ *
1727
+ * The type parameter defaults to `PostgresJsDatabase` for backwards
1728
+ * compatibility — seeders written before this was generic keep compiling.
1729
+ */
1730
+ interface SeederContext<TDatabase = PostgresJsDatabase> {
1731
+ db: TDatabase;
1637
1732
  }
1638
- type SeederHandler = (context: SeederContext) => unknown;
1639
- declare function loadSeeders(directory: string | URL): Promise<Array<SeederHandler>>;
1640
- declare function runSeeders(db: PostgresJsDatabase, directory: string | URL): Promise<void>;
1641
- declare function defineSeeder(handler: SeederHandler): SeederHandler;
1733
+ type SeederHandler<TDatabase = PostgresJsDatabase> = (context: SeederContext<TDatabase>) => unknown;
1734
+ /** Seeder context for apps created with `createPostgresDatabase()`. */
1735
+ type PostgresSeederContext = SeederContext<PostgresJsDatabase>;
1736
+ /** Seeder context for apps created with `createMySqlDatabase()`. */
1737
+ type MySqlSeederContext = SeederContext<MySql2Database>;
1738
+ /** Seeder context for apps created with `createSqliteDatabase()`. */
1739
+ type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
1740
+ /** Seeder context for apps created with `createAwsDataApiDatabase()`. */
1741
+ type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase$1>;
1742
+ /**
1743
+ * Seeders are loaded as modules, so the dialect they were written against is
1744
+ * unknowable here. `TDatabase` is the caller stating which database it will
1745
+ * hand them — the same contract `runSeeders()` fulfils from the driver side.
1746
+ */
1747
+ declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
1748
+ declare function runSeeders<TDatabase>(db: TDatabase, directory: string | URL): Promise<void>;
1749
+ declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHandler<TDatabase>): SeederHandler<TDatabase>;
1642
1750
 
1643
1751
  /**
1644
1752
  * Serialize a model record for API/JSON output.
@@ -1654,4 +1762,4 @@ declare function serializeRecord(record: PlainObject, options: {
1654
1762
  /** Serialize an array of records. */
1655
1763
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1656
1764
 
1657
- export { type AccessorDefinitions, type AccessorFn, 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 ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, 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, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1765
+ 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 WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
package/dist/index.js CHANGED
@@ -766,8 +766,11 @@ var QueryBuilder = class {
766
766
  *
767
767
  * Mass-assignment protection applies exactly as in `Model.update()`:
768
768
  * with a `fillable` allowlist, out-of-allowlist keys throw a
769
- * MassAssignmentException. Note that bulk updates skip model hooks,
770
- * observers, mutators, and casts by design.
769
+ * MassAssignmentException. The payload also runs through the same
770
+ * persistence preparation as `Model.update()` — mutators, casts, and
771
+ * `preparePersistencePayload` overrides (e.g. password hashing on
772
+ * authenticatable models). Per-record hooks and observers are still
773
+ * skipped by design.
771
774
  *
772
775
  * @param data - Data to set on matching records
773
776
  * @returns The updated record (adapter-dependent)
@@ -787,7 +790,8 @@ var QueryBuilder = class {
787
790
  throw new Error("Configured adapter does not support update operations.");
788
791
  }
789
792
  const model = this.modelClass;
790
- const payload = applyFillable ? model.filterFillable(data) : { ...data };
793
+ const filtered = applyFillable ? model.filterFillable(data) : { ...data };
794
+ const payload = await model.prepareBulkPersistencePayload(filtered);
791
795
  const advancedAdapter = this.adapter;
792
796
  if (typeof advancedAdapter.updateAdvanced === "function") {
793
797
  return advancedAdapter.updateAdvanced(this.table, this.conditions, payload, { trx: this.options.trx });
@@ -943,14 +947,18 @@ function serializeRecords(records, options) {
943
947
  var MassAssignmentException = class extends Error {
944
948
  model;
945
949
  fields;
946
- constructor(model, fields) {
950
+ reason;
951
+ constructor(model, fields, options) {
952
+ const reason = options?.reason ?? "not-fillable";
947
953
  const list = fields.map((field) => `"${field}"`).join(", ");
954
+ const remediation = reason === "denied" ? `These are protected columns (e.g. credential fields) and can never be mass-assigned \u2014 not even via ${model}.fillable. Pass the plain input field (e.g. \`password\`) and let the model derive them, or use ${model}.forceCreate()/forceUpdate() for trusted server-side values such as \`passwordHash: 'oauth:...'\`.` : `Add them to fillable, or use ${model}.forceCreate()/forceUpdate() for trusted server-side data.`;
948
955
  super(
949
- `${model}: mass assignment blocked for field(s) ${list} \u2014 not listed in ${model}.fillable. Add them to fillable, use ${model}.forceCreate()/forceUpdate() for trusted server-side data, or set \`static strictFillable = false\` to restore silent discarding.`
956
+ `${model}: mass assignment blocked for field(s) ${list}. ${remediation} Never call forceCreate/forceUpdate with request input.`
950
957
  );
951
958
  this.name = "MassAssignmentException";
952
959
  this.model = model;
953
960
  this.fields = fields;
961
+ this.reason = reason;
954
962
  }
955
963
  };
956
964
 
@@ -961,9 +969,9 @@ var Model = class _Model {
961
969
  static ormAdapter = DrizzleAdapter;
962
970
  /** The database table (e.g., Drizzle table schema). */
963
971
  static table;
964
- /** Type marker for TypeScript inference. Define as `{} as YourRecordType`. */
972
+ /** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
965
973
  static recordType = void 0;
966
- /** Type marker for insert/update payload inference. Define as `{} as typeof table.$inferInsert`. */
974
+ /** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
967
975
  static createType = void 0;
968
976
  static relationDefinitions;
969
977
  /** Type marker for relation types. Define relation types here for type inference. */
@@ -1026,8 +1034,11 @@ var Model = class _Model {
1026
1034
  * containing any other key throws a MassAssignmentException so bugs
1027
1035
  * (and injection attempts) surface immediately instead of being
1028
1036
  * silently discarded. Use `forceCreate()` / `forceUpdate()` for
1029
- * trusted server-side data, or set `strictFillable = false` to
1030
- * restore silent discarding.
1037
+ * trusted server-side data.
1038
+ *
1039
+ * The primary key (`id`) is always silently stripped from mass-assignment
1040
+ * input, and fields returned by `deniedFields()` always throw — neither
1041
+ * depends on `fillable`.
1031
1042
  *
1032
1043
  * @example
1033
1044
  * class User extends Model<UserRecord> {
@@ -1036,21 +1047,16 @@ var Model = class _Model {
1036
1047
  */
1037
1048
  static fillable;
1038
1049
  /**
1039
- * When `fillable` is set, controls what happens to input fields outside
1040
- * the allowlist: `true` (default) throws a MassAssignmentException,
1041
- * `false` silently discards them (pre-1.0 behavior).
1042
- */
1043
- static strictFillable;
1044
- /**
1045
- * Blacklist of fields excluded from mass assignment.
1046
- * Defaults to `['id']`. Ignored if `fillable` is set.
1047
- *
1048
- * @example
1049
- * class Post extends Model<PostRecord> {
1050
- * static guarded = ['id', 'createdAt']
1051
- * }
1050
+ * Fields that can never be mass-assigned, resolved at call time so
1051
+ * subclasses can derive them from their own configuration (e.g.
1052
+ * `AuthenticatableModel` contributes its resolved password-hash and
1053
+ * remember-token columns). Input containing any of these throws a
1054
+ * MassAssignmentException regardless of `fillable` — use
1055
+ * `forceCreate()` / `forceUpdate()` for trusted server-side values.
1052
1056
  */
1053
- static guarded;
1057
+ static deniedFields() {
1058
+ return [];
1059
+ }
1054
1060
  /**
1055
1061
  * Accessor functions for computed/virtual attributes.
1056
1062
  * Applied after reading records from the database.
@@ -1334,37 +1340,38 @@ var Model = class _Model {
1334
1340
  /**
1335
1341
  * Filter input data based on mass assignment protection rules.
1336
1342
  *
1337
- * If `fillable` is defined, only fields listed in `fillable` are kept.
1338
- * Otherwise, fields listed in `guarded` (default: `['id']`) are removed.
1343
+ * Applied in order: fields returned by `deniedFields()` throw a
1344
+ * MassAssignmentException (checked on the raw input, so no other rule
1345
+ * can silently swallow them); the primary key (`id`) is silently
1346
+ * stripped; when `fillable` is defined, any remaining field outside it
1347
+ * throws and only listed fields are kept.
1339
1348
  *
1340
1349
  * @param data - The input data to filter
1341
1350
  * @returns Filtered data safe for mass assignment
1342
1351
  */
1343
1352
  static filterFillable(data) {
1353
+ const denied = this.deniedFields().filter((field) => field in data);
1354
+ if (denied.length > 0) {
1355
+ throw new MassAssignmentException(this.name, denied, { reason: "denied" });
1356
+ }
1357
+ let candidate = data;
1358
+ if ("id" in candidate) {
1359
+ const { id: _id, ...rest } = candidate;
1360
+ candidate = rest;
1361
+ }
1344
1362
  const fillableFields = this.fillable;
1345
- if (fillableFields) {
1346
- if (this.strictFillable !== false) {
1347
- const blocked = Object.keys(data).filter((key) => !fillableFields.includes(key));
1348
- if (blocked.length > 0) {
1349
- throw new MassAssignmentException(this.name, blocked);
1350
- }
1351
- }
1352
- const filtered2 = {};
1353
- for (const key of fillableFields) {
1354
- if (key in data) {
1355
- filtered2[key] = data[key];
1356
- }
1357
- }
1358
- return filtered2;
1363
+ if (!fillableFields) {
1364
+ return candidate;
1359
1365
  }
1360
- const guardedFields = this.guarded ?? ["id"];
1361
- const hasGuardedKey = guardedFields.some((key) => key in data);
1362
- if (!hasGuardedKey) {
1363
- return data;
1366
+ const blocked = Object.keys(candidate).filter((key) => !fillableFields.includes(key));
1367
+ if (blocked.length > 0) {
1368
+ throw new MassAssignmentException(this.name, blocked);
1364
1369
  }
1365
- const filtered = { ...data };
1366
- for (const key of guardedFields) {
1367
- delete filtered[key];
1370
+ const filtered = {};
1371
+ for (const key of fillableFields) {
1372
+ if (key in candidate) {
1373
+ filtered[key] = candidate[key];
1374
+ }
1368
1375
  }
1369
1376
  return filtered;
1370
1377
  }
@@ -1409,6 +1416,10 @@ var Model = class _Model {
1409
1416
  }
1410
1417
  return result;
1411
1418
  }
1419
+ /** @internal Lets QueryBuilder bulk updates run the same payload preparation as `Model.update()`. */
1420
+ static async prepareBulkPersistencePayload(data) {
1421
+ return this.preparePersistencePayload(data);
1422
+ }
1412
1423
  static getRelationDefinitions() {
1413
1424
  if (!Object.prototype.hasOwnProperty.call(this, "relationDefinitions") || !this.relationDefinitions) {
1414
1425
  this.relationDefinitions = /* @__PURE__ */ new Map();
@@ -2502,7 +2513,7 @@ function defineModel(table, options = {}) {
2502
2513
  ;
2503
2514
  DefinedModel.table = table;
2504
2515
  DefinedModel.recordType = {};
2505
- DefinedModel.createType = options.createType ?? {};
2516
+ DefinedModel.createType = {};
2506
2517
  return DefinedModel;
2507
2518
  }
2508
2519
  function normalizeOrderBy(order) {
@@ -2610,11 +2621,85 @@ function getRegistry() {
2610
2621
  function isHotReloadRuntime() {
2611
2622
  return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
2612
2623
  }
2624
+ var WHITESPACE = /\s/;
2625
+ var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
2626
+ var OPEN_PAREN = 40;
2627
+ var CLOSE_PAREN = 41;
2628
+ function isLineTerminator(code) {
2629
+ return code === 10 || code === 13 || code === 8232 || code === 8233;
2630
+ }
2631
+ function isDigitAt(text, index) {
2632
+ const code = text.charCodeAt(index);
2633
+ return code >= 48 && code <= 57;
2634
+ }
2635
+ function locationSplits(frame, end) {
2636
+ let cursor = end;
2637
+ while (cursor > 0 && isDigitAt(frame, cursor - 1)) cursor -= 1;
2638
+ if (cursor === end || cursor === 0 || frame[cursor - 1] !== ":") return [];
2639
+ const lastColon = cursor - 1;
2640
+ cursor = lastColon;
2641
+ while (cursor > 0 && isDigitAt(frame, cursor - 1)) cursor -= 1;
2642
+ return cursor < lastColon && cursor > 0 && frame[cursor - 1] === ":" ? [cursor - 1, lastColon] : [lastColon];
2643
+ }
2644
+ function pathBefore(frame, from, splits) {
2645
+ for (const split of splits) {
2646
+ if (split > from) return frame.slice(from, split);
2647
+ }
2648
+ return void 0;
2649
+ }
2650
+ function matchingOpenParen(frame, closeIndex) {
2651
+ if (frame.charCodeAt(closeIndex) !== CLOSE_PAREN) {
2652
+ return void 0;
2653
+ }
2654
+ let depth = 0;
2655
+ let leftmostOpen;
2656
+ for (let index = closeIndex; index >= 0; index--) {
2657
+ const code = frame.charCodeAt(index);
2658
+ if (isLineTerminator(code)) {
2659
+ break;
2660
+ }
2661
+ if (code === CLOSE_PAREN) {
2662
+ depth++;
2663
+ } else if (code === OPEN_PAREN) {
2664
+ if (--depth === 0) {
2665
+ return index;
2666
+ }
2667
+ leftmostOpen = index;
2668
+ }
2669
+ }
2670
+ return leftmostOpen;
2671
+ }
2613
2672
  function parseFrameLocation(frame) {
2614
- return frame?.match(/\((.+?):\d+(?::\d+)?\)\s*$/)?.[1] ?? frame?.match(/^\s*at\s+(.+?):\d+(?::\d+)?\s*$/)?.[1];
2673
+ const end = frame.trimEnd().length;
2674
+ if (end > 0 && frame[end - 1] === ")") {
2675
+ const splits2 = locationSplits(frame, end - 1);
2676
+ const open = splits2.length === 0 ? void 0 : matchingOpenParen(frame, end - 1);
2677
+ const path2 = open === void 0 ? void 0 : pathBefore(frame, open + 1, splits2);
2678
+ if (path2 !== void 0 && !path2.startsWith("eval at ")) return path2;
2679
+ }
2680
+ let cursor = 0;
2681
+ while (cursor < end && WHITESPACE.test(frame[cursor])) cursor += 1;
2682
+ if (!frame.startsWith("at", cursor)) return void 0;
2683
+ const afterAt = cursor + 2;
2684
+ let pathStart = afterAt;
2685
+ while (pathStart < end && WHITESPACE.test(frame[pathStart])) pathStart += 1;
2686
+ if (pathStart === afterAt) return void 0;
2687
+ const splits = locationSplits(frame, end);
2688
+ if (splits.length === 0) return void 0;
2689
+ pathStart = Math.min(pathStart, splits[splits.length - 1] - 1);
2690
+ if (pathStart <= afterAt) return void 0;
2691
+ const path = pathBefore(frame, pathStart, splits);
2692
+ return path !== void 0 && !LINE_TERMINATOR.test(path) ? path : void 0;
2615
2693
  }
2694
+ var SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set(["unknown", "native", "<anonymous>"]);
2616
2695
  function describeCallerFile(stack) {
2617
- return parseFrameLocation(stack?.split("\n")[2]);
2696
+ for (const frame of stack?.split("\n").slice(2) ?? []) {
2697
+ const path = parseFrameLocation(frame);
2698
+ if (path && !SYNTHETIC_FRAME_PATHS.has(path)) {
2699
+ return path;
2700
+ }
2701
+ }
2702
+ return void 0;
2618
2703
  }
2619
2704
  function hotReloadKey(driver, stack, target) {
2620
2705
  if (!isHotReloadRuntime()) {
@@ -2696,6 +2781,76 @@ function warnIgnoredFlatSqlMigrations(migrationsFolder) {
2696
2781
  );
2697
2782
  }
2698
2783
  }
2784
+ var PRE_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
2785
+ "CONNECT_TIMEOUT",
2786
+ "EAI_AGAIN",
2787
+ "ECONNREFUSED",
2788
+ "EHOSTUNREACH",
2789
+ "ENETUNREACH",
2790
+ "ENOTFOUND"
2791
+ ]);
2792
+ function failedWhileConnecting(error) {
2793
+ const { code, syscall } = error;
2794
+ if (typeof code !== "string" || code === "") {
2795
+ return false;
2796
+ }
2797
+ return PRE_CONNECTION_ERROR_CODES.has(code) || syscall === "connect";
2798
+ }
2799
+ function collectCauses(error, seen = /* @__PURE__ */ new Set()) {
2800
+ if (error == null || typeof error !== "object" || seen.has(error)) {
2801
+ return [];
2802
+ }
2803
+ seen.add(error);
2804
+ const nested = [
2805
+ ...Array.isArray(error.errors) ? error.errors : [],
2806
+ ..."cause" in error ? [error.cause] : []
2807
+ ];
2808
+ return [error, ...nested.flatMap((child) => collectCauses(child, seen))];
2809
+ }
2810
+ function isConnectionFailure(error) {
2811
+ return collectCauses(error).some(failedWhileConnecting);
2812
+ }
2813
+ function describeDatabaseFailure(error, endpoint) {
2814
+ const causes = collectCauses(error);
2815
+ const connectFailure = causes.find(failedWhileConnecting);
2816
+ if (connectFailure) {
2817
+ const target = endpoint ? `the database at ${endpoint}` : "the database";
2818
+ return `cannot connect to ${target} (${connectFailure.code}). Is it running and accepting connections?`;
2819
+ }
2820
+ const messages = [
2821
+ ...new Set(
2822
+ causes.map((cause) => cause.message).filter((message) => typeof message === "string" && message.trim() !== "")
2823
+ )
2824
+ ];
2825
+ if (messages.length === 0) {
2826
+ return error instanceof Error ? error.message : String(error);
2827
+ }
2828
+ if (messages.length === 1) {
2829
+ const deepestCode = causes.reduce(
2830
+ (found, cause) => typeof cause.code === "string" && cause.code !== "" ? cause.code : found,
2831
+ void 0
2832
+ );
2833
+ if (deepestCode) {
2834
+ return `${messages[0]} (${deepestCode})`;
2835
+ }
2836
+ }
2837
+ return messages.join(" \u2014 ");
2838
+ }
2839
+ function migrationFailure(error, endpoint) {
2840
+ return new Error(`Failed to run database migrations: ${describeDatabaseFailure(error, endpoint)}`);
2841
+ }
2842
+ function seedFailure(error, endpoint) {
2843
+ return new Error(`Failed to seed the database: ${describeDatabaseFailure(error, endpoint)}`);
2844
+ }
2845
+ function describeConnectionEndpoint(connectionString) {
2846
+ try {
2847
+ const { hostname, port } = new URL(connectionString);
2848
+ if (!hostname) return void 0;
2849
+ return port ? `${hostname}:${port}` : hostname;
2850
+ } catch {
2851
+ return void 0;
2852
+ }
2853
+ }
2699
2854
  function listLocalMigrations(migrationsFolder) {
2700
2855
  if (!existsSync(migrationsFolder)) {
2701
2856
  return [];
@@ -2830,6 +2985,7 @@ function createPostgresDatabase(options) {
2830
2985
  if (migrationsPromise) {
2831
2986
  return migrationsPromise;
2832
2987
  }
2988
+ let endpoint;
2833
2989
  const promise = (async () => {
2834
2990
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
2835
2991
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
@@ -2837,6 +2993,7 @@ function createPostgresDatabase(options) {
2837
2993
  }
2838
2994
  const { drizzle, migrate, postgres: postgresFactory } = await loadPostgresModules();
2839
2995
  const url = resolveConnectionString();
2996
+ endpoint = describeConnectionEndpoint(url);
2840
2997
  const migrationClient = postgresFactory(url, {
2841
2998
  max: 1,
2842
2999
  ...clientOptions
@@ -2850,8 +3007,7 @@ function createPostgresDatabase(options) {
2850
3007
  })();
2851
3008
  migrationsPromise = promise.catch((error) => {
2852
3009
  migrationsPromise = void 0;
2853
- const reason = error instanceof Error ? error.message : String(error);
2854
- throw new Error(`Failed to run database migrations: ${reason}`);
3010
+ throw migrationFailure(error, endpoint);
2855
3011
  });
2856
3012
  await migrationsPromise;
2857
3013
  }
@@ -2908,16 +3064,23 @@ function createPostgresDatabase(options) {
2908
3064
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createPostgresDatabase().');
2909
3065
  }
2910
3066
  const db = await getDatabase();
2911
- await runSeeders(db, resolvedSeedersFolder);
3067
+ try {
3068
+ await runSeeders(db, resolvedSeedersFolder);
3069
+ } catch (error) {
3070
+ throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
3071
+ }
2912
3072
  }
2913
3073
  async function withAdminClient(callback) {
2914
3074
  const { postgres: postgresFactory } = await loadPostgresModules();
2915
- const adminClient = postgresFactory(resolveConnectionString(), {
3075
+ const url = resolveConnectionString();
3076
+ const adminClient = postgresFactory(url, {
2916
3077
  max: 1,
2917
3078
  ...clientOptions
2918
3079
  });
2919
3080
  try {
2920
3081
  return await callback(adminClient);
3082
+ } catch (error) {
3083
+ throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
2921
3084
  } finally {
2922
3085
  await adminClient.end({ timeout: 0 });
2923
3086
  }
@@ -2940,7 +3103,8 @@ function createPostgresDatabase(options) {
2940
3103
  const record = row;
2941
3104
  return { name: record.name, appliedAt: null };
2942
3105
  });
2943
- } catch {
3106
+ } catch (error) {
3107
+ if (isConnectionFailure(error)) throw error;
2944
3108
  return [];
2945
3109
  }
2946
3110
  });
@@ -2962,11 +3126,12 @@ import { resolve as resolve4 } from "path";
2962
3126
  import { fileURLToPath as fileURLToPath3 } from "url";
2963
3127
  async function loadMySqlModules() {
2964
3128
  try {
2965
- const [{ drizzle }, { migrate }] = await Promise.all([
3129
+ const [{ drizzle }, { migrate }, { createPool }] = await Promise.all([
2966
3130
  import("drizzle-orm/mysql2"),
2967
- import("drizzle-orm/mysql2/migrator")
3131
+ import("drizzle-orm/mysql2/migrator"),
3132
+ import("mysql2")
2968
3133
  ]);
2969
- return { drizzle, migrate };
3134
+ return { drizzle, migrate, createPool };
2970
3135
  } catch (error) {
2971
3136
  const reason = error instanceof Error ? error.message : String(error);
2972
3137
  throw new Error(
@@ -2980,7 +3145,7 @@ function createMySqlDatabase(options) {
2980
3145
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
2981
3146
  let migrationsPromise;
2982
3147
  let databasePromise;
2983
- let database2;
3148
+ let client;
2984
3149
  let activeKey;
2985
3150
  const callSite = new Error().stack;
2986
3151
  function resolveConnectionString() {
@@ -2995,31 +3160,29 @@ function createMySqlDatabase(options) {
2995
3160
  if (migrationsPromise) {
2996
3161
  return migrationsPromise;
2997
3162
  }
3163
+ let endpoint;
2998
3164
  const promise = (async () => {
2999
3165
  if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3000
3166
  warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3001
3167
  return;
3002
3168
  }
3003
- const { drizzle, migrate } = await loadMySqlModules();
3169
+ const { drizzle, migrate, createPool } = await loadMySqlModules();
3004
3170
  const url = resolveConnectionString();
3005
- const migrationDb = drizzle({
3006
- connection: {
3007
- uri: url,
3008
- ...clientOptions
3009
- },
3010
- mode: "default",
3011
- ...relations ? { relations } : {}
3012
- });
3171
+ endpoint = describeConnectionEndpoint(url);
3172
+ const migrationClient = createPool({ uri: url, ...clientOptions });
3013
3173
  try {
3174
+ const migrationDb = drizzle({
3175
+ client: migrationClient,
3176
+ ...relations ? { relations } : {}
3177
+ });
3014
3178
  await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
3015
3179
  } finally {
3016
- await closeClient(migrationDb);
3180
+ await closePool(migrationClient);
3017
3181
  }
3018
3182
  })();
3019
3183
  migrationsPromise = promise.catch((error) => {
3020
3184
  migrationsPromise = void 0;
3021
- const reason = error instanceof Error ? error.message : String(error);
3022
- throw new Error(`Failed to run database migrations: ${reason}`);
3185
+ throw migrationFailure(error, endpoint);
3023
3186
  });
3024
3187
  await migrationsPromise;
3025
3188
  }
@@ -3029,22 +3192,18 @@ function createMySqlDatabase(options) {
3029
3192
  }
3030
3193
  const promise = (async () => {
3031
3194
  await migrateOnce();
3032
- const { drizzle } = await loadMySqlModules();
3195
+ const { drizzle, createPool } = await loadMySqlModules();
3033
3196
  const url = resolveConnectionString();
3034
- const db = drizzle({
3035
- connection: {
3036
- uri: url,
3037
- ...clientOptions
3038
- },
3039
- mode: "default",
3040
- ...relations ? { relations } : {}
3041
- });
3042
- database2 = db;
3197
+ const activeClient = createPool({ uri: url, ...clientOptions });
3198
+ client = activeClient;
3043
3199
  activeKey = hotReloadKey("mysql", callSite, url);
3044
3200
  if (activeKey) {
3045
3201
  await replaceActiveConnection(activeKey, closeDatabase);
3046
3202
  }
3047
- return db;
3203
+ return drizzle({
3204
+ client: activeClient,
3205
+ ...relations ? { relations } : {}
3206
+ });
3048
3207
  })();
3049
3208
  databasePromise = promise.catch((error) => {
3050
3209
  databasePromise = void 0;
@@ -3053,15 +3212,15 @@ function createMySqlDatabase(options) {
3053
3212
  return databasePromise;
3054
3213
  }
3055
3214
  async function closeDatabase() {
3056
- if (!database2) {
3215
+ if (!client) {
3057
3216
  return;
3058
3217
  }
3059
3218
  const key = activeKey;
3060
3219
  activeKey = void 0;
3061
3220
  try {
3062
- await closeClient(database2);
3221
+ await closePool(client);
3063
3222
  } finally {
3064
- database2 = void 0;
3223
+ client = void 0;
3065
3224
  databasePromise = void 0;
3066
3225
  if (key) {
3067
3226
  releaseActiveConnection(key, closeDatabase);
@@ -3077,33 +3236,40 @@ function createMySqlDatabase(options) {
3077
3236
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createMySqlDatabase().');
3078
3237
  }
3079
3238
  const db = await getDatabase();
3080
- await runSeeders(db, resolvedSeedersFolder);
3239
+ try {
3240
+ await runSeeders(db, resolvedSeedersFolder);
3241
+ } catch (error) {
3242
+ throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
3243
+ }
3081
3244
  }
3082
3245
  async function withAdminDb(callback) {
3083
- const { drizzle } = await loadMySqlModules();
3084
- const adminDb = drizzle({
3085
- connection: {
3086
- uri: resolveConnectionString(),
3087
- ...clientOptions
3088
- },
3089
- mode: "default"
3090
- });
3246
+ const { drizzle, createPool } = await loadMySqlModules();
3247
+ const url = resolveConnectionString();
3248
+ const adminClient = createPool({ uri: url, ...clientOptions });
3249
+ const adminDb = drizzle({ client: adminClient });
3091
3250
  try {
3092
3251
  return await callback(adminDb);
3252
+ } catch (error) {
3253
+ throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
3093
3254
  } finally {
3094
- await closeClient(adminDb);
3255
+ await closePool(adminClient);
3095
3256
  }
3096
3257
  }
3097
3258
  async function resetDatabase() {
3098
3259
  const { sql } = await import("drizzle-orm");
3099
3260
  await withAdminDb(async (adminDb) => {
3100
3261
  const [rows] = await adminDb.execute(
3101
- sql.raw("SELECT table_name AS name FROM information_schema.tables WHERE table_schema = DATABASE()")
3262
+ sql.raw(
3263
+ "SELECT table_name AS name, table_type AS type FROM information_schema.tables WHERE table_schema = DATABASE()"
3264
+ )
3102
3265
  );
3103
3266
  await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 0"));
3104
3267
  try {
3105
- for (const { name } of rows) {
3106
- await adminDb.execute(sql.raw(`DROP TABLE IF EXISTS \`${name.replaceAll("`", "``")}\``));
3268
+ for (const { name, type } of rows) {
3269
+ const identifier = sql.identifier(name);
3270
+ await adminDb.execute(
3271
+ type === "VIEW" ? sql`DROP VIEW IF EXISTS ${identifier}` : sql`DROP TABLE IF EXISTS ${identifier}`
3272
+ );
3107
3273
  }
3108
3274
  } finally {
3109
3275
  await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 1"));
@@ -3121,7 +3287,8 @@ function createMySqlDatabase(options) {
3121
3287
  sql.raw("SELECT name, applied_at FROM __drizzle_migrations")
3122
3288
  );
3123
3289
  return rows.map((row) => ({ name: row.name, appliedAt: row.applied_at }));
3124
- } catch {
3290
+ } catch (error) {
3291
+ if (isConnectionFailure(error)) throw error;
3125
3292
  return [];
3126
3293
  }
3127
3294
  });
@@ -3137,34 +3304,11 @@ function createMySqlDatabase(options) {
3137
3304
  migrationStatus
3138
3305
  };
3139
3306
  }
3140
- async function closeClient(db) {
3141
- if (typeof db !== "object" || db === null) {
3142
- return;
3143
- }
3144
- const maybeClient = db.$client;
3145
- if (!maybeClient || typeof maybeClient.end !== "function") {
3146
- return;
3147
- }
3148
- if (maybeClient.end.length === 0) {
3149
- const maybePromise = maybeClient.end();
3150
- if (isPromiseLike2(maybePromise)) {
3151
- await maybePromise;
3152
- }
3153
- return;
3154
- }
3307
+ async function closePool(pool) {
3155
3308
  await new Promise((resolveClose, rejectClose) => {
3156
- maybeClient.end?.((error) => {
3157
- if (error) {
3158
- rejectClose(error);
3159
- return;
3160
- }
3161
- resolveClose();
3162
- });
3309
+ pool.end((error) => error ? rejectClose(error) : resolveClose());
3163
3310
  });
3164
3311
  }
3165
- function isPromiseLike2(value) {
3166
- return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3167
- }
3168
3312
 
3169
3313
  // src/sqlite.ts
3170
3314
  import { resolve as resolve5 } from "path";
@@ -3234,8 +3378,7 @@ function createSqliteDatabase(options) {
3234
3378
  })();
3235
3379
  migrationsPromise = migrationsPromise.catch((error) => {
3236
3380
  migrationsPromise = void 0;
3237
- const reason = error instanceof Error ? error.message : String(error);
3238
- throw new Error(`Failed to run database migrations: ${reason}`);
3381
+ throw migrationFailure(error);
3239
3382
  });
3240
3383
  await migrationsPromise;
3241
3384
  }
@@ -3249,11 +3392,14 @@ function createSqliteDatabase(options) {
3249
3392
  async resetDatabase() {
3250
3393
  await ensureDatabase2();
3251
3394
  if (!sqliteClient) return;
3252
- const tables = sqliteClient.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
3395
+ const objects = sqliteClient.query(
3396
+ "SELECT name, type FROM main.sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'"
3397
+ ).all();
3253
3398
  sqliteClient.exec("PRAGMA foreign_keys = OFF;");
3254
3399
  try {
3255
- for (const { name } of tables) {
3256
- sqliteClient.exec(`DROP TABLE IF EXISTS "${name.replaceAll('"', '""')}"`);
3400
+ for (const { name, type } of objects) {
3401
+ const quoted = `main."${name.replaceAll('"', '""')}"`;
3402
+ sqliteClient.exec(type === "view" ? `DROP VIEW IF EXISTS ${quoted}` : `DROP TABLE IF EXISTS ${quoted}`);
3257
3403
  }
3258
3404
  } finally {
3259
3405
  sqliteClient.exec("PRAGMA foreign_keys = ON;");
@@ -3282,10 +3428,11 @@ function createSqliteDatabase(options) {
3282
3428
  throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createSqliteDatabase().');
3283
3429
  }
3284
3430
  const database2 = await ensureDatabase2();
3285
- await runSeeders(
3286
- database2,
3287
- resolvedSeedersFolder
3288
- );
3431
+ try {
3432
+ await runSeeders(database2, resolvedSeedersFolder);
3433
+ } catch (error) {
3434
+ throw seedFailure(error);
3435
+ }
3289
3436
  }
3290
3437
  };
3291
3438
  }
@@ -3346,6 +3493,182 @@ function createD1Database(options) {
3346
3493
  }
3347
3494
  };
3348
3495
  }
3496
+
3497
+ // src/aws-data-api.ts
3498
+ import { resolve as resolve6 } from "path";
3499
+ import { fileURLToPath as fileURLToPath6 } from "url";
3500
+ async function loadAwsDataApiModules() {
3501
+ try {
3502
+ const [{ drizzle }, { migrate }] = await Promise.all([
3503
+ import("drizzle-orm/aws-data-api/pg"),
3504
+ import("drizzle-orm/aws-data-api/pg/migrator")
3505
+ ]);
3506
+ return { drizzle, migrate };
3507
+ } catch (error) {
3508
+ const reason = error instanceof Error ? error.message : String(error);
3509
+ throw new Error(
3510
+ `createAwsDataApiDatabase() requires the "@aws-sdk/client-rds-data" package. Install it with \`bun add @aws-sdk/client-rds-data\`. (${reason})`
3511
+ );
3512
+ }
3513
+ }
3514
+ function createAwsDataApiDatabase(options) {
3515
+ const { migrationsFolder, database: database2, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
3516
+ const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath6(migrationsFolder) : resolve6(String(migrationsFolder));
3517
+ const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath6(seedersFolder) : resolve6(String(seedersFolder));
3518
+ let migrationsPromise;
3519
+ let databasePromise;
3520
+ let client;
3521
+ let activeKey;
3522
+ const callSite = new Error().stack;
3523
+ function resolveConnection() {
3524
+ const resolveValue = (value, envKey) => {
3525
+ const resolved = typeof value === "function" ? value() : value;
3526
+ return resolved ?? process.env[envKey];
3527
+ };
3528
+ const resolvedDatabase = resolveValue(database2, "DATABASE_NAME");
3529
+ const resolvedResourceArn = resolveValue(resourceArn, "DATABASE_RESOURCE_ARN");
3530
+ const resolvedSecretArn = resolveValue(secretArn, "DATABASE_SECRET_ARN");
3531
+ const missing = [
3532
+ resolvedDatabase ? null : "database (DATABASE_NAME)",
3533
+ resolvedResourceArn ? null : "resourceArn (DATABASE_RESOURCE_ARN)",
3534
+ resolvedSecretArn ? null : "secretArn (DATABASE_SECRET_ARN)"
3535
+ ].filter((entry) => entry !== null);
3536
+ if (missing.length > 0) {
3537
+ throw new Error(`Missing AWS Data API connection settings: ${missing.join(", ")}.`);
3538
+ }
3539
+ return { database: resolvedDatabase, resourceArn: resolvedResourceArn, secretArn: resolvedSecretArn };
3540
+ }
3541
+ function buildDrizzleConfig(connection) {
3542
+ return {
3543
+ connection: {
3544
+ ...clientOptions,
3545
+ ...connection
3546
+ },
3547
+ ...relations ? { relations } : {}
3548
+ };
3549
+ }
3550
+ async function migrateOnce() {
3551
+ if (migrationsPromise) {
3552
+ return migrationsPromise;
3553
+ }
3554
+ const promise = (async () => {
3555
+ if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
3556
+ warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
3557
+ return;
3558
+ }
3559
+ const { migrate } = await loadAwsDataApiModules();
3560
+ await withAdminDb((db) => migrate(db, { migrationsFolder: resolvedMigrationsFolder }));
3561
+ })();
3562
+ migrationsPromise = promise.catch((error) => {
3563
+ migrationsPromise = void 0;
3564
+ const reason = error instanceof Error ? error.message : String(error);
3565
+ throw new Error(`Failed to run database migrations: ${reason}`);
3566
+ });
3567
+ await migrationsPromise;
3568
+ }
3569
+ async function getDatabase() {
3570
+ if (databasePromise) {
3571
+ return databasePromise;
3572
+ }
3573
+ const promise = (async () => {
3574
+ if (migrateOnStart) {
3575
+ await migrateOnce();
3576
+ }
3577
+ const { drizzle } = await loadAwsDataApiModules();
3578
+ const connection = resolveConnection();
3579
+ const db = drizzle(buildDrizzleConfig(connection));
3580
+ client = db.$client;
3581
+ activeKey = hotReloadKey("aws-data-api", callSite, `${connection.resourceArn}/${connection.database}`);
3582
+ if (activeKey) {
3583
+ await replaceActiveConnection(activeKey, closeDatabase);
3584
+ }
3585
+ return db;
3586
+ })();
3587
+ databasePromise = promise.catch((error) => {
3588
+ databasePromise = void 0;
3589
+ throw error;
3590
+ });
3591
+ return databasePromise;
3592
+ }
3593
+ async function closeDatabase() {
3594
+ if (!client) {
3595
+ return;
3596
+ }
3597
+ const key = activeKey;
3598
+ activeKey = void 0;
3599
+ try {
3600
+ client.destroy?.();
3601
+ } finally {
3602
+ client = void 0;
3603
+ databasePromise = void 0;
3604
+ if (key) {
3605
+ releaseActiveConnection(key, closeDatabase);
3606
+ }
3607
+ }
3608
+ }
3609
+ async function configureOrm() {
3610
+ const db = await getDatabase();
3611
+ DrizzleAdapter.configure(db);
3612
+ }
3613
+ async function seedDatabase() {
3614
+ if (!resolvedSeedersFolder) {
3615
+ throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createAwsDataApiDatabase().');
3616
+ }
3617
+ const db = await getDatabase();
3618
+ await runSeeders(db, resolvedSeedersFolder);
3619
+ }
3620
+ async function withAdminDb(callback) {
3621
+ const { drizzle } = await loadAwsDataApiModules();
3622
+ const adminDb = drizzle(buildDrizzleConfig(resolveConnection()));
3623
+ try {
3624
+ return await callback(adminDb);
3625
+ } finally {
3626
+ adminDb.$client?.destroy?.();
3627
+ }
3628
+ }
3629
+ async function resetDatabase() {
3630
+ const { sql } = await import("drizzle-orm");
3631
+ await withAdminDb(async (adminDb) => {
3632
+ await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS public CASCADE"));
3633
+ await adminDb.execute(sql.raw("CREATE SCHEMA public"));
3634
+ await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
3635
+ });
3636
+ migrationsPromise = void 0;
3637
+ }
3638
+ async function migrationStatus() {
3639
+ const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
3640
+ if (localMigrations.length === 0) return [];
3641
+ const { sql } = await import("drizzle-orm");
3642
+ const appliedRows = await withAdminDb(async (adminDb) => {
3643
+ try {
3644
+ const result = await adminDb.execute(
3645
+ sql.raw("SELECT name FROM drizzle.__drizzle_migrations")
3646
+ );
3647
+ const rows = Array.isArray(result) ? result : result.rows ?? [];
3648
+ return rows.map((row) => ({ name: row.name, appliedAt: null }));
3649
+ } catch (error) {
3650
+ if (isMissingTrackerTableError(error)) {
3651
+ return [];
3652
+ }
3653
+ throw error;
3654
+ }
3655
+ });
3656
+ return buildMigrationStatus(localMigrations, appliedRows);
3657
+ }
3658
+ return {
3659
+ getDatabase,
3660
+ migrateDatabase: migrateOnce,
3661
+ closeDatabase,
3662
+ configureOrm,
3663
+ seedDatabase,
3664
+ resetDatabase,
3665
+ migrationStatus
3666
+ };
3667
+ }
3668
+ function isMissingTrackerTableError(error) {
3669
+ const message = error instanceof Error ? error.message : String(error);
3670
+ return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
3671
+ }
3349
3672
  export {
3350
3673
  DrizzleAdapter,
3351
3674
  GlobalScopeRegistry,
@@ -3357,6 +3680,7 @@ export {
3357
3680
  applyAccessors,
3358
3681
  applyMutators,
3359
3682
  buildDrizzleConditions,
3683
+ createAwsDataApiDatabase,
3360
3684
  createD1Database,
3361
3685
  createMySqlDatabase,
3362
3686
  createPostgresDatabase,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -40,10 +40,14 @@
40
40
  "drizzle-orm": "1.0.0-rc.4"
41
41
  },
42
42
  "peerDependencies": {
43
+ "@aws-sdk/client-rds-data": "^3.0.0",
43
44
  "mysql2": "^3.11.3",
44
45
  "postgres": "^3.4.3"
45
46
  },
46
47
  "peerDependenciesMeta": {
48
+ "@aws-sdk/client-rds-data": {
49
+ "optional": true
50
+ },
47
51
  "mysql2": {
48
52
  "optional": true
49
53
  },
@@ -52,6 +56,7 @@
52
56
  }
53
57
  },
54
58
  "devDependencies": {
59
+ "@aws-sdk/client-rds-data": "^3.0.0",
55
60
  "@types/node": "^20.14.10",
56
61
  "mysql2": "^3.11.3",
57
62
  "postgres": "^3.4.3",