@guren/orm 2.15.0 → 2.16.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 CHANGED
@@ -68,6 +68,10 @@ declare function applyAccessors<T extends PlainObject>(record: T, accessors?: Ac
68
68
  /** Apply mutators to data before persistence, returning a new object. */
69
69
  declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions): PlainObject;
70
70
  //#endregion
71
+ //#region src/increment-amount.d.ts
72
+ /** What an adapter adds to a column; a string must match `DECIMAL_LITERAL`. */
73
+ type IncrementValue = number | bigint | string;
74
+ //#endregion
71
75
  //#region src/internal-keys.d.ts
72
76
  /**
73
77
  * What `Model`, `QueryBuilder` and the adapters share without importing each
@@ -84,6 +88,8 @@ declare const SEAL_SCOPES: unique symbol;
84
88
  declare const READ_TRANSFORMS: unique symbol;
85
89
  /** Rows as the adapter read them, for the joins a relation loader makes. */
86
90
  declare const RAW_RESULTS: unique symbol;
91
+ /** A model's own relation definitions, for the serializer, which cannot import `Model`. */
92
+ declare const RELATION_DEFINITIONS: unique symbol;
87
93
  /** Explicit physical deletion, used by SoftDeletes.forceDelete. */
88
94
  declare const PHYSICAL_DELETE: unique symbol;
89
95
  /** A static delete run inside the model's lifecycle, shared with SoftDeletes. */
@@ -104,6 +110,12 @@ type AvgValue<TValue> = unknown extends TValue ? number | string : NonNullable<T
104
110
  * A text column is a `string` too, which the type cannot tell from `numeric`.
105
111
  */
106
112
  type NumericFieldKey<TRecord extends PlainObject> = string extends keyof TRecord ? string : { [K in FieldKey<TRecord>]: [SumValue<TRecord[K]>] extends [never] ? never : K; }[FieldKey<TRecord>];
113
+ /**
114
+ * What `increment()`/`decrement()` add: a plain number, or the column's own
115
+ * kind ({@link SumValue}), so a `numeric`/`decimal` column takes a decimal string.
116
+ * A text column is a `string` too; the adapter refuses that one at runtime.
117
+ */
118
+ type IncrementAmount<TValue> = [SumValue<TValue>] extends [never] ? never : SumValue<TValue> | number;
107
119
  /** A Drizzle select builder as `toDrizzle(query)` needs it: something to add a where clause to. */
108
120
  type DrizzleWhereable = {
109
121
  where: (...args: any[]) => unknown;
@@ -302,6 +314,19 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
302
314
  * would be a supported way to bypass mass-assignment protection entirely.
303
315
  */
304
316
  [PREPARED_UPDATE](payload: PlainObject): Promise<TRecord>;
317
+ /**
318
+ * `field = field + amount` in one statement, so concurrent calls lose no
319
+ * count; resolves to the number of rows changed. Scopes apply as in
320
+ * `update()`; `fillable`, mutators and hooks do not, since code names the
321
+ * column. A `NULL` stays `NULL`.
322
+ */
323
+ increment<TKey extends NumericFieldKey<TRecord>>(field: TKey, amount?: IncrementAmount<TRecord[TKey]>): Promise<number>;
324
+ /**
325
+ * `increment()` with `amount` subtracted. A condition makes it a guard.
326
+ * @example await Product.where({ id }).where('stock', '>=', 2).decrement('stock', 2) // 0: not enough stock
327
+ */
328
+ decrement<TKey extends NumericFieldKey<TRecord>>(field: TKey, amount?: IncrementAmount<TRecord[TKey]>): Promise<number>;
329
+ private addToColumn;
305
330
  /**
306
331
  * The object-where a basic adapter takes; a condition the flat object cannot
307
332
  * carry (an OR group, an operator, two values on one field) refuses rather
@@ -400,6 +425,11 @@ interface ORMAdapterAdvanced extends ORMAdapter {
400
425
  count: number;
401
426
  }>>;
402
427
  updateAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
428
+ /**
429
+ * `UPDATE ... SET field = field + amount` under `conditions`, resolving to
430
+ * the number of rows changed. A string `amount` is a decimal literal.
431
+ */
432
+ incrementAdvanced?(table: unknown, conditions: WhereCondition[], field: string, amount: IncrementValue, writeOptions?: AdapterQueryOptions): Promise<number>;
403
433
  deleteAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
404
434
  }
