@guren/orm 1.3.0 → 2.1.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 +172 -48
- package/dist/index.js +155 -60
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
|
3
3
|
import postgres from 'postgres';
|
|
4
4
|
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
5
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';
|
|
6
7
|
import { RDSDataClientConfig } from '@aws-sdk/client-rds-data';
|
|
8
|
+
import { SQLiteBunDatabase } from 'drizzle-orm/bun-sqlite';
|
|
7
9
|
|
|
8
10
|
/** Accessor function: transforms a record field value after reading from DB. */
|
|
9
11
|
type AccessorFn<T = unknown> = (record: PlainObject) => T;
|
|
@@ -215,8 +217,11 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
215
217
|
*
|
|
216
218
|
* Mass-assignment protection applies exactly as in `Model.update()`:
|
|
217
219
|
* with a `fillable` allowlist, out-of-allowlist keys throw a
|
|
218
|
-
* MassAssignmentException.
|
|
219
|
-
*
|
|
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.
|
|
220
225
|
*
|
|
221
226
|
* @param data - Data to set on matching records
|
|
222
227
|
* @returns The updated record (adapter-dependent)
|
|
@@ -508,10 +513,14 @@ type SelectFrom<TDatabase> = TDatabase extends {
|
|
|
508
513
|
* CRUD, querying, pagination, and eager-loading of relationships.
|
|
509
514
|
*
|
|
510
515
|
* @example
|
|
511
|
-
* // Define a model
|
|
512
|
-
* class User extends
|
|
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> {
|
|
513
521
|
* static override table = users // Drizzle table
|
|
514
|
-
* static
|
|
522
|
+
* declare static readonly recordType: UserRecord
|
|
523
|
+
* declare static readonly createType: NewUserRecord
|
|
515
524
|
* }
|
|
516
525
|
*
|
|
517
526
|
* // Query records
|
|
@@ -534,9 +543,9 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
534
543
|
protected static ormAdapter: ORMAdapter;
|
|
535
544
|
/** The database table (e.g., Drizzle table schema). */
|
|
536
545
|
protected static table: unknown;
|
|
537
|
-
/** Type marker for TypeScript inference.
|
|
546
|
+
/** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
|
|
538
547
|
static readonly recordType: unknown;
|
|
539
|
-
/** Type marker for insert/update payload inference.
|
|
548
|
+
/** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
|
|
540
549
|
static readonly createType: unknown;
|
|
541
550
|
protected static relationDefinitions?: Map<string, RelationDefinition>;
|
|
542
551
|
/** Type marker for relation types. Define relation types here for type inference. */
|
|
@@ -597,8 +606,11 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
597
606
|
* containing any other key throws a MassAssignmentException so bugs
|
|
598
607
|
* (and injection attempts) surface immediately instead of being
|
|
599
608
|
* silently discarded. Use `forceCreate()` / `forceUpdate()` for
|
|
600
|
-
* trusted server-side data
|
|
601
|
-
*
|
|
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`.
|
|
602
614
|
*
|
|
603
615
|
* @example
|
|
604
616
|
* class User extends Model<UserRecord> {
|
|
@@ -607,21 +619,14 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
607
619
|
*/
|
|
608
620
|
static fillable?: string[];
|
|
609
621
|
/**
|
|
610
|
-
*
|
|
611
|
-
*
|
|
612
|
-
* `
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
* Blacklist of fields excluded from mass assignment.
|
|
617
|
-
* Defaults to `['id']`. Ignored if `fillable` is set.
|
|
618
|
-
*
|
|
619
|
-
* @example
|
|
620
|
-
* class Post extends Model<PostRecord> {
|
|
621
|
-
* static guarded = ['id', 'createdAt']
|
|
622
|
-
* }
|
|
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.
|
|
623
628
|
*/
|
|
624
|
-
static
|
|
629
|
+
protected static deniedFields(): string[];
|
|
625
630
|
/**
|
|
626
631
|
* Accessor functions for computed/virtual attributes.
|
|
627
632
|
* Applied after reading records from the database.
|
|
@@ -767,14 +772,19 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
767
772
|
/**
|
|
768
773
|
* Filter input data based on mass assignment protection rules.
|
|
769
774
|
*
|
|
770
|
-
*
|
|
771
|
-
*
|
|
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.
|
|
772
780
|
*
|
|
773
781
|
* @param data - The input data to filter
|
|
774
782
|
* @returns Filtered data safe for mass assignment
|
|
775
783
|
*/
|
|
776
784
|
static filterFillable(data: PlainObject): PlainObject;
|
|
777
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>;
|
|
778
788
|
protected static getRelationDefinitions(): Map<string, RelationDefinition>;
|
|
779
789
|
/** @internal */
|
|
780
790
|
static getRelationDefinition(name: string): RelationDefinition | undefined;
|
|
@@ -1358,22 +1368,107 @@ type MorphToRelationResult = PlainObject | null;
|
|
|
1358
1368
|
type MorphToRecord = PlainObject | null;
|
|
1359
1369
|
/** Utility type: model record with specified relations merged. */
|
|
1360
1370
|
type WithRelations<T extends typeof Model, K extends RelationPath<T> | readonly RelationPath<T>[]> = TRecordFor<T> & RelationTypePick<T, K>;
|
|
1361
|
-
type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model
|
|
1371
|
+
type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model, TCreate extends PlainObject> = TBase & {
|
|
1362
1372
|
readonly table: TTable;
|
|
1363
1373
|
readonly recordType: InferModelRecord<TTable>;
|
|
1364
1374
|
readonly createType: TCreate;
|
|
1365
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
|
+
/**
|
|
1379
|
+
* Named fields a base class contributes to the create payload, such as
|
|
1380
|
+
* `AuthenticatableModel`'s virtual `password`. A plain `Model` base has no
|
|
1381
|
+
* declared createType, so its keys collapse to `string` — guard against that
|
|
1382
|
+
* collapse, or every misspelling would pass the allowlist checks below.
|
|
1383
|
+
*/
|
|
1384
|
+
type BaseContributedKey<TBase extends typeof Model> = string extends keyof TCreateFor<TBase> & string ? never : keyof TCreateFor<TBase> & string;
|
|
1385
|
+
/** A key valid in a `fillable` allowlist: an insertable column, or a base-contributed field. */
|
|
1386
|
+
type FillableKey<TTable extends TableShape, TBase extends typeof Model> = (keyof InferModelInsert<TTable> & string) | BaseContributedKey<TBase>;
|
|
1387
|
+
/** A key of the record read back from the table. */
|
|
1388
|
+
type RecordKey<TTable extends TableShape> = keyof InferModelRecord<TTable> & string;
|
|
1389
|
+
/**
|
|
1390
|
+
* Accessor map keyed by TKey whose functions receive the table's inferred
|
|
1391
|
+
* record. A homomorphic mapped type so TypeScript infers the key union from
|
|
1392
|
+
* the object literal's keys — a plain `Record<string, fn>` constraint fails
|
|
1393
|
+
* here: the accessor functions are context-sensitive, which defers inference
|
|
1394
|
+
* past the point where the key type parameter falls back to its default.
|
|
1395
|
+
*/
|
|
1396
|
+
type AccessorsShape<TTable extends TableShape, TKey extends string> = {
|
|
1397
|
+
[K in TKey]: (record: InferModelRecord<TTable>) => unknown;
|
|
1398
|
+
};
|
|
1399
|
+
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>)>>;
|
|
1366
1400
|
/**
|
|
1367
1401
|
* Create a table-backed model base class from a Drizzle table.
|
|
1368
1402
|
*
|
|
1403
|
+
* `recordType` and `createType` are inferred from the table. The inferred
|
|
1404
|
+
* createType requires every non-defaulted column, which is not always the
|
|
1405
|
+
* payload a model accepts: `AuthenticatableModel` hashes a plain `password`
|
|
1406
|
+
* into `passwordHash`, so a user model wants the column optional and the
|
|
1407
|
+
* virtual field required. `optionalOnCreate` and `requireOnCreate` reshape the
|
|
1408
|
+
* inferred type without any cast.
|
|
1409
|
+
*
|
|
1410
|
+
* The allowlist statics (`fillable`, `hidden`, `visible`, `accessors`,
|
|
1411
|
+
* `appends`) can be passed here instead of declared on the subclass: the
|
|
1412
|
+
* option form checks every name against the table's columns (plus fields the
|
|
1413
|
+
* `base` contributes), so a typo is a compile error instead of a silently
|
|
1414
|
+
* ineffective entry. A `static` declaration on the subclass still works and
|
|
1415
|
+
* shadows the option, matching normal class semantics.
|
|
1416
|
+
*
|
|
1369
1417
|
* @example
|
|
1370
|
-
* export class Post extends defineModel(posts
|
|
1371
|
-
*
|
|
1418
|
+
* export class Post extends defineModel(posts, {
|
|
1419
|
+
* fillable: ['title', 'body'],
|
|
1420
|
+
* }) {}
|
|
1421
|
+
*
|
|
1422
|
+
* export class User extends defineModel(users, {
|
|
1423
|
+
* base: AuthenticatableModel,
|
|
1424
|
+
* optionalOnCreate: ['passwordHash'],
|
|
1425
|
+
* requireOnCreate: ['password'],
|
|
1426
|
+
* fillable: ['name', 'email', 'password'],
|
|
1427
|
+
* hidden: ['passwordHash', 'rememberToken'],
|
|
1428
|
+
* }) {}
|
|
1372
1429
|
*/
|
|
1373
|
-
declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model,
|
|
1430
|
+
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, TAccessorKey extends string = never>(table: TTable, options?: {
|
|
1374
1431
|
base?: TBase;
|
|
1375
|
-
|
|
1376
|
-
|
|
1432
|
+
/**
|
|
1433
|
+
* Columns the model fills in itself, so callers need not pass them.
|
|
1434
|
+
* Type-level only.
|
|
1435
|
+
*/
|
|
1436
|
+
optionalOnCreate?: readonly TOptional[];
|
|
1437
|
+
/**
|
|
1438
|
+
* Fields to make required on the create payload. Accepts table columns
|
|
1439
|
+
* (Drizzle marks defaulted ones optional) and named fields contributed by
|
|
1440
|
+
* `base`, such as `AuthenticatableModel`'s virtual `password`.
|
|
1441
|
+
* Type-level only.
|
|
1442
|
+
*/
|
|
1443
|
+
requireOnCreate?: readonly TRequire[];
|
|
1444
|
+
/**
|
|
1445
|
+
* Typed form of `static fillable`: mass-assignment allowlist checked
|
|
1446
|
+
* against insertable columns and base-contributed fields.
|
|
1447
|
+
*/
|
|
1448
|
+
fillable?: readonly FillableKey<TTable, TBase>[];
|
|
1449
|
+
/**
|
|
1450
|
+
* Typed form of `static hidden`: fields excluded from serialization,
|
|
1451
|
+
* checked against record columns and declared accessors.
|
|
1452
|
+
*/
|
|
1453
|
+
hidden?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1454
|
+
/**
|
|
1455
|
+
* Typed form of `static visible`: serialization allowlist, checked
|
|
1456
|
+
* against record columns and declared accessors.
|
|
1457
|
+
*/
|
|
1458
|
+
visible?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1459
|
+
/**
|
|
1460
|
+
* Typed form of `static accessors`: each function receives the table's
|
|
1461
|
+
* inferred record. Names declared here are what `appends` may reference.
|
|
1462
|
+
* The Record intersection rejects non-object values — with no keys to
|
|
1463
|
+
* infer, the mapped type alone collapses to `{}`, which admits anything.
|
|
1464
|
+
*/
|
|
1465
|
+
accessors?: AccessorsShape<TTable, TAccessorKey> & Record<string, (record: InferModelRecord<TTable>) => unknown>;
|
|
1466
|
+
/**
|
|
1467
|
+
* Typed form of `static appends`: virtual attributes to serialize,
|
|
1468
|
+
* checked against the names declared in `accessors`.
|
|
1469
|
+
*/
|
|
1470
|
+
appends?: readonly NoInfer<TAccessorKey>[];
|
|
1471
|
+
}): ModelClassWithTable<TTable, TBase, CreateShape<TTable, TBase, TOptional, TRequire>>;
|
|
1377
1472
|
|
|
1378
1473
|
/**
|
|
1379
1474
|
* Exception thrown when a model is not found via findOrFail or firstOrFail.
|
|
@@ -1389,15 +1484,24 @@ declare class ModelNotFoundException extends Error {
|
|
|
1389
1484
|
}
|
|
1390
1485
|
|
|
1391
1486
|
/**
|
|
1392
|
-
* Thrown when mass assignment receives fields
|
|
1393
|
-
*
|
|
1394
|
-
*
|
|
1395
|
-
*
|
|
1487
|
+
* Thrown when mass assignment receives fields it must not write. Silently
|
|
1488
|
+
* discarding them hides bugs (a typo'd fillable entry surfaces as a NOT NULL
|
|
1489
|
+
* violation much later) and can mask injection attempts, so models fail
|
|
1490
|
+
* loudly instead.
|
|
1491
|
+
*
|
|
1492
|
+
* `reason` distinguishes the two rules that throw:
|
|
1493
|
+
* - `'not-fillable'` — the field is outside the model's `fillable` allowlist.
|
|
1494
|
+
* - `'denied'` — the field is in the model's `deniedFields()` (e.g. a
|
|
1495
|
+
* credential column on an authenticatable model) and can never be
|
|
1496
|
+
* mass-assigned, `fillable` notwithstanding.
|
|
1396
1497
|
*/
|
|
1397
1498
|
declare class MassAssignmentException extends Error {
|
|
1398
1499
|
readonly model: string;
|
|
1399
1500
|
readonly fields: string[];
|
|
1400
|
-
|
|
1501
|
+
readonly reason: 'not-fillable' | 'denied';
|
|
1502
|
+
constructor(model: string, fields: string[], options?: {
|
|
1503
|
+
reason?: 'not-fillable' | 'denied';
|
|
1504
|
+
});
|
|
1401
1505
|
}
|
|
1402
1506
|
|
|
1403
1507
|
/**
|
|
@@ -1425,9 +1529,7 @@ interface SoftDeletesStatic {
|
|
|
1425
1529
|
* records via a global scope named 'softDelete'.
|
|
1426
1530
|
*
|
|
1427
1531
|
* @example
|
|
1428
|
-
* class Post extends SoftDeletes(
|
|
1429
|
-
* static table = posts
|
|
1430
|
-
* }
|
|
1532
|
+
* class Post extends SoftDeletes(defineModel(posts)) {}
|
|
1431
1533
|
*
|
|
1432
1534
|
* // Soft delete a record (sets deletedAt)
|
|
1433
1535
|
* await Post.delete({ id: 1 })
|
|
@@ -1561,7 +1663,7 @@ interface MySqlDatabase {
|
|
|
1561
1663
|
closeDatabase(): Promise<void>;
|
|
1562
1664
|
configureOrm(): Promise<void>;
|
|
1563
1665
|
seedDatabase(): Promise<void>;
|
|
1564
|
-
/** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1666
|
+
/** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1565
1667
|
resetDatabase(): Promise<void>;
|
|
1566
1668
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1567
1669
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1587,7 +1689,7 @@ interface SqliteDatabase {
|
|
|
1587
1689
|
closeDatabase(): Promise<void>;
|
|
1588
1690
|
configureOrm(): Promise<void>;
|
|
1589
1691
|
seedDatabase(): Promise<void>;
|
|
1590
|
-
/** Drops every table (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1692
|
+
/** Drops every table and view (including the drizzle migration tracker) so migrations can be re-applied from scratch. */
|
|
1591
1693
|
resetDatabase(): Promise<void>;
|
|
1592
1694
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1593
1695
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1675,13 +1777,35 @@ interface AwsDataApiDatabase {
|
|
|
1675
1777
|
}
|
|
1676
1778
|
declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
|
|
1677
1779
|
|
|
1678
|
-
|
|
1679
|
-
|
|
1780
|
+
/**
|
|
1781
|
+
* The context a seeder receives. `db` is the drizzle database the app
|
|
1782
|
+
* configured, so its type depends on the dialect: annotate the seeder with the
|
|
1783
|
+
* matching alias below (or pass the driver's own database type) whenever the
|
|
1784
|
+
* app is not on PostgreSQL.
|
|
1785
|
+
*
|
|
1786
|
+
* The type parameter defaults to `PostgresJsDatabase` for backwards
|
|
1787
|
+
* compatibility — seeders written before this was generic keep compiling.
|
|
1788
|
+
*/
|
|
1789
|
+
interface SeederContext<TDatabase = PostgresJsDatabase> {
|
|
1790
|
+
db: TDatabase;
|
|
1680
1791
|
}
|
|
1681
|
-
type SeederHandler = (context: SeederContext) => unknown;
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1792
|
+
type SeederHandler<TDatabase = PostgresJsDatabase> = (context: SeederContext<TDatabase>) => unknown;
|
|
1793
|
+
/** Seeder context for apps created with `createPostgresDatabase()`. */
|
|
1794
|
+
type PostgresSeederContext = SeederContext<PostgresJsDatabase>;
|
|
1795
|
+
/** Seeder context for apps created with `createMySqlDatabase()`. */
|
|
1796
|
+
type MySqlSeederContext = SeederContext<MySql2Database>;
|
|
1797
|
+
/** Seeder context for apps created with `createSqliteDatabase()`. */
|
|
1798
|
+
type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
|
|
1799
|
+
/** Seeder context for apps created with `createAwsDataApiDatabase()`. */
|
|
1800
|
+
type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase$1>;
|
|
1801
|
+
/**
|
|
1802
|
+
* Seeders are loaded as modules, so the dialect they were written against is
|
|
1803
|
+
* unknowable here. `TDatabase` is the caller stating which database it will
|
|
1804
|
+
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
1805
|
+
*/
|
|
1806
|
+
declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
|
|
1807
|
+
declare function runSeeders<TDatabase>(db: TDatabase, directory: string | URL): Promise<void>;
|
|
1808
|
+
declare function defineSeeder<TDatabase = PostgresJsDatabase>(handler: SeederHandler<TDatabase>): SeederHandler<TDatabase>;
|
|
1685
1809
|
|
|
1686
1810
|
/**
|
|
1687
1811
|
* Serialize a model record for API/JSON output.
|
|
@@ -1697,4 +1821,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1697
1821
|
/** Serialize an array of records. */
|
|
1698
1822
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1699
1823
|
|
|
1700
|
-
export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, 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, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
|
1824
|
+
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.
|
|
770
|
-
*
|
|
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
|
|
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
|
-
|
|
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}
|
|
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.
|
|
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.
|
|
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
|
|
1030
|
-
*
|
|
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
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
* `
|
|
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.
|
|
1042
1056
|
*/
|
|
1043
|
-
static
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
* Defaults to `['id']`. Ignored if `fillable` is set.
|
|
1047
|
-
*
|
|
1048
|
-
* @example
|
|
1049
|
-
* class Post extends Model<PostRecord> {
|
|
1050
|
-
* static guarded = ['id', 'createdAt']
|
|
1051
|
-
* }
|
|
1052
|
-
*/
|
|
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
|
-
*
|
|
1338
|
-
*
|
|
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
|
-
|
|
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
|
|
1361
|
-
|
|
1362
|
-
|
|
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 = {
|
|
1366
|
-
for (const key of
|
|
1367
|
-
|
|
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,12 @@ function defineModel(table, options = {}) {
|
|
|
2502
2513
|
;
|
|
2503
2514
|
DefinedModel.table = table;
|
|
2504
2515
|
DefinedModel.recordType = {};
|
|
2505
|
-
DefinedModel.createType =
|
|
2516
|
+
DefinedModel.createType = {};
|
|
2517
|
+
if (options.fillable) DefinedModel.fillable = [...options.fillable];
|
|
2518
|
+
if (options.hidden) DefinedModel.hidden = [...options.hidden];
|
|
2519
|
+
if (options.visible) DefinedModel.visible = [...options.visible];
|
|
2520
|
+
if (options.accessors) DefinedModel.accessors = options.accessors;
|
|
2521
|
+
if (options.appends) DefinedModel.appends = [...options.appends];
|
|
2506
2522
|
return DefinedModel;
|
|
2507
2523
|
}
|
|
2508
2524
|
function normalizeOrderBy(order) {
|
|
@@ -2610,11 +2626,85 @@ function getRegistry() {
|
|
|
2610
2626
|
function isHotReloadRuntime() {
|
|
2611
2627
|
return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
|
|
2612
2628
|
}
|
|
2613
|
-
|
|
2614
|
-
|
|
2629
|
+
var WHITESPACE = /\s/;
|
|
2630
|
+
var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
2631
|
+
var OPEN_PAREN = 40;
|
|
2632
|
+
var CLOSE_PAREN = 41;
|
|
2633
|
+
function isLineTerminator(code) {
|
|
2634
|
+
return code === 10 || code === 13 || code === 8232 || code === 8233;
|
|
2635
|
+
}
|
|
2636
|
+
function isDigitAt(text, index) {
|
|
2637
|
+
const code = text.charCodeAt(index);
|
|
2638
|
+
return code >= 48 && code <= 57;
|
|
2639
|
+
}
|
|
2640
|
+
function locationSplits(frame, end) {
|
|
2641
|
+
let cursor = end;
|
|
2642
|
+
while (cursor > 0 && isDigitAt(frame, cursor - 1)) cursor -= 1;
|
|
2643
|
+
if (cursor === end || cursor === 0 || frame[cursor - 1] !== ":") return [];
|
|
2644
|
+
const lastColon = cursor - 1;
|
|
2645
|
+
cursor = lastColon;
|
|
2646
|
+
while (cursor > 0 && isDigitAt(frame, cursor - 1)) cursor -= 1;
|
|
2647
|
+
return cursor < lastColon && cursor > 0 && frame[cursor - 1] === ":" ? [cursor - 1, lastColon] : [lastColon];
|
|
2648
|
+
}
|
|
2649
|
+
function pathBefore(frame, from, splits) {
|
|
2650
|
+
for (const split of splits) {
|
|
2651
|
+
if (split > from) return frame.slice(from, split);
|
|
2652
|
+
}
|
|
2653
|
+
return void 0;
|
|
2615
2654
|
}
|
|
2655
|
+
function matchingOpenParen(frame, closeIndex) {
|
|
2656
|
+
if (frame.charCodeAt(closeIndex) !== CLOSE_PAREN) {
|
|
2657
|
+
return void 0;
|
|
2658
|
+
}
|
|
2659
|
+
let depth = 0;
|
|
2660
|
+
let leftmostOpen;
|
|
2661
|
+
for (let index = closeIndex; index >= 0; index--) {
|
|
2662
|
+
const code = frame.charCodeAt(index);
|
|
2663
|
+
if (isLineTerminator(code)) {
|
|
2664
|
+
break;
|
|
2665
|
+
}
|
|
2666
|
+
if (code === CLOSE_PAREN) {
|
|
2667
|
+
depth++;
|
|
2668
|
+
} else if (code === OPEN_PAREN) {
|
|
2669
|
+
if (--depth === 0) {
|
|
2670
|
+
return index;
|
|
2671
|
+
}
|
|
2672
|
+
leftmostOpen = index;
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
return leftmostOpen;
|
|
2676
|
+
}
|
|
2677
|
+
function parseFrameLocation(frame) {
|
|
2678
|
+
const end = frame.trimEnd().length;
|
|
2679
|
+
if (end > 0 && frame[end - 1] === ")") {
|
|
2680
|
+
const splits2 = locationSplits(frame, end - 1);
|
|
2681
|
+
const open = splits2.length === 0 ? void 0 : matchingOpenParen(frame, end - 1);
|
|
2682
|
+
const path2 = open === void 0 ? void 0 : pathBefore(frame, open + 1, splits2);
|
|
2683
|
+
if (path2 !== void 0 && !path2.startsWith("eval at ")) return path2;
|
|
2684
|
+
}
|
|
2685
|
+
let cursor = 0;
|
|
2686
|
+
while (cursor < end && WHITESPACE.test(frame[cursor])) cursor += 1;
|
|
2687
|
+
if (!frame.startsWith("at", cursor)) return void 0;
|
|
2688
|
+
const afterAt = cursor + 2;
|
|
2689
|
+
let pathStart = afterAt;
|
|
2690
|
+
while (pathStart < end && WHITESPACE.test(frame[pathStart])) pathStart += 1;
|
|
2691
|
+
if (pathStart === afterAt) return void 0;
|
|
2692
|
+
const splits = locationSplits(frame, end);
|
|
2693
|
+
if (splits.length === 0) return void 0;
|
|
2694
|
+
pathStart = Math.min(pathStart, splits[splits.length - 1] - 1);
|
|
2695
|
+
if (pathStart <= afterAt) return void 0;
|
|
2696
|
+
const path = pathBefore(frame, pathStart, splits);
|
|
2697
|
+
return path !== void 0 && !LINE_TERMINATOR.test(path) ? path : void 0;
|
|
2698
|
+
}
|
|
2699
|
+
var SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set(["unknown", "native", "<anonymous>"]);
|
|
2616
2700
|
function describeCallerFile(stack) {
|
|
2617
|
-
|
|
2701
|
+
for (const frame of stack?.split("\n").slice(2) ?? []) {
|
|
2702
|
+
const path = parseFrameLocation(frame);
|
|
2703
|
+
if (path && !SYNTHETIC_FRAME_PATHS.has(path)) {
|
|
2704
|
+
return path;
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
return void 0;
|
|
2618
2708
|
}
|
|
2619
2709
|
function hotReloadKey(driver, stack, target) {
|
|
2620
2710
|
if (!isHotReloadRuntime()) {
|
|
@@ -3174,12 +3264,17 @@ function createMySqlDatabase(options) {
|
|
|
3174
3264
|
const { sql } = await import("drizzle-orm");
|
|
3175
3265
|
await withAdminDb(async (adminDb) => {
|
|
3176
3266
|
const [rows] = await adminDb.execute(
|
|
3177
|
-
sql.raw(
|
|
3267
|
+
sql.raw(
|
|
3268
|
+
"SELECT table_name AS name, table_type AS type FROM information_schema.tables WHERE table_schema = DATABASE()"
|
|
3269
|
+
)
|
|
3178
3270
|
);
|
|
3179
3271
|
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 0"));
|
|
3180
3272
|
try {
|
|
3181
|
-
for (const { name } of rows) {
|
|
3182
|
-
|
|
3273
|
+
for (const { name, type } of rows) {
|
|
3274
|
+
const identifier = sql.identifier(name);
|
|
3275
|
+
await adminDb.execute(
|
|
3276
|
+
type === "VIEW" ? sql`DROP VIEW IF EXISTS ${identifier}` : sql`DROP TABLE IF EXISTS ${identifier}`
|
|
3277
|
+
);
|
|
3183
3278
|
}
|
|
3184
3279
|
} finally {
|
|
3185
3280
|
await adminDb.execute(sql.raw("SET FOREIGN_KEY_CHECKS = 1"));
|
|
@@ -3302,11 +3397,14 @@ function createSqliteDatabase(options) {
|
|
|
3302
3397
|
async resetDatabase() {
|
|
3303
3398
|
await ensureDatabase2();
|
|
3304
3399
|
if (!sqliteClient) return;
|
|
3305
|
-
const
|
|
3400
|
+
const objects = sqliteClient.query(
|
|
3401
|
+
"SELECT name, type FROM main.sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'"
|
|
3402
|
+
).all();
|
|
3306
3403
|
sqliteClient.exec("PRAGMA foreign_keys = OFF;");
|
|
3307
3404
|
try {
|
|
3308
|
-
for (const { name } of
|
|
3309
|
-
|
|
3405
|
+
for (const { name, type } of objects) {
|
|
3406
|
+
const quoted = `main."${name.replaceAll('"', '""')}"`;
|
|
3407
|
+
sqliteClient.exec(type === "view" ? `DROP VIEW IF EXISTS ${quoted}` : `DROP TABLE IF EXISTS ${quoted}`);
|
|
3310
3408
|
}
|
|
3311
3409
|
} finally {
|
|
3312
3410
|
sqliteClient.exec("PRAGMA foreign_keys = ON;");
|
|
@@ -3336,10 +3434,7 @@ function createSqliteDatabase(options) {
|
|
|
3336
3434
|
}
|
|
3337
3435
|
const database2 = await ensureDatabase2();
|
|
3338
3436
|
try {
|
|
3339
|
-
await runSeeders(
|
|
3340
|
-
database2,
|
|
3341
|
-
resolvedSeedersFolder
|
|
3342
|
-
);
|
|
3437
|
+
await runSeeders(database2, resolvedSeedersFolder);
|
|
3343
3438
|
} catch (error) {
|
|
3344
3439
|
throw seedFailure(error);
|
|
3345
3440
|
}
|