@guren/orm 2.12.0 → 2.13.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/README.md CHANGED
@@ -57,7 +57,13 @@ Relationships, scopes, soft deletes, observers, accessors and mutators, and eage
57
57
 
58
58
  ## Mass assignment
59
59
 
60
- `fillable` is the allowlist, and it is always strict: primary keys are excluded, and an `AuthenticatableModel` refuses password hashes and remember tokens whatever the list says. Trusted values go through `forceCreate()` and `forceUpdate()`.
60
+ `fillable` is the allowlist, and it is always strict: primary keys are excluded, and an `AuthenticatableModel` refuses password hashes and remember tokens whatever the list says. A column the server chooses next to request data, such as an owner, goes in `set` and stays out of `fillable`:
61
+
62
+ ```typescript
63
+ const post = await Post.create(data, { set: { authorId: user.id } })
64
+ ```
65
+
66
+ Writes that carry no request data at all (seeders, system records) go through `forceCreate()` and `forceUpdate()`.
61
67
 
62
68
  ## Dialect subpaths
63
69
 
package/dist/index.d.ts CHANGED
@@ -340,6 +340,12 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
340
340
  */
341
341
  private filtersEvaporated;
342
342
  private assertFiltersSurvived;
343
+ /**
344
+ * `where(field, 'is null')` type-checks through the `(field, value)` overload on
345
+ * any string column and compiles to `field = 'is null'`, silently dropping the
346
+ * NULL rows. A value-taking token (`'like'`) is left alone: it can be real data.
347
+ */
348
+ private refuseOperatorAsValue;
343
349
  private addSimpleCondition;
344
350
  private executeQuery;
345
351
  /**
@@ -514,6 +520,11 @@ interface AdapterQueryOptions {
514
520
  trx?: unknown;
515
521
  }
516
522
  type ModelWriteOptions = AdapterQueryOptions;
523
+ /** The options of `create(data, { set })` and `update(where, data, { set })` (RFC 0031). */
524
+ type ModelSetOptions<T extends typeof Model, S extends PlainObject> = ModelWriteOptions & SetOption<T, S>;
525
+ type WithoutSet = ModelWriteOptions & {
526
+ set?: never;
527
+ };
517
528
  type ModelQueryOptions = AdapterQueryOptions;
518
529
  type TransactionHandle = NonNullable<AdapterQueryOptions['trx']>;
519
530
  type SelectFrom<TDatabase> = TDatabase extends {
@@ -552,9 +563,9 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
552
563
  /**
553
564
  * Mass-assignment allowlist. When set, any other key in `create()`/`update()`
554
565
  * input throws a MassAssignmentException rather than being discarded, so
555
- * bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
556
- * the trusted-data escape. Independent of it, `id` is always stripped and
557
- * `deniedFields()` always throws.
566
+ * bugs and injection attempts surface. A column the server chooses goes in
567
+ * `set`, and must stay out of this list. Independent of it, `id` is always
568
+ * stripped and `deniedFields()` always throws.
558
569
  */
559
570
  static fillable?: string[];
560
571
  /**
@@ -628,11 +639,13 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
628
639
  */
629
640
  static [READ_TRANSFORMS]<T extends PlainObject>(records: T[], projected?: boolean): T[];
630
641
  /**
631
- * In order: `deniedFields()` throws, checked on the raw input so no later
632
- * rule can swallow them; `id` is stripped silently; then, with `fillable`
633
- * set, anything outside it throws.
642
+ * In order: a non-empty `set` is refused without `fillable`, or holding `id`,
643
+ * a denied or a fillable key (RFC 0031); `deniedFields()` throws, checked on
644
+ * the raw input so no later rule can swallow them; `id` is stripped silently;
645
+ * then, with `fillable` set, anything outside it throws. `set` is merged last.
634
646
  */
635
- static filterFillable(data: PlainObject): PlainObject;
647
+ static filterFillable(data: PlainObject, set?: PlainObject): PlainObject;
648
+ private static assertSettable;
636
649
  protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
637
650
  /** @internal Lets QueryBuilder bulk updates run the same payload preparation as `Model.update()`. */
638
651
  static prepareBulkPersistencePayload(data: PlainObject): Promise<PlainObject>;
@@ -746,20 +759,32 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
746
759
  */
747
760
  private static paginationQuery;
748
761
  static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
749
- static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
750
762
  /**
751
- * Create bypassing mass-assignment protection. Trusted server-side data only
752
- * (OAuth linking, seeders, system records), never raw request input.
763
+ * `set` holds the columns the server chose, such as an owner. They skip
764
+ * `fillable`, must not be in it, and `data` is filtered as without `set`.
765
+ *
766
+ * @example
767
+ * await Post.create(data, { set: { authorId: user.id } })
768
+ */
769
+ static create<T extends typeof Model, S extends PlainObject>(this: T, data: CreateDataFor<T, NoInfer<S>>, options: ModelSetOptions<T, S>): Promise<TRecordFor<T>>;
770
+ static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: WithoutSet): Promise<TRecordFor<T>>;
771
+ /**
772
+ * Create bypassing mass-assignment protection. Data that carries nothing from
773
+ * the request only (OAuth linking, seeders, system records); a server-chosen
774
+ * column next to request data goes in `create(data, { set })`.
753
775
  */