405
435
  //#endregion
@@ -629,9 +659,14 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
629
659
  * that is refused; the builder repeats the check for its own callers.
630
660
  */
631
661
  private static assertFiltersSurvived;
632
- /** Applies hidden/visible filtering, accessors and appends. */
662
+ /**
663
+ * Applies hidden/visible filtering, accessors and appends, then each loaded
664
+ * relation's own model's hidden/visible to its rows, nested ones included.
665
+ */
633
666
  static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
634
667
  static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
668
+ /** @internal The serializer's view of the relations, symbol-keyed like `[READ_TRANSFORMS]`. */
669
+ static [RELATION_DEFINITIONS](): ReadonlyMap<string, RelationDefinition>;
635
670
  static applyCasts<T extends PlainObject>(record: T): T;
636
671
  /** The one read-transform pass for a record, in order: casts then accessors. */
637
672
  protected static applyReadTransforms<T extends PlainObject>(record: T): T;
@@ -667,6 +702,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
667
702
  /** @throws ModelNotFoundException (404) when no record matches. */
668
703
  static findOrFail<T extends typeof Model>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>>;
669
704
  static findWith<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
705
+ /**
706
+ * `find()` with its relations loaded ahead of the read transforms: a loader
707
+ * matches rows on raw key values, which a cast or an accessor on this model
708
+ * would have rewritten.
709
+ */
710
+ private static findRawWith;
670
711
  /**
671
712
  * Relations accept dot-notation paths (`comments.author`).
672
713
  * @throws ModelNotFoundException when no record matches.
@@ -789,6 +830,10 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
789
830
  */
790
831
  static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
791
832
  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>>;
833
+ /** `QueryBuilder.increment()` for the rows matching `where`; fires no model events. */
834
+ static increment<T extends typeof Model, K extends NumericFieldKey<TRecordFor<T>>>(this: T, where: WhereClauseFor<T>, field: K, amount?: IncrementAmount<TRecordFor<T>[K]>, writeOptions?: ModelWriteOptions): Promise<number>;
835
+ /** `increment()` with `amount` subtracted. */
836
+ static decrement<T extends typeof Model, K extends NumericFieldKey<TRecordFor<T>>>(this: T, where: WhereClauseFor<T>, field: K, amount?: IncrementAmount<TRecordFor<T>[K]>, writeOptions?: ModelWriteOptions): Promise<number>;
792
837
  static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
793
838
  /**
794
839
  * Runs `write` between the `deleting` and `deleted` events, for `delete()`
@@ -1055,7 +1100,7 @@ type DrizzleLikeInsertResult = {
1055
1100
  type DrizzleLikeUpdate = {
1056
1101
  set: (record: PlainObject) => DrizzleLikeUpdate;
1057
1102
  where: (clause: unknown) => DrizzleLikeUpdate;
1058
- returning?: () => Promise<unknown[]>;
1103
+ returning?: (selection?: Record<string, unknown>) => Promise<unknown[]>;
1059
1104
  };
1060
1105
  type DrizzleLikeDelete = {
1061
1106
  where: (clause: unknown) => DrizzleLikeDelete;
@@ -1426,4 +1471,4 @@ declare function serializeRecord(record: PlainObject, options: {
1426
1471
  /** Serialize an array of records. */
1427
1472
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1428
1473
  //#endregion
1429
- 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, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, 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 };
1474
+ 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, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, 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 IncrementAmount, 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
@@ -100,6 +100,8 @@ const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
100
100
  const READ_TRANSFORMS = Symbol("guren.orm.readTransforms");
101
101
  /** Rows as the adapter read them, for the joins a relation loader makes. */
102
102
  const RAW_RESULTS = Symbol("guren.orm.rawResults");
103
+ /** A model's own relation definitions, for the serializer, which cannot import `Model`. */
104
+ const RELATION_DEFINITIONS = Symbol("guren.orm.relationDefinitions");
103
105
  /** Model-specific bulk deletion, preserving the builder's scopes. */
104
106
  const BULK_DELETE = Symbol("guren.orm.bulkDelete");
105
107
  /** Explicit physical deletion, used by SoftDeletes.forceDelete. */
@@ -247,9 +249,38 @@ async function loadRelatedRecords(related, keys, clause, queryOptions, constrain
247
249
  async function countByChunks(values, size, count) {
248
250
  return new Map(await loadByChunks(values, size, async (chunk) => Array.from(await count(chunk))));
249
251
  }
252
+ const resolvedReferences = /* @__PURE__ */ new WeakMap();
253
+ function isModelClass(reference) {
254
+ return typeof reference.newQuery === "function";
255
+ }
250
256
  async function resolveModelReference(reference) {
251
- if (typeof reference.newQuery === "function") return reference;
252
- return await reference();
257
+ if (isModelClass(reference)) return reference;
258
+ const model = await reference();
259
+ resolvedReferences.set(reference, model);
260
+ return model;
261
+ }
262
+ const morphTargets = /* @__PURE__ */ new WeakMap();
263
+ function rememberMorphTarget(row, model) {
264
+ morphTargets.set(row, model);
265
+ }
266
+ function knownMorphTarget(row) {
267
+ return row !== null && typeof row === "object" ? morphTargets.get(row) : void 0;
268
+ }
269
+ /**
270
+ * The model a reference names. A thunk no load has resolved is called: rows can
271
+ * reach the serializer without a load in this process (a cache, a job payload).
272
+ * An asynchronous one yields `undefined` this time and is remembered once it settles.
273
+ */
274
+ function knownModelReference(reference) {
275
+ if (isModelClass(reference)) return reference;
276
+ const known = resolvedReferences.get(reference);
277
+ if (known) return known;
278
+ const result = reference();
279
+ if (isModelClass(result)) {
280
+ resolvedReferences.set(reference, result);
281
+ return result;
282
+ }
283
+ result.then((model) => resolvedReferences.set(reference, model), () => void 0);
253
284
  }
254
285
  //#endregion
255
286
  //#region src/relation-loading.ts
@@ -420,6 +451,7 @@ async function loadMorphTo(morphMap, records, definition, queryOptions, constrai
420
451
  const idMap = /* @__PURE__ */ new Map();
421
452
  for (const r of results) idMap.set(r.id, { ...r });
422
453
  applyRelatedReadTransforms(modelClass, Array.from(idMap.values()), projected);
454
+ for (const row of idMap.values()) rememberMorphTarget(row, modelClass);
423
455
  resolved.set(type, idMap);
424
456
  }
425
457
  for (const record of records) {
@@ -466,6 +498,19 @@ async function loadRelationChildren({ modelName, records, definition, head, tail
466
498
  applyRelatedReadTransforms(related, children, projected);
467
499
  }
468
500
  //#endregion
501
+ //#region src/increment-amount.ts
502
+ /** A decimal as every dialect reads it unquoted; the only string an adapter may inline. */
503
+ const DECIMAL_LITERAL = /^-?\d+(?:\.\d+)?$/;
504
+ /** Refuses anything but a finite number, a bigint or a `DECIMAL_LITERAL` string. */
505
+ function signedAmount(caller, amount, negate) {
506
+ if (typeof amount === "bigint" || typeof amount === "number" && Number.isFinite(amount)) return negate ? -amount : amount;
507
+ if (typeof amount === "string" && DECIMAL_LITERAL.test(amount)) {
508
+ if (!negate) return amount;
509
+ return amount.startsWith("-") ? amount.slice(1) : `-${amount}`;
510
+ }
511
+ throw new TypeError(`${caller}() takes a finite number, a bigint, or a decimal string such as '10.50'; got ${typeof amount === "string" ? JSON.stringify(amount) : String(amount)}.`);
512
+ }
513
+ //#endregion
469
514
  //#region src/where-conditions.ts
470
515
  /**
471
516
  * True when the caller wrote filters and every one of them was `undefined`.
@@ -969,6 +1014,53 @@ async function resolveWithReturning(query) {
969
1014
  row: void 0
970
1015
  };
971
1016
  }
1017
+ /** A string-typed column that still holds a number: `numeric`/`decimal` (unsigned too) and a bigint in string mode. */
1018
+ const NUMERIC_STRING_DETAILS = /* @__PURE__ */ new Set([
1019
+ "numeric",
1020
+ "unumeric",
1021
+ "int64",
1022
+ "uint64"
1023
+ ]);
1024
+ /**
1025
+ * Refuses `column + amount` where SQL would not add: SQLite stores `'one' + 1`
1026
+ * as `1` and `1.5` in an integer column, both without an error. `dataType` is
1027
+ * `number int32`, `number uint32`, `bigint int64`, `string numeric`, `string`,
1028
+ * `boolean`, `object date`, …; a `custom` column is the database's to judge.
1029
+ */
1030
+ function assertAddable(column, field, amount) {
1031
+ const dataType = column.dataType;
1032
+ if (typeof dataType !== "string") return;
1033
+ const [kind, detail = ""] = dataType.split(" ");
1034
+ if (kind === "string" ? !NUMERIC_STRING_DETAILS.has(detail) : kind === "boolean" || kind === "object" || kind === "array") throw new TypeError(`DrizzleAdapter: cannot add to "${field}", a ${dataType} column; increment() and decrement() take a numeric column.`);
1035
+ if ((typeof amount === "number" ? !Number.isInteger(amount) : typeof amount === "string" && amount.includes(".")) && /^u?int\d/.test(detail)) throw new TypeError(`DrizzleAdapter: cannot add ${String(amount)} to "${field}", an integer column.`);
1036
+ }
1037
+ /** `String(number)` of a finite number, a bigint, or a decimal string: digits, one point, an exponent. */
1038
+ const NUMERIC_LITERAL = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/;
1039
+ /**
1040
+ * The amount as a SQL literal. A bound amount reaches each driver in its own
1041
+ * encoding: D1 takes no bigint, the Data API sends one as a string, and MySQL
1042
+ * reads a bound string as a double, which a `decimal` column cannot afford.
1043
+ */
1044
+ function amountLiteral(amount) {
1045
+ const literal = String(amount);
1046
+ if (typeof amount === "string" ? !DECIMAL_LITERAL.test(literal) : !NUMERIC_LITERAL.test(literal)) throw new TypeError(`DrizzleAdapter: increment amount ${JSON.stringify(literal)} is not a numeric literal.`);
1047
+ return sql.raw(literal);
1048
+ }
1049
+ /**
1050
+ * Runs an update and counts the rows it changed: the RETURNING rows where the
1051
+ * dialect has them (`column` keeps each one small), else the driver's header,
1052
+ * which mysql2 resolves as `[ResultSetHeader, fields]`.
1053
+ */
1054
+ async function countChangedRows(query, column) {
1055
+ if (typeof query.returning === "function") return (await query.returning({ value: column })).length;
1056
+ const result = await resolveMutation(query);
1057
+ const header = Array.isArray(result) ? result[0] : result;
1058
+ for (const key of ["affectedRows", "rowsAffected"]) {
1059
+ const value = header?.[key];
1060
+ if (typeof value === "number") return value;
1061
+ }
1062
+ throw new Error("DrizzleAdapter: the write ran, but the driver reported no count of the rows it changed.");
1063
+ }
972
1064
  const DrizzleAdapter = {
973
1065
  configure: configureConnection,
974
1066
  getDatabase() {
@@ -1111,6 +1203,17 @@ const DrizzleAdapter = {
1111
1203
  return await resolveMutation(finalQuery);
1112
1204
  });
1113
1205
  },
1206
+ async incrementAdvanced(table, conditions, field, amount, writeOptions) {
1207
+ return connection().run(writeOptions, async (db) => {
1208
+ if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
1209
+ const delta = amountLiteral(amount);
1210
+ const column = resolveColumn(table, field);
1211
+ assertAddable(column, field, amount);
1212
+ const data = { [field]: sql`${column} + ${delta}` };
1213
+ const clause = buildDrizzleConditions(table, conditions);
1214
+ return countChangedRows(clause ? db.update(table).set(data).where(clause) : db.update(table).set(data), column);
1215
+ });
1216
+ },
1114
1217
  async deleteAdvanced(table, conditions, writeOptions) {
1115
1218
  return connection().run(writeOptions, async (db) => {
1116
1219
  if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
@@ -1589,6 +1692,28 @@ var QueryBuilder = class QueryBuilder {
1589
1692
  return adapter.update(this.table, this.simpleWhereFor("update"), payload, { trx: this.options.trx });
1590
1693
  }
1591
1694
  /**
1695
+ * `field = field + amount` in one statement, so concurrent calls lose no
1696
+ * count; resolves to the number of rows changed. Scopes apply as in
1697
+ * `update()`; `fillable`, mutators and hooks do not, since code names the
1698
+ * column. A `NULL` stays `NULL`.
1699
+ */
1700
+ async increment(field, amount) {
1701
+ return this.addToColumn("increment", field, amount);
1702
+ }
1703
+ /**
1704
+ * `increment()` with `amount` subtracted. A condition makes it a guard.
1705
+ * @example await Product.where({ id }).where('stock', '>=', 2).decrement('stock', 2) // 0: not enough stock
1706
+ */
1707
+ async decrement(field, amount) {
1708
+ return this.addToColumn("decrement", field, amount);
1709
+ }
1710
+ async addToColumn(method, field, amount) {
1711
+ const signed = signedAmount(`${this.modelClass.name}.${method}`, amount === void 0 ? 1 : amount, method === "decrement");
1712
+ const adapter = this.assertWritable("update");
1713
+ if (typeof adapter.incrementAdvanced !== "function") throw new Error(`${this.modelClass.name}: ${method}() needs an adapter that implements incrementAdvanced.`);
1714
+ return adapter.incrementAdvanced(this.table, this.effectiveConditions(), field, signed, { trx: this.options.trx });
1715
+ }
1716
+ /**
1592
1717
  * The object-where a basic adapter takes; a condition the flat object cannot
1593
1718
  * carry (an OR group, an operator, two values on one field) refuses rather
1594
1719
  * than writing with it dropped.
@@ -1787,6 +1912,112 @@ function serializeRecord(record, options) {
1787
1912
  function serializeRecords(records, options) {
1788
1913
  return records.map((r) => serializeRecord(r, options));
1789
1914
  }
1915
+ /**
1916
+ * Filters the relation rows on `serialized` (a copy `serializeRecord` made of
1917
+ * `source`) by each related model's own `hidden`/`visible`, at every depth.
1918
+ * Only keys present on the rows are visited; untouched values keep their
1919
+ * references, and no input is written to.
1920
+ */
1921
+ function serializeLoadedRelations(model, source, serialized, walk) {
1922
+ const definitions = model[RELATION_DEFINITIONS]();
1923
+ if (definitions.size === 0) return serialized;
1924
+ for (const key in serialized) {
1925
+ const definition = definitions.get(key);
1926
+ if (definition === void 0) continue;
1927
+ const value = serialized[key];
1928
+ const filtered = filterRelationValue(relatedModelOf(definition, source, value, walk.morphMap), value, walk);
1929
+ if (filtered !== value) serialized[key] = filtered;
1930
+ }
1931
+ return serialized;
1932
+ }
1933
+ /**
1934
+ * The related model; an asynchronous reference no load has resolved yields
1935
+ * `undefined`. A morphTo target is the model its load
1936
+ * resolved, since the holder's casts or accessors may rewrite the type column
1937
+ * afterwards; a row no load tagged falls back to that column.
1938
+ */
1939
+ function relatedModelOf(definition, holder, value, morphMap) {
1940
+ if (definition.type !== "morphTo") return knownModelReference(definition.related);
1941
+ const loaded = knownMorphTarget(value);
1942
+ if (loaded) return loaded;
1943
+ const type = holder[`${definition.morphName}Type`];
1944
+ return typeof type === "string" && morphMap && Object.hasOwn(morphMap, type) ? morphMap[type] : void 0;
1945
+ }
1946
+ function hasColumnFilter(model) {
1947
+ return (model.visible?.length ?? 0) > 0 || (model.hidden?.length ?? 0) > 0;
1948
+ }
1949
+ function isRow(value) {
1950
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1951
+ }
1952
+ function holdsRelation(definitions, row) {
1953
+ for (const key in row) if (definitions.has(key)) return true;
1954
+ return false;
1955
+ }
1956
+ function filterRelationValue(model, value, walk) {
1957
+ if (!model || value === null || typeof value !== "object") return value;
1958
+ const definitions = model[RELATION_DEFINITIONS]();
1959
+ const filtered = hasColumnFilter(model);
1960
+ if (!filtered && definitions.size === 0) return value;
1961
+ if (!Array.isArray(value)) return isRow(value) ? filterRow(model, definitions, filtered, value, walk) : value;
1962
+ let copy;
1963
+ for (let i = 0; i < value.length; i++) {
1964
+ const item = value[i];
1965
+ const next = isRow(item) ? filterRow(model, definitions, filtered, item, walk) : item;
1966
+ if (copy) copy.push(next);
1967
+ else if (next !== item) {
1968
+ copy = value.slice(0, i);
1969
+ copy.push(next);
1970
+ }
1971
+ }
1972
+ return copy ?? value;
1973
+ }
1974
+ function filterRow(model, definitions, filtered, row, walk) {
1975
+ if (!filtered && !holdsRelation(definitions, row)) return row;
1976
+ walk.memo ??= /* @__PURE__ */ new Map();
1977
+ let rows = walk.memo.get(model);
1978
+ if (!rows) {
1979
+ rows = /* @__PURE__ */ new Map();
1980
+ walk.memo.set(model, rows);
1981
+ }
1982
+ const seen = rows.get(row);
1983
+ if (seen) {
1984
+ if (!seen.done && seen.output === row) seen.output = { ...row };
1985
+ return seen.output;
1986
+ }
1987
+ const entry = {
1988
+ output: filtered ? filterColumns(model, row) : row,
1989
+ done: false
1990
+ };
1991
+ rows.set(row, entry);
1992
+ for (const key in entry.output) {
1993
+ const definition = definitions.get(key);
1994
+ if (definition === void 0) continue;
1995
+ const value = row[key];
1996
+ const next = filterRelationValue(relatedModelOf(definition, row, value, walk.morphMap), value, walk);
1997
+ if (next === value) continue;
1998
+ if (entry.output === row) entry.output = { ...row };
1999
+ entry.output[key] = next;
2000
+ }
2001
+ entry.done = true;
2002
+ return entry.output;
2003
+ }
2004
+ /**
2005
+ * A related row's own columns, by the rule `serializeRecord` applies to the
2006
+ * serialized record: `visible` keeps only the keys it names (relations
2007
+ * included), in loaded order; otherwise `hidden` keys go. Appends are not computed.
2008
+ */
2009
+ function filterColumns(model, row) {
2010
+ const hidden = model.hidden;
2011
+ const visible = model.visible;
2012
+ const kept = {};
2013
+ if (visible && visible.length > 0) {
2014
+ for (const key in row) if (visible.includes(key)) kept[key] = row[key];
2015
+ return kept;
2016
+ }
2017
+ if (!hidden?.some((key) => key in row)) return row;
2018
+ for (const key in row) if (!hidden.includes(key)) kept[key] = row[key];
2019
+ return kept;
2020
+ }
1790
2021
  //#endregion
1791
2022
  //#region src/MassAssignmentException.ts
1792
2023
  /**
@@ -1973,22 +2204,32 @@ var Model = class Model {
1973
2204
  if (!everyFilterDropped(where)) return;
1974
2205
  throw new Error(`${this.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
1975
2206
  }
1976
- /** Applies hidden/visible filtering, accessors and appends. */
2207
+ /**
2208
+ * Applies hidden/visible filtering, accessors and appends, then each loaded
2209
+ * relation's own model's hidden/visible to its rows, nested ones included.
2210
+ */
1977
2211
  static serialize(record) {
1978
- return serializeRecord(record, {
2212
+ const serialized = serializeRecord(record, {
1979
2213
  hidden: this.hidden,
1980
2214
  visible: this.visible,
1981
2215
  appends: this.appends,
1982
2216
  accessors: this.accessors
1983
2217
  });
2218
+ return serializeLoadedRelations(this, record, serialized, { morphMap: Model.morphMap });
1984
2219
  }
1985
2220
  static serializeMany(records) {
1986
- return serializeRecords(records, {
2221
+ const options = {
1987
2222
  hidden: this.hidden,
1988
2223
  visible: this.visible,
1989
2224
  appends: this.appends,
1990
2225
  accessors: this.accessors
1991
- });
2226
+ };
2227
+ const walk = { morphMap: Model.morphMap };
2228
+ return records.map((record) => serializeLoadedRelations(this, record, serializeRecord(record, options), walk));
2229
+ }
2230
+ /** @internal The serializer's view of the relations, symbol-keyed like `[READ_TRANSFORMS]`. */
2231
+ static [RELATION_DEFINITIONS]() {
2232
+ return this.getRelationDefinitions();
1992
2233
  }
1993
2234
  static applyCasts(record) {
1994
2235
  const castDefs = this.casts;
@@ -2123,21 +2364,28 @@ var Model = class Model {
2123
2364
  return record;
2124
2365
  }
2125
2366
  static async findWith(id, relations, key, queryOptions) {
2126
- const record = await this.find(id, key, queryOptions);
2127
- if (record == null) return null;
2128
2367
  const relationList = normalizeRelations(relations);
2129
- if (relationList.length === 0) return record;
2368
+ return relationList.length === 0 ? await this.find(id, key, queryOptions) : await this.findRawWith(id, relationList, key, queryOptions);
2369
+ }
2370
+ /**
2371
+ * `find()` with its relations loaded ahead of the read transforms: a loader
2372
+ * matches rows on raw key values, which a cast or an accessor on this model
2373
+ * would have rewritten.
2374
+ */
2375
+ static async findRawWith(id, relationList, key = "id", queryOptions) {
2376
+ if (id === void 0) return null;
2377
+ const where = { [key]: id };
2378
+ if (this.hasScopes()) return this.newQuery(queryOptions).where(where).with(...relationList).first();
2379
+ const record = await this.getAdapter().findUnique(this.resolveTable(), where, queryOptions);
2380
+ if (record == null) return null;
2130
2381
  const copy = { ...record };
2131
2382
  await this.loadRelationsInto([copy], relationList, queryOptions);
2132
- return copy;
2383
+ return this.applyReadTransforms(copy);
2133
2384
  }
2134
2385
  static async findWithOrFail(id, relations, key, queryOptions) {
2135
- const record = await this.findOrFail(id, key, queryOptions);
2136
- const relationList = normalizeRelations(relations);
2137
- if (relationList.length === 0) return record;
2138
- const copy = { ...record };
2139
- await this.loadRelationsInto([copy], relationList, queryOptions);
2140
- return copy;
2386
+ const record = await this.findWith(id, relations, key, queryOptions);
2387
+ if (record == null) throw new ModelNotFoundException(this.name, id, key ?? "id");
2388
+ return record;
2141
2389
  }
2142
2390
  static async first(where, queryOptions) {
2143
2391
  if (everyFilterDropped(where)) return null;
@@ -2405,6 +2653,14 @@ var Model = class Model {
2405
2653
  await lifecycle.after(result);
2406
2654
  return this.applyReadTransforms(result);
2407
2655
  }
2656
+ /** `QueryBuilder.increment()` for the rows matching `where`; fires no model events. */
2657
+ static async increment(where, field, amount, writeOptions) {
2658
+ return this.newQuery(writeOptions).where(where).increment(field, amount);
2659
+ }
2660
+ /** `increment()` with `amount` subtracted. */
2661
+ static async decrement(where, field, amount, writeOptions) {
2662
+ return this.newQuery(writeOptions).where(where).decrement(field, amount);
2663
+ }
2408
2664
  static async delete(where, writeOptions) {
2409
2665
  if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
2410
2666
  return this[LIFECYCLE_DELETE](where, "delete", () => this.newQuery(writeOptions).where(where).delete());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.15.0",
3
+ "version": "2.16.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",