754
776
  static forceCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
755
- protected static runCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean): Promise<TRecordFor<T>>;
756
- static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
777
+ protected static runCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean, set?: PlainObject): Promise<TRecordFor<T>>;
778
+ /** `set` as in `create(data, { set })`. */
779
+ static update<T extends typeof Model, S extends PlainObject>(this: T, where: WhereClauseFor<T>, data: Partial<CreateDataFor<T, NoInfer<S>>>, options: ModelSetOptions<T, S>): Promise<TRecordFor<T>>;
780
+ static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: WithoutSet): Promise<TRecordFor<T>>;
757
781
  /**
758
- * Update bypassing mass-assignment protection. Trusted server-side data only,
759
- * never raw request input.
782
+ * Update bypassing mass-assignment protection. Data that carries nothing from
783
+ * the request only; a server-chosen column next to request data goes in
784
+ * `update(where, data, { set })`.
760
785
  */
761
786
  static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
762
- protected static runUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean): Promise<TRecordFor<T>>;
787
+ protected static runUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean, set?: PlainObject): Promise<TRecordFor<T>>;
763
788
  static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
764
789
  /**
765
790
  * Runs `write` between the `deleting` and `deleted` events, for `delete()`
@@ -827,6 +852,14 @@ type TRecordFor<T extends typeof Model> = T extends {
827
852
  type TCreateFor<T extends typeof Model> = T extends {
828
853
  createType: infer R;
829
854
  } ? R extends PlainObject ? R : PlainObject : PlainObject;
855
+ type OmitNamed<T, K extends PropertyKey> = { [P in keyof T as P extends K ? never : P]: T[P]; };
856
+ type NamedKeys<T> = keyof { [P in keyof T as string extends P ? never : number extends P ? never : P]: T[P]; };
857
+ type SetOption<T extends typeof Model, S> = {
858
+ set: S & { [K in Exclude<keyof S, SettableKey<T>>]: never; } & { [K in Extract<keyof S, keyof TCreateFor<T>>]: TCreateFor<T>[K]; };
859
+ };
860
+ type SettableKey<T extends typeof Model> = [SetKey<T>] extends [never] ? PropertyKey : SetKey<T>;
861
+ type SetKey<T extends typeof Model> = Exclude<NamedKeys<TCreateFor<T>>, 'id'>;
862
+ type CreateDataFor<T extends typeof Model, S> = OmitNamed<TCreateFor<T>, keyof S> & { [K in keyof S]?: never; };
830
863
  type WhereClauseFor<T extends typeof Model> = WhereClause<TRecordFor<T>>;
831
864
  type FieldFor<T extends typeof Model> = keyof TRecordFor<T> & string;
832
865
  type RelationPath<T extends typeof Model> = RelationKey<T> | `${RelationKey<T>}.${string}`;
@@ -850,7 +883,9 @@ interface TransactionModelScope<T extends typeof Model> {
850
883
  where(field: FieldFor<T>, value: unknown): QueryBuilder<TRecordFor<T>>;
851
884
  where(field: FieldFor<T>, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
852
885
  newQuery(): QueryBuilder<TRecordFor<T>>;
886
+ create<S extends PlainObject>(data: CreateDataFor<T, NoInfer<S>>, options: SetOption<T, S>): Promise<TRecordFor<T>>;
853
887
  create(data: TCreateFor<T>): Promise<TRecordFor<T>>;
888
+ update<S extends PlainObject>(where: WhereClauseFor<T>, data: Partial<CreateDataFor<T, NoInfer<S>>>, options: SetOption<T, S>): Promise<TRecordFor<T>>;
854
889
  update(where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>): Promise<TRecordFor<T>>;
855
890
  delete(where: WhereClauseFor<T>): Promise<number | PlainObject | void>;
856
891
  paginate(options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T>>>;
@@ -948,17 +983,28 @@ declare class ModelNotFoundException extends Error {
948
983
  /**
949
984
  * Thrown when mass assignment receives fields it must not write. Discarding
950
985
  * them silently hides bugs and can mask injection attempts, so models throw.
951
- * `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
952
- * `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
986
+ * `reason` is `'denied'` for a field in `deniedFields()`, unassignable whatever
987
+ * `fillable` says, and `'not-fillable'` for every other refusal: a field outside
988
+ * `fillable`, or a `set` the allowlist does not admit (RFC 0031).
953
989
  */
954
990
  declare class MassAssignmentException extends Error {
955
991
  readonly model: string;
956
992
  readonly fields: string[];
957
993
  readonly reason: 'not-fillable' | 'denied';
994
+ /**
995
+ * `set` names the `create(data, { set })` rule that refused the fields and
996
+ * only changes the message: `'no-fillable'` (the model declares no `fillable`),
997
+ * `'id'`, `'fillable'` (a `set` key a request may already write) or
998
+ * `'conflict'` (a key in both `data` and `set`).
999
+ */
958
1000
  constructor(model: string, fields: string[], options?: {
959
- reason?: 'not-fillable' | 'denied';
1001
+ reason?: 'not-fillable';
1002
+ set?: SetRule;
1003
+ } | {
1004
+ reason: 'denied';
960
1005
  });
961
1006
  }
1007
+ type SetRule = 'no-fillable' | 'id' | 'fillable' | 'conflict';
962
1008
  //#endregion
963
1009
  //#region src/SoftDeletes.d.ts
964
1010
  /** The static methods the SoftDeletes mixin adds. */
@@ -1327,4 +1373,4 @@ declare function serializeRecord(record: PlainObject, options: {
1327
1373
  /** Serialize an array of records. */
1328
1374
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1329
1375
  //#endregion
1330
- export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1376
+ export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, 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 OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
package/dist/index.js CHANGED
@@ -1248,6 +1248,10 @@ var ModelNotFoundException = class extends Error {
1248
1248
  };
1249
1249
  //#endregion
1250
1250
  //#region src/QueryBuilder.ts
1251
+ const VALUELESS_OPERATOR_HELPERS = {
1252
+ "is null": "whereNull",
1253
+ "is not null": "whereNotNull"
1254
+ };
1251
1255
  /**
1252
1256
  * Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
1253
1257
  * resolves to the result of `get()`.
@@ -1282,8 +1286,10 @@ var QueryBuilder = class QueryBuilder {
1282
1286
  return this;
1283
1287
  }
1284
1288
  const field = fieldOrConditions;
1285
- if (arguments.length === 2) this.addSimpleCondition(field, Array.isArray(operatorOrValue) ? "in" : "=", operatorOrValue);
1286
- else this.addSimpleCondition(field, operatorOrValue, value);
1289
+ if (arguments.length === 2) {
1290
+ this.refuseOperatorAsValue("where", field, operatorOrValue);
1291
+ this.addSimpleCondition(field, Array.isArray(operatorOrValue) ? "in" : "=", operatorOrValue);
1292
+ } else this.addSimpleCondition(field, operatorOrValue, value);
1287
1293
  return this;
1288
1294
  }
1289
1295
  orWhere(fieldOrConditions, operatorOrValue, value) {
@@ -1295,13 +1301,15 @@ var QueryBuilder = class QueryBuilder {
1295
1301
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) orConditions.push(...this.simpleConditionsFrom(fieldOrConditions));
1296
1302
  else {
1297
1303
  const field = fieldOrConditions;
1298
- if (arguments.length === 2) orConditions.push({
1299
- type: "simple",
1300
- field,
1301
- operator: Array.isArray(operatorOrValue) ? "in" : "=",
1302
- value: operatorOrValue
1303
- });
1304
- else orConditions.push({
1304
+ if (arguments.length === 2) {
1305
+ this.refuseOperatorAsValue("orWhere", field, operatorOrValue);
1306
+ orConditions.push({
1307
+ type: "simple",
1308
+ field,
1309
+ operator: Array.isArray(operatorOrValue) ? "in" : "=",
1310
+ value: operatorOrValue
1311
+ });
1312
+ } else orConditions.push({
1305
1313
  type: "simple",
1306
1314
  field,
1307
1315
  operator: operatorOrValue,
@@ -1685,6 +1693,18 @@ var QueryBuilder = class QueryBuilder {
1685
1693
  if (!this.filtersEvaporated()) return;
1686
1694
  throw new Error(`${this.modelClass.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
1687
1695
  }
1696
+ /**
1697
+ * `where(field, 'is null')` type-checks through the `(field, value)` overload on
1698
+ * any string column and compiles to `field = 'is null'`, silently dropping the
1699
+ * NULL rows. A value-taking token (`'like'`) is left alone: it can be real data.
1700
+ */
1701
+ refuseOperatorAsValue(method, field, value) {
1702
+ if (typeof value !== "string" || !Object.hasOwn(VALUELESS_OPERATOR_HELPERS, value)) return;
1703
+ const helper = `${VALUELESS_OPERATOR_HELPERS[value]}('${field}')`;
1704
+ const threeArgument = `${method}('${field}', '${value}', null)`;
1705
+ const fix = method === "where" ? `Use ${helper} or ${threeArgument}` : `Use ${threeArgument}, the OR form of ${helper}`;
1706
+ throw new Error(`${this.modelClass.name}: ${method}('${field}', '${value}') would compare ${field} to the string '${value}'. ${fix}; to match that string, write ${method}('${field}', '=', '${value}').`);
1707
+ }
1688
1708
  addSimpleCondition(field, operator, value) {
1689
1709
  this.conditions.push({
1690
1710
  type: "simple",
@@ -1770,24 +1790,41 @@ function serializeRecords(records, options) {
1770
1790
  /**
1771
1791
  * Thrown when mass assignment receives fields it must not write. Discarding
1772
1792
  * them silently hides bugs and can mask injection attempts, so models throw.
1773
- * `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
1774
- * `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
1793
+ * `reason` is `'denied'` for a field in `deniedFields()`, unassignable whatever
1794
+ * `fillable` says, and `'not-fillable'` for every other refusal: a field outside
1795
+ * `fillable`, or a `set` the allowlist does not admit (RFC 0031).
1775
1796
  */
1776
1797
  var MassAssignmentException = class extends Error {
1777
1798
  model;
1778
1799
  fields;
1779
1800
  reason;
1801
+ /**
1802
+ * `set` names the `create(data, { set })` rule that refused the fields and
1803
+ * only changes the message: `'no-fillable'` (the model declares no `fillable`),
1804
+ * `'id'`, `'fillable'` (a `set` key a request may already write) or
1805
+ * `'conflict'` (a key in both `data` and `set`).
1806
+ */
1780
1807
  constructor(model, fields, options) {
1781
1808
  const reason = options?.reason ?? "not-fillable";
1809
+ const set = options && "set" in options ? options.set : void 0;
1782
1810
  const list = fields.map((field) => `"${field}"`).join(", ");
1783
- const remediation = reason === "denied" ? `These are protected columns (e.g. credential fields) and can never be mass-assigned — 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.`;
1784
- super(`${model}: mass assignment blocked for field(s) ${list}. ${remediation} Never call forceCreate/forceUpdate with request input.`);
1811
+ super(`${model}: mass assignment blocked for field(s) ${list}. ${remediation(model, fields, reason, set)} Never pass request input to forceCreate/forceUpdate or spread it into set.`);
1785
1812
  this.name = "MassAssignmentException";
1786
1813
  this.model = model;
1787
1814
  this.fields = fields;
1788
1815
  this.reason = reason;
1789
1816
  }
1790
1817
  };
1818
+ function remediation(model, fields, reason, set) {
1819
+ if (reason === "denied") return `These are protected columns (e.g. credential fields) and can never be mass-assigned, not even through ${model}.fillable or set. 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:...'\`.`;
1820
+ switch (set) {
1821
+ case "no-fillable": return `${model} declares no fillable, so every column is already writable through the data and set would keep nothing apart. Declare fillable with the columns a request may set.`;
1822
+ case "id": return `set cannot carry the primary key: a server-chosen id is a system write, which belongs in ${model}.forceCreate().`;
1823
+ case "fillable": return `They are in ${model}.fillable, so a request may already set them: pass them in the data. A column the server sets must not be fillable, or every other write would accept it from a request.`;
1824
+ case "conflict": return `They are set by the server in this call, so they must not also arrive in the data.`;
1825
+ default: return `Add them to fillable if a request may set them; if the server chooses the value, name it in the set option of ${model}.create() or ${model}.update(): { set: { ${fields.join(", ")} } }.`;
1826
+ }
1827
+ }
1791
1828
  //#endregion
1792
1829
  //#region src/Model.ts
1793
1830
  /**
@@ -1821,9 +1858,9 @@ var Model = class Model {
1821
1858
  /**
1822
1859
  * Mass-assignment allowlist. When set, any other key in `create()`/`update()`
1823
1860
  * input throws a MassAssignmentException rather than being discarded, so
1824
- * bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
1825
- * the trusted-data escape. Independent of it, `id` is always stripped and
1826
- * `deniedFields()` always throws.
1861
+ * bugs and injection attempts surface. A column the server chooses goes in
1862
+ * `set`, and must stay out of this list. Independent of it, `id` is always
1863
+ * stripped and `deniedFields()` always throws.
1827
1864
  */
1828
1865
  static fillable;
1829
1866
  /**
@@ -1863,10 +1900,11 @@ var Model = class Model {
1863
1900
  }
1864
1901
  /** A model scope that forwards `trx` to every query and write on it. */
1865
1902
  static inTransaction(trx) {
1866
- const where = (fieldOrConditions, operatorOrValue, value) => {
1903
+ const where = (...args) => {
1904
+ const [fieldOrConditions, operatorOrValue, value] = args;
1867
1905
  if (typeof fieldOrConditions === "function") return this.newQuery({ trx }).where(fieldOrConditions);
1868
1906
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) return this.newQuery({ trx }).where(fieldOrConditions);
1869
- if (value !== void 0) return this.newQuery({ trx }).where(fieldOrConditions, operatorOrValue, value);
1907
+ if (args.length === 3) return this.newQuery({ trx }).where(fieldOrConditions, operatorOrValue, value);
1870
1908
  return this.newQuery({ trx }).where(fieldOrConditions, operatorOrValue);
1871
1909
  };
1872
1910
  return {
@@ -1877,8 +1915,14 @@ var Model = class Model {
1877
1915
  first: (where) => this.first(where, { trx }),
1878
1916
  where,
1879
1917
  newQuery: () => this.newQuery({ trx }),
1880
- create: (data) => this.create(data, { trx }),
1881
- update: (where, data) => this.update(where, data, { trx }),
1918
+ create: ((data, options) => this.create(data, {
1919
+ ...options,
1920
+ trx
1921
+ })),
1922
+ update: ((where, data, options) => this.update(where, data, {
1923
+ ...options,
1924
+ trx
1925
+ })),
1882
1926
  delete: (where) => this.delete(where, { trx }),
1883
1927
  paginate: (options) => this.paginate(options, { trx })
1884
1928
  };
@@ -1972,25 +2016,43 @@ var Model = class Model {
1972
2016
  return records.map((record) => this.applyReadTransforms(record));
1973
2017
  }
1974
2018
  /**
1975
- * In order: `deniedFields()` throws, checked on the raw input so no later
1976
- * rule can swallow them; `id` is stripped silently; then, with `fillable`
1977
- * set, anything outside it throws.
2019
+ * In order: a non-empty `set` is refused without `fillable`, or holding `id`,
2020
+ * a denied or a fillable key (RFC 0031); `deniedFields()` throws, checked on
2021
+ * the raw input so no later rule can swallow them; `id` is stripped silently;
2022
+ * then, with `fillable` set, anything outside it throws. `set` is merged last.
1978
2023
  */
1979
- static filterFillable(data) {
1980
- const denied = this.deniedFields().filter((field) => field in data);
2024
+ static filterFillable(data, set) {
2025
+ const fillableFields = this.fillable;
2026
+ const deniedFields = this.deniedFields();
2027
+ const setKeys = set ? Object.keys(set) : [];
2028
+ if (setKeys.length > 0) this.assertSettable(setKeys, fillableFields, deniedFields);
2029
+ const denied = deniedFields.filter((field) => field in data);
1981
2030
  if (denied.length > 0) throw new MassAssignmentException(this.name, denied, { reason: "denied" });
1982
2031
  let candidate = data;
1983
2032
  if ("id" in candidate) {
1984
2033
  const { id: _id, ...rest } = candidate;
1985
2034
  candidate = rest;
1986
2035
  }
1987
- const fillableFields = this.fillable;
1988
2036
  if (!fillableFields) return candidate;
1989
2037
  const blocked = Object.keys(candidate).filter((key) => !fillableFields.includes(key));
1990
- if (blocked.length > 0) throw new MassAssignmentException(this.name, blocked);
2038
+ if (blocked.length > 0) {
2039
+ const alsoSet = blocked.filter((key) => setKeys.includes(key));
2040
+ throw alsoSet.length > 0 ? new MassAssignmentException(this.name, alsoSet, { set: "conflict" }) : new MassAssignmentException(this.name, blocked);
2041
+ }
1991
2042
  const filtered = {};
1992
2043
  for (const key of fillableFields) if (key in candidate) filtered[key] = candidate[key];
1993
- return filtered;
2044
+ return setKeys.length > 0 ? {
2045
+ ...filtered,
2046
+ ...set
2047
+ } : filtered;
2048
+ }
2049
+ static assertSettable(keys, fillableFields, deniedFields) {
2050
+ if (!fillableFields) throw new MassAssignmentException(this.name, keys, { set: "no-fillable" });
2051
+ if (keys.includes("id")) throw new MassAssignmentException(this.name, ["id"], { set: "id" });
2052
+ const denied = keys.filter((key) => deniedFields.includes(key));
2053
+ if (denied.length > 0) throw new MassAssignmentException(this.name, denied, { reason: "denied" });
2054
+ const fillable = keys.filter((key) => fillableFields.includes(key));
2055
+ if (fillable.length > 0) throw new MassAssignmentException(this.name, fillable, { set: "fillable" });
1994
2056
  }
1995
2057
  static async preparePersistencePayload(data) {
1996
2058
  let result = { ...data };
@@ -2046,7 +2108,7 @@ var Model = class Model {
2046
2108
  }
2047
2109
  static async find(id, key = "id", queryOptions) {
2048
2110
  if (id === void 0) return null;
2049
- if (this.hasScopes()) return this.newQuery(queryOptions).where(key, id).first();
2111
+ if (this.hasScopes()) return this.newQuery(queryOptions).where({ [key]: id }).first();
2050
2112
  const table = this.resolveTable();
2051
2113
  const where = { [key]: id };
2052
2114
  const record = await this.getAdapter().findUnique(table, where, queryOptions);
@@ -2294,19 +2356,22 @@ var Model = class Model {
2294
2356
  perPage: options.perPage
2295
2357
  });
2296
2358
  }
2297
- static async create(data, writeOptions) {
2298
- return this.runCreate(data, writeOptions, true);
2359
+ static async create(data, options) {
2360
+ if (options?.set === void 0) return this.runCreate(data, options, true);
2361
+ const { set, ...writeOptions } = options;
2362
+ return this.runCreate(data, writeOptions, true, set);
2299
2363
  }
2300
2364
  /**
2301
- * Create bypassing mass-assignment protection. Trusted server-side data only
2302
- * (OAuth linking, seeders, system records), never raw request input.
2365
+ * Create bypassing mass-assignment protection. Data that carries nothing from
2366
+ * the request only (OAuth linking, seeders, system records); a server-chosen
2367
+ * column next to request data goes in `create(data, { set })`.
2303
2368
  */
2304
2369
  static async forceCreate(data, writeOptions) {
2305
2370
  return this.runCreate(data, writeOptions, false);
2306
2371
  }
2307
- static async runCreate(data, writeOptions, applyFillable) {
2372
+ static async runCreate(data, writeOptions, applyFillable, set) {
2308
2373
  const table = this.resolveTable();
2309
- const filtered = applyFillable ? this.filterFillable(data) : { ...data };
2374
+ const filtered = applyFillable ? this.filterFillable(data, set) : { ...data };
2310
2375
  const payload = await this.preparePersistencePayload(filtered);
2311
2376
  const lifecycle = modelLifecycle(this.name, "create", this.hooks, this.observers);
2312
2377
  await lifecycle.before(payload);
@@ -2314,20 +2379,23 @@ var Model = class Model {
2314
2379
  await lifecycle.after(result);
2315
2380
  return this.applyReadTransforms(result);
2316
2381
  }
2317
- static async update(where, data, writeOptions) {
2318
- return this.runUpdate(where, data, writeOptions, true);
2382
+ static async update(where, data, options) {
2383
+ if (options?.set === void 0) return this.runUpdate(where, data, options, true);
2384
+ const { set, ...writeOptions } = options;
2385
+ return this.runUpdate(where, data, writeOptions, true, set);
2319
2386
  }
2320
2387
  /**
2321
- * Update bypassing mass-assignment protection. Trusted server-side data only,
2322
- * never raw request input.
2388
+ * Update bypassing mass-assignment protection. Data that carries nothing from
2389
+ * the request only; a server-chosen column next to request data goes in
2390
+ * `update(where, data, { set })`.
2323
2391
  */
2324
2392
  static async forceUpdate(where, data, writeOptions) {
2325
2393
  return this.runUpdate(where, data, writeOptions, false);
2326
2394
  }
2327
- static async runUpdate(where, data, writeOptions, applyFillable) {
2395
+ static async runUpdate(where, data, writeOptions, applyFillable, set) {
2328
2396
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations.");
2329
2397
  this.assertFiltersSurvived(where, "update");
2330
- const filtered = applyFillable ? this.filterFillable(data) : { ...data };
2398
+ const filtered = applyFillable ? this.filterFillable(data, set) : { ...data };
2331
2399
  const payload = await this.preparePersistencePayload(filtered);
2332
2400
  const lifecycle = modelLifecycle(this.name, "update", this.hooks, this.observers);
2333
2401
  await lifecycle.before(payload);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.12.0",
3
+ "version": "2.13.0",
4
4
  "description": "Eloquent-style models for the Guren framework, on Drizzle ORM: PostgreSQL, MySQL, SQLite and Cloudflare D1.",
5
5
  "keywords": [
6
6
  "guren",