@forestfuture/active-record 0.8.0 → 0.8.1

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.
@@ -117,7 +117,8 @@ var RecordNotSaved = class extends ActiveRecordError {
117
117
  };
118
118
  /**
119
119
  * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
120
- * `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
120
+ * `afterDestroy`, `afterTouch`). That's a mistake: the write already succeeded and nothing rolls
121
+ * back.
121
122
  */
122
123
  var AbortAfterPersistence = class extends ActiveRecordError {
123
124
  name = "AbortAfterPersistence";
@@ -264,6 +265,82 @@ function pluralize(word) {
264
265
  function singularize(word) {
265
266
  return inflect(word, SINGULARS);
266
267
  }
268
+ // src/binary-values.ts
269
+ /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
270
+ function castBinary(value) {
271
+ if (value instanceof Uint8Array) return value;
272
+ return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
273
+ }
274
+ /**
275
+ * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
276
+ * a `bytea` as a `Buffer`.
277
+ */
278
+ function readBinary(cell) {
279
+ if (cell instanceof Uint8Array) return Uint8Array.from(cell);
280
+ return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
281
+ }
282
+ /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
283
+ function isSameCell(a, b) {
284
+ if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
285
+ return a.length === b.length && a.every((byte, index) => byte === b[index]);
286
+ }
287
+ /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
288
+ const digitCodes = new TextEncoder().encode("0123456789abcdef");
289
+ const decoder = new TextDecoder();
290
+ /**
291
+ * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
292
+ * digits' character codes are written into one array and decoded once: mapping each byte to a
293
+ * string of its own takes many times the memory and time, which a large file can't afford.
294
+ */
295
+ function hexOf(bytes) {
296
+ const text = new Uint8Array(bytes.length * 2);
297
+ for (let index = 0; index < bytes.length; index++) {
298
+ const byte = bytes[index];
299
+ text[index * 2] = digitCodes[byte >> 4];
300
+ text[index * 2 + 1] = digitCodes[byte & 15];
301
+ }
302
+ return decoder.decode(text);
303
+ }
304
+ // src/calendar-values.ts
305
+ /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
306
+ const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
307
+ /**
308
+ * Text naming a day that exists (`"2026-01-02"`), as it is; anything else, a `Date` included
309
+ * (its day depends on the time zone), is `uncastable`. Each database returns a day as this text.
310
+ */
311
+ function castDay(value) {
312
+ if (typeof value !== "string") return uncastable;
313
+ const match = dayText.exec(value);
314
+ if (match === null) return uncastable;
315
+ const [, year, month, day] = match.map(Number);
316
+ const date = /* @__PURE__ */ new Date(0);
317
+ date.setUTCFullYear(year, month - 1, day);
318
+ return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? value : uncastable;
319
+ }
320
+ /** A time of day: hours and minutes, then optionally seconds and up to six digits of a fraction. */
321
+ const timeText = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?$/;
322
+ /** The end of a day, which Postgres's `time` holds as `24:00:00`, with no time past it. */
323
+ const endOfDay = /^24:00(?::00(?:\.0{1,6})?)?$/;
324
+ /**
325
+ * Text naming a time of day (`"09:30"`, `"09:30:15.5"`) in its one form, as Postgres writes a
326
+ * `time`: seconds always, a fraction without trailing zeros (`"09:30:00"`, `"09:30:15.5"`). The
327
+ * end of the day is `"24:00:00"`. Anything else, a `Date` included, is `uncastable`.
328
+ */
329
+ function castTime(value) {
330
+ if (typeof value !== "string") return uncastable;
331
+ if (endOfDay.test(value)) return "24:00:00";
332
+ const match = timeText.exec(value);
333
+ if (match === null) return uncastable;
334
+ const [, hours, minutes, seconds = "00", fraction = ""] = match;
335
+ const digits = withoutTrailingZeros(fraction);
336
+ return `${hours}:${minutes}:${seconds}${digits === "" ? "" : `.${digits}`}`;
337
+ }
338
+ /** `digits` without the zeros it ends with, found by a loop rather than an unanchored `0+$`. */
339
+ function withoutTrailingZeros(digits) {
340
+ let end = digits.length;
341
+ while (digits[end - 1] === "0") end--;
342
+ return digits.slice(0, end);
343
+ }
267
344
  // src/enum-values.ts
268
345
  /** Whether `value` is an enum's values: a list of names, or an object of names and stored values. */
269
346
  function isEnumValues(value) {
@@ -344,89 +421,6 @@ function enumValuesOf(model, attribute) {
344
421
  if (values === void 0) throw new UnknownAttribute(`${model.name} has no enum attribute "${attribute}"`);
345
422
  return mappingOf(values);
346
423
  }
347
- // src/identifiers.ts
348
- /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
349
- function isIdentifier(name) {
350
- return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
351
- }
352
- /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
353
- const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
354
- // src/binary-values.ts
355
- /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
356
- function castBinary(value) {
357
- if (value instanceof Uint8Array) return value;
358
- return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
359
- }
360
- /**
361
- * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
362
- * a `bytea` as a `Buffer`.
363
- */
364
- function readBinary(cell) {
365
- if (cell instanceof Uint8Array) return Uint8Array.from(cell);
366
- return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
367
- }
368
- /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
369
- function isSameCell(a, b) {
370
- if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
371
- return a.length === b.length && a.every((byte, index) => byte === b[index]);
372
- }
373
- /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
374
- const digitCodes = new TextEncoder().encode("0123456789abcdef");
375
- const decoder = new TextDecoder();
376
- /**
377
- * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
378
- * digits' character codes are written into one array and decoded once: mapping each byte to a
379
- * string of its own takes many times the memory and time, which a large file can't afford.
380
- */
381
- function hexOf(bytes) {
382
- const text = new Uint8Array(bytes.length * 2);
383
- for (let index = 0; index < bytes.length; index++) {
384
- const byte = bytes[index];
385
- text[index * 2] = digitCodes[byte >> 4];
386
- text[index * 2 + 1] = digitCodes[byte & 15];
387
- }
388
- return decoder.decode(text);
389
- }
390
- // src/calendar-values.ts
391
- /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
392
- const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
393
- /**
394
- * Text naming a day that exists (`"2026-01-02"`), as it is; anything else, a `Date` included
395
- * (its day depends on the time zone), is `uncastable`. Each database returns a day as this text.
396
- */
397
- function castDay(value) {
398
- if (typeof value !== "string") return uncastable;
399
- const match = dayText.exec(value);
400
- if (match === null) return uncastable;
401
- const [, year, month, day] = match.map(Number);
402
- const date = /* @__PURE__ */ new Date(0);
403
- date.setUTCFullYear(year, month - 1, day);
404
- return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? value : uncastable;
405
- }
406
- /** A time of day: hours and minutes, then optionally seconds and up to six digits of a fraction. */
407
- const timeText = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?$/;
408
- /** The end of a day, which Postgres's `time` holds as `24:00:00`, with no time past it. */
409
- const endOfDay = /^24:00(?::00(?:\.0{1,6})?)?$/;
410
- /**
411
- * Text naming a time of day (`"09:30"`, `"09:30:15.5"`) in its one form, as Postgres writes a
412
- * `time`: seconds always, a fraction without trailing zeros (`"09:30:00"`, `"09:30:15.5"`). The
413
- * end of the day is `"24:00:00"`. Anything else, a `Date` included, is `uncastable`.
414
- */
415
- function castTime(value) {
416
- if (typeof value !== "string") return uncastable;
417
- if (endOfDay.test(value)) return "24:00:00";
418
- const match = timeText.exec(value);
419
- if (match === null) return uncastable;
420
- const [, hours, minutes, seconds = "00", fraction = ""] = match;
421
- const digits = withoutTrailingZeros(fraction);
422
- return `${hours}:${minutes}:${seconds}${digits === "" ? "" : `.${digits}`}`;
423
- }
424
- /** `digits` without the zeros it ends with, found by a loop rather than an unanchored `0+$`. */
425
- function withoutTrailingZeros(digits) {
426
- let end = digits.length;
427
- while (digits[end - 1] === "0") end--;
428
- return digits.slice(0, end);
429
- }
430
424
  // src/conversion.ts
431
425
  /** A value that can't be read as the attribute's type. */
432
426
  const uncastable = Symbol("uncastable");
@@ -985,4 +979,11 @@ function incremented(digits) {
985
979
  // src/epoch-storage.ts
986
980
  /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
987
981
  const epochStorages = ["unixSeconds", "unixMilliseconds"];
988
- export { abort as $, CallbackAbort as A, NotNullViolation as B, pluralize as C, AbortAfterPersistence as D, underscore as E, InvalidForeignKey as F, RecordNotFound as G, RecordDestroyed as H, InvalidModel as I, SoleRecordExceeded as J, RecordNotSaved as K, IrreversibleOrder as L, ConstraintViolation as M, DeleteRestriction as N, ActiveRecordError as O, IncompatibleRelation as P, UnknownModelName as Q, MissingAttribute as R, listedNames as S, camelize as T, RecordInvalid as U, ReadonlyAssociation as V, RecordNotDestroyed as W, UnknownAssociation as X, StrictValidationFailed as Y, UnknownAttribute as Z, enumEntries as _, castKey as a, enumValuesOf as b, readValue as c, writeValue as d, zonelessDateTime as f, reservedWords as g, isIdentifier as h, castCondition as i, CheckViolation as j, AssociationNotLoaded as k, uncastable as l, isSameCell as m, digitsProblem as n, castValue as o, hexOf as p, RecordNotUnique as q, orderDecimal as r, isInvalidDate as s, epochStorages as t, writeUntypedValue as u, enumProblem as v, singularize as w, isEnumValues as x, enumValidations as y, NoDatabase as z };
982
+ // src/identifiers.ts
983
+ /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
984
+ function isIdentifier(name) {
985
+ return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
986
+ }
987
+ /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
988
+ const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
989
+ export { abort as $, CallbackAbort as A, NotNullViolation as B, pluralize as C, AbortAfterPersistence as D, underscore as E, InvalidForeignKey as F, RecordNotFound as G, RecordDestroyed as H, InvalidModel as I, SoleRecordExceeded as J, RecordNotSaved as K, IrreversibleOrder as L, ConstraintViolation as M, DeleteRestriction as N, ActiveRecordError as O, IncompatibleRelation as P, UnknownModelName as Q, MissingAttribute as R, isSameCell as S, camelize as T, RecordInvalid as U, ReadonlyAssociation as V, RecordNotDestroyed as W, UnknownAssociation as X, StrictValidationFailed as Y, UnknownAttribute as Z, enumValidations as _, orderDecimal as a, listedNames as b, castValue as c, uncastable as d, writeUntypedValue as f, enumProblem as g, enumEntries as h, digitsProblem as i, CheckViolation as j, AssociationNotLoaded as k, isInvalidDate as l, zonelessDateTime as m, reservedWords as n, castCondition as o, writeValue as p, RecordNotUnique as q, epochStorages as r, castKey as s, isIdentifier as t, readValue as u, enumValuesOf as v, singularize as w, hexOf as x, isEnumValues as y, NoDatabase as z };
@@ -1,4 +1,4 @@
1
- import { $ as PolymorphicBelongsTo, G as BelongsTo, I as NumberAttributeKey, J as HasManyDependent, K as HasMany, O as AnyDatabase, Q as HasOneThrough, W as AssociationOptions, X as HasOne, Y as HasManyThrough, Z as HasOneDependent, et as ThroughDependent, f as Model, g as DatabaseSchema, p as ModelClass, tt as ThroughOptions } from "./validations-DHDVV8hB.mjs";
1
+ import { $ as PolymorphicBelongsTo, G as BelongsTo, I as NumberAttributeKey, J as HasManyDependent, K as HasMany, O as AnyDatabase, Q as HasOneThrough, W as AssociationOptions, X as HasOne, Y as HasManyThrough, Z as HasOneDependent, et as ThroughDependent, f as Model, g as DatabaseSchema, p as ModelClass, tt as ThroughOptions } from "./validations-BSZ5gVeI.mjs";
2
2
  /** One of the attributes of `C`'s records, which a counter cache names. */
3
3
  type CounterName<C extends ModelClass> = NumberAttributeKey<InstanceType<C>>;
4
4
  /** What only a belongsTo takes; `C` is its target, whose attribute a counter cache names. */
@@ -180,13 +180,14 @@ declare class RecordNotSaved extends ActiveRecordError {
180
180
  }
181
181
  /**
182
182
  * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
183
- * `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
183
+ * `afterDestroy`, `afterTouch`). That's a mistake: the write already succeeded and nothing rolls
184
+ * back.
184
185
  */
185
186
  declare class AbortAfterPersistence extends ActiveRecordError {
186
187
  name: string;
187
188
  readonly callback: string;
188
189
  readonly reason: string;
189
- constructor(callback: string, lifecycle: "save" | "destroy", abortion: CallbackAbort);
190
+ constructor(callback: string, lifecycle: "save" | "destroy" | "touch", abortion: CallbackAbort);
190
191
  }
191
192
  /**
192
193
  * A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)` or a
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { _ as defineType, a as AttributeType, g as CustomType, i as AttributeSpecs, l as EpochStorage, r as AttributeSpec } from "./metadata-CzntpYzC.mjs";
2
- import { $ as PolymorphicBelongsTo, B as ValidationContexts, C as QueryEvent, Ct as lt, Et as InOrderOfOptions, F as RecordStatement, Ft as column, G as BelongsTo, H as Page, It as sql, J as HasManyDependent, K as HasMany, L as SaveOptions, Lt as Comparable, M as BatchResults, Mt as ColumnReference, N as batch, Nt as ColumnValue, Ot as QuerySql, P as Batch, Pt as SafeSql, Q as HasOneThrough, R as ValidationCallbackOptions, Rt as ComparisonBound, St as gte, Tt as QueryPart, U as PageOptions, V as CountlessPage, W as AssociationOptions, X as HasOne, Y as HasManyThrough, Z as HasOneDependent, _ as TableSchema, _t as Returning, a as ValidationOptions, at as Scoped, bt as between, c as AttributeErrorMessages, ct as Init, d as RestrictMessages, dt as WriteResult, et as ThroughDependent, f as Model, g as DatabaseSchema, gt as OrderSpec, h as TableAttributes, ht as InsertOptions, i as UniquenessOptions, it as ScopeMethods, j as BatchEntry, k as RelationsFor, l as ErrorMessage, lt as ReturnedRow, m as ScopeStatic, mt as Conditions, n as LengthOptions, nt as Relation, o as Errors, ot as IterationOptions, q as HasManyCollection, r as NumericalityOptions, rt as Scope, s as ValidationError, st as GroupedRelation, t as AssociatedValidationOptions, tt as ThroughOptions, u as ErrorMessages, ut as Statement, v as TableSchemas, vt as UpsertOptions, w as QueryListener, wt as lte, x as AttributeConversions, xt as gt, y as FilterAttribute, yt as Comparison, z as ValidationContext, zt as ComparisonOptions } from "./validations-DHDVV8hB.mjs";
3
- import { A as PolymorphicBelongsToOptions, C as RecordNotUnique, D as UnknownAttribute, E as UnknownAssociation, M as hasMany, N as hasOne, O as UnknownModelName, S as RecordNotSaved, T as StrictValidationFailed, _ as ReadonlyAssociation, a as AssociationNotLoaded, b as RecordNotDestroyed, c as ConstraintViolation, d as InvalidForeignKey, f as InvalidModel, g as NotNullViolation, h as NoDatabase, i as ActiveRecordError, j as belongsTo, k as abort, l as DeleteRestriction, m as MissingAttribute, n as withDatabase, o as CallbackAbort, p as IrreversibleOrder, r as AbortAfterPersistence, s as CheckViolation, t as defineSchema, u as IncompatibleRelation, v as RecordDestroyed, w as SoleRecordExceeded, x as RecordNotFound, y as RecordInvalid } from "./index-BATasvJa.mjs";
4
- export { AbortAfterPersistence, ActiveRecordError, type AssociatedValidationOptions, AssociationNotLoaded, type AssociationOptions, type AttributeConversions, type AttributeErrorMessages, type AttributeSpec, type AttributeSpecs, type AttributeType, type Batch, type BatchEntry, type BatchResults, type BelongsTo, CallbackAbort, CheckViolation, type ColumnReference, type ColumnValue, type Comparable, type Comparison, type ComparisonBound, type ComparisonOptions, type Conditions, ConstraintViolation, type CountlessPage, type CustomType, type DatabaseSchema, DeleteRestriction, type EpochStorage, type ErrorMessage, type ErrorMessages, Errors, type FilterAttribute, type GroupedRelation, type HasMany, type HasManyCollection, type HasManyDependent, type HasManyThrough, type HasOne, type HasOneDependent, type HasOneThrough, type InOrderOfOptions, IncompatibleRelation, type Init, type InsertOptions, InvalidForeignKey, InvalidModel, IrreversibleOrder, type IterationOptions, type LengthOptions, MissingAttribute, Model, NoDatabase, NotNullViolation, type NumericalityOptions, type OrderSpec, type Page, type PageOptions, type PolymorphicBelongsTo, type PolymorphicBelongsToOptions, type QueryEvent, type QueryListener, type QueryPart, type QuerySql, ReadonlyAssociation, RecordDestroyed, RecordInvalid, RecordNotDestroyed, RecordNotFound, RecordNotSaved, RecordNotUnique, type RecordStatement, Relation, type RelationsFor, type RestrictMessages, type ReturnedRow, type Returning, type SafeSql, type SaveOptions, type Scope, type ScopeMethods, type ScopeStatic, type Scoped, SoleRecordExceeded, type Statement, StrictValidationFailed, type TableAttributes, type TableSchema, type TableSchemas, type ThroughDependent, type ThroughOptions, type UniquenessOptions, UnknownAssociation, UnknownAttribute, UnknownModelName, type UpsertOptions, type ValidationCallbackOptions, type ValidationContext, type ValidationContexts, type ValidationError, type ValidationOptions, type WriteResult, abort, batch, belongsTo, between, column, defineSchema, defineType, gt, gte, hasMany, hasOne, lt, lte, sql, withDatabase };
2
+ import { $ as PolymorphicBelongsTo, B as ValidationContexts, Bt as ComparisonOptions, C as QueryEvent, Ct as gte, Dt as InOrderOfOptions, Et as QueryPart, F as RecordStatement, Ft as SafeSql, G as BelongsTo, H as Page, It as column, J as HasManyDependent, K as HasMany, L as SaveOptions, Lt as sql, M as BatchResults, N as batch, Nt as ColumnReference, P as Batch, Pt as ColumnValue, Q as HasOneThrough, R as ValidationCallbackOptions, Rt as Comparable, St as gt, Tt as lte, U as PageOptions, V as CountlessPage, W as AssociationOptions, X as HasOne, Y as HasManyThrough, Z as HasOneDependent, _ as TableSchema, _t as OrderSpec, a as ValidationOptions, at as Scoped, bt as Comparison, c as AttributeErrorMessages, ct as GroupedRelation, d as RestrictMessages, dt as Statement, et as ThroughDependent, f as Model, ft as WriteResult, g as DatabaseSchema, gt as InsertOptions, h as TableAttributes, ht as Conditions, i as UniquenessOptions, it as ScopeMethods, j as BatchEntry, k as RelationsFor, kt as QuerySql, l as ErrorMessage, lt as Init, m as ScopeStatic, n as LengthOptions, nt as Relation, o as Errors, ot as IterationOptions, q as HasManyCollection, r as NumericalityOptions, rt as Scope, s as ValidationError, st as TouchOptions, t as AssociatedValidationOptions, tt as ThroughOptions, u as ErrorMessages, ut as ReturnedRow, v as TableSchemas, vt as Returning, w as QueryListener, wt as lt, x as AttributeConversions, xt as between, y as FilterAttribute, yt as UpsertOptions, z as ValidationContext, zt as ComparisonBound } from "./validations-BSZ5gVeI.mjs";
3
+ import { A as PolymorphicBelongsToOptions, C as RecordNotUnique, D as UnknownAttribute, E as UnknownAssociation, M as hasMany, N as hasOne, O as UnknownModelName, S as RecordNotSaved, T as StrictValidationFailed, _ as ReadonlyAssociation, a as AssociationNotLoaded, b as RecordNotDestroyed, c as ConstraintViolation, d as InvalidForeignKey, f as InvalidModel, g as NotNullViolation, h as NoDatabase, i as ActiveRecordError, j as belongsTo, k as abort, l as DeleteRestriction, m as MissingAttribute, n as withDatabase, o as CallbackAbort, p as IrreversibleOrder, r as AbortAfterPersistence, s as CheckViolation, t as defineSchema, u as IncompatibleRelation, v as RecordDestroyed, w as SoleRecordExceeded, x as RecordNotFound, y as RecordInvalid } from "./index-D5getfHx.mjs";
4
+ export { AbortAfterPersistence, ActiveRecordError, type AssociatedValidationOptions, AssociationNotLoaded, type AssociationOptions, type AttributeConversions, type AttributeErrorMessages, type AttributeSpec, type AttributeSpecs, type AttributeType, type Batch, type BatchEntry, type BatchResults, type BelongsTo, CallbackAbort, CheckViolation, type ColumnReference, type ColumnValue, type Comparable, type Comparison, type ComparisonBound, type ComparisonOptions, type Conditions, ConstraintViolation, type CountlessPage, type CustomType, type DatabaseSchema, DeleteRestriction, type EpochStorage, type ErrorMessage, type ErrorMessages, Errors, type FilterAttribute, type GroupedRelation, type HasMany, type HasManyCollection, type HasManyDependent, type HasManyThrough, type HasOne, type HasOneDependent, type HasOneThrough, type InOrderOfOptions, IncompatibleRelation, type Init, type InsertOptions, InvalidForeignKey, InvalidModel, IrreversibleOrder, type IterationOptions, type LengthOptions, MissingAttribute, Model, NoDatabase, NotNullViolation, type NumericalityOptions, type OrderSpec, type Page, type PageOptions, type PolymorphicBelongsTo, type PolymorphicBelongsToOptions, type QueryEvent, type QueryListener, type QueryPart, type QuerySql, ReadonlyAssociation, RecordDestroyed, RecordInvalid, RecordNotDestroyed, RecordNotFound, RecordNotSaved, RecordNotUnique, type RecordStatement, Relation, type RelationsFor, type RestrictMessages, type ReturnedRow, type Returning, type SafeSql, type SaveOptions, type Scope, type ScopeMethods, type ScopeStatic, type Scoped, SoleRecordExceeded, type Statement, StrictValidationFailed, type TableAttributes, type TableSchema, type TableSchemas, type ThroughDependent, type ThroughOptions, type TouchOptions, type UniquenessOptions, UnknownAssociation, UnknownAttribute, UnknownModelName, type UpsertOptions, type ValidationCallbackOptions, type ValidationContext, type ValidationContexts, type ValidationError, type ValidationOptions, type WriteResult, abort, batch, belongsTo, between, column, defineSchema, defineType, gt, gte, hasMany, hasOne, lt, lte, sql, withDatabase };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { $ as abort, A as CallbackAbort, B as NotNullViolation, D as AbortAfterPersistence, F as InvalidForeignKey, G as RecordNotFound, H as RecordDestroyed, I as InvalidModel, J as SoleRecordExceeded, K as RecordNotSaved, L as IrreversibleOrder, M as ConstraintViolation, N as DeleteRestriction, O as ActiveRecordError, P as IncompatibleRelation, Q as UnknownModelName, R as MissingAttribute, U as RecordInvalid, V as ReadonlyAssociation, W as RecordNotDestroyed, X as UnknownAssociation, Y as StrictValidationFailed, Z as UnknownAttribute, j as CheckViolation, k as AssociationNotLoaded, q as RecordNotUnique, z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
2
- import { _ as lte, b as hasOne, c as Relation, d as sql, g as lt, h as gte, m as gt, n as Model, p as between, r as withDatabase, t as batch, u as column, v as belongsTo, y as hasMany } from "./batch-ReqVoCfa.mjs";
3
- import { U as defineType, f as Errors } from "./generated-model-g5oWsDKE.mjs";
4
- import { t as defineSchema } from "./src-D56_3odT.mjs";
1
+ import { $ as abort, A as CallbackAbort, B as NotNullViolation, D as AbortAfterPersistence, F as InvalidForeignKey, G as RecordNotFound, H as RecordDestroyed, I as InvalidModel, J as SoleRecordExceeded, K as RecordNotSaved, L as IrreversibleOrder, M as ConstraintViolation, N as DeleteRestriction, O as ActiveRecordError, P as IncompatibleRelation, Q as UnknownModelName, R as MissingAttribute, U as RecordInvalid, V as ReadonlyAssociation, W as RecordNotDestroyed, X as UnknownAssociation, Y as StrictValidationFailed, Z as UnknownAttribute, j as CheckViolation, k as AssociationNotLoaded, q as RecordNotUnique, z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
2
+ import { b as hasOne, c as Relation, d as between, f as gt, h as lte, i as withDatabase, l as column, m as lt, p as gte, r as Model, t as batch, u as sql, v as belongsTo, y as hasMany } from "./batch-Ms5p9lKq.mjs";
3
+ import { g as Errors, z as defineType } from "./generated-model-DJA8vmNE.mjs";
4
+ import { t as defineSchema } from "./src-BAVZKQ7J.mjs";
5
5
  export { AbortAfterPersistence, ActiveRecordError, AssociationNotLoaded, CallbackAbort, CheckViolation, ConstraintViolation, DeleteRestriction, Errors, IncompatibleRelation, InvalidForeignKey, InvalidModel, IrreversibleOrder, MissingAttribute, Model, NoDatabase, NotNullViolation, ReadonlyAssociation, RecordDestroyed, RecordInvalid, RecordNotDestroyed, RecordNotFound, RecordNotSaved, RecordNotUnique, Relation, SoleRecordExceeded, StrictValidationFailed, UnknownAssociation, UnknownAttribute, UnknownModelName, abort, batch, belongsTo, between, column, defineSchema, defineType, gt, gte, hasMany, hasOne, lt, lte, sql, withDatabase };
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-n4w1cS_M.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-DhNV1mWf.mjs";
3
- import { E as underscore } from "./epoch-storage-CDlQZcBB.mjs";
1
+ import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
+ import { E as underscore } from "./identifiers-Dh5DFACX.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-n4w1cS_M.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-DhNV1mWf.mjs";
3
- import { E as underscore } from "./epoch-storage-CDlQZcBB.mjs";
1
+ import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
+ import { E as underscore } from "./identifiers-Dh5DFACX.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, readFileSync, readdirSync } from "node:fs";
6
6
  import { basename, dirname, join } from "node:path";
@@ -1,4 +1,4 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-DHDVV8hB.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-BSZ5gVeI.mjs";
2
2
  import pg from "pg";
3
3
  /** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
4
4
  export declare function postgresql({ binding }: {
@@ -1,7 +1,7 @@
1
- import { a as databaseExecutor, i as AnyDatabase, l as DatabaseExecutor } from "./batch-ReqVoCfa.mjs";
2
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-CfXMGeOu.mjs";
3
- import { z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
4
- import { M as boundValue } from "./generated-model-g5oWsDKE.mjs";
1
+ import { a as AnyDatabase, g as DatabaseExecutor, o as databaseExecutor } from "./batch-Ms5p9lKq.mjs";
2
+ import { n as onlyRequested, t as workersEnv } from "./for-adapters-C-MQxaIx.mjs";
3
+ import { z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
4
+ import { U as boundValue } from "./generated-model-DJA8vmNE.mjs";
5
5
  import pg from "pg";
6
6
  // src/adapters/postgresql/connect-timeout.ts
7
7
  /** The limit when the connection string sets none, in milliseconds. */
@@ -1,5 +1,5 @@
1
- import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-ReqVoCfa.mjs";
2
- import { $ as modelNameOf, et as ownValueSetter, ot as ancestors, st as staticBelow } from "./generated-model-g5oWsDKE.mjs";
1
+ import { n as readyModel, r as Model, s as isReservedScopeName } from "./batch-Ms5p9lKq.mjs";
2
+ import { $ as modelNameOf, et as ownValueSetter, ot as ancestors, st as staticBelow } from "./generated-model-DJA8vmNE.mjs";
3
3
  // src/define-schema.ts
4
4
  const listed = /* @__PURE__ */ new Set();
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { E as underscore, T as camelize, g as reservedWords, l as uncastable, o as castValue, t as epochStorages } from "./epoch-storage-CDlQZcBB.mjs";
1
+ import { E as underscore, T as camelize, c as castValue, d as uncastable, n as reservedWords, r as epochStorages } from "./identifiers-Dh5DFACX.mjs";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  // cli/project/paths.ts
@@ -462,6 +462,13 @@ declare class GroupedRelation<M extends Model, G extends readonly GroupTerm<M>[]
462
462
  calculate(operation: "average", attribute: NumberAttribute<M> | SafeSql): Promise<Map<GroupKey<M, G>, number | null>>;
463
463
  calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K, unknown> | null>>;
464
464
  }
465
+ /** What `touch` and `touchAll` take after the attributes they name: the `time` to set. */
466
+ interface TouchOptions {
467
+ /** The time to set, now by default. */
468
+ time?: Date;
469
+ }
470
+ /** `touch`'s arguments on record type `R`: its datetime attributes' names, then its options. */
471
+ type TouchArguments<R> = DatetimeAttributeKey<R>[] | [...DatetimeAttributeKey<R>[], TouchOptions];
465
472
  /** What `findEach`, `findInBatches` and `inBatches` take. */
466
473
  interface IterationOptions {
467
474
  /** Records in each batch: each is one query. 1000 by default. */
@@ -608,6 +615,12 @@ declare class Relation<M extends Model, S = {}> {
608
615
  * Rails. A `none()` Relation sends nothing and resolves to 0.
609
616
  */
610
617
  updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
618
+ /**
619
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
620
+ * Relation matches, in one statement, as Rails' `touch_all` (#50). Resolves to the number of
621
+ * rows; skips what `updateAll` skips.
622
+ */
623
+ touchAll(...args: TouchArguments<M>): Promise<number>;
611
624
  /**
612
625
  * Adds to number attributes in every row this Relation matches, now, in one statement:
613
626
  * `updateCounters({ viewCount: 1 })` sets `view_count = COALESCE(view_count, 0) + 1`, so
@@ -799,6 +812,12 @@ interface AssociationOptions<C extends ModelClass = ModelClass> {
799
812
  * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
800
813
  */
801
814
  autosave?: true;
815
+ /**
816
+ * The target's association that points back (#62), whose record is this one, so records loaded
817
+ * or built through either side point at each other without a query: a hasMany's or hasOne's
818
+ * belongsTo, or a belongsTo's hasOne. Inferred when left out; `false` turns it off.
819
+ */
820
+ inverseOf?: string | false;
802
821
  }
803
822
  /**
804
823
  * What an association through another takes (#59): `projects = hasMany(Project, { through:
@@ -948,7 +967,7 @@ interface SaveOptions {
948
967
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
949
968
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
950
969
  /** The Relation methods every Model has as statics (besides the overloaded ones). */
951
- declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
970
+ declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
952
971
  /** A Relation method with no overloads, by name. */
953
972
  type RelationMethod = (typeof relationMethods)[number];
954
973
  /**
@@ -1069,6 +1088,8 @@ interface CallbackStatics {
1069
1088
  beforeDestroy: CallbackStatic;
1070
1089
  /** Runs after the row was deleted; the record is already destroyed. */
1071
1090
  afterDestroy: CallbackStatic;
1091
+ /** Runs after `touch()` wrote the record's timestamps (#50); no save callback runs for it. */
1092
+ afterTouch: CallbackStatic;
1072
1093
  /**
1073
1094
  * Runs when the database refused the record's save or destroy (a constraint, or another write in
1074
1095
  * its batch). Not for a validation failure or an `abort()`: nothing was sent then.
@@ -1112,7 +1133,7 @@ type AttributeKeyOf<R, T> = { [K in keyof SpecsOf<R>]: SpecsOf<R>[K] extends {
1112
1133
  type AttributeKey$1<R> = keyof AttributesOf<R> & string;
1113
1134
  /** A record's number attributes, which `increment` and `decrement` take. */
1114
1135
  type NumberAttributeKey<R> = AttributeKeyOf<R, "integer" | "real">;
1115
- /** A record's datetime attributes, which a counter's `touch` names (#61). */
1136
+ /** A record's datetime attributes, which `touch` (#50) and a counter's `touch` (#61) name. */
1116
1137
  type DatetimeAttributeKey<R> = AttributeKeyOf<R, "datetime">;
1117
1138
  /** A record's boolean attributes, which `toggle` takes. */
1118
1139
  type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
@@ -1138,12 +1159,19 @@ declare abstract class AttributeWrites extends ModelStatics {
1138
1159
  /**
1139
1160
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1140
1161
  * writes all count, with no validation, callback or `updatedAt`; the record then holds the
1141
- * row's new value. An unsaved change to it is added too, as Rails' `increment!`. Resolves to
1142
- * whether there was a row to write.
1162
+ * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
1163
+ * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
1164
+ * the record holds them (#50). Resolves to whether there was a row to write.
1143
1165
  */
1144
- incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1166
+ incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1145
1167
  /** `incrementColumn`, taking `by` away. */
1146
- decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1168
+ decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1169
+ /**
1170
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1171
+ * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1172
+ * was a row to write.
1173
+ */
1174
+ touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1147
1175
  /**
1148
1176
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1149
1177
  * validation or callback, unlike Rails' `toggle!`, which runs the save callbacks.
@@ -1993,4 +2021,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
1993
2021
  }
1994
2022
  /** The options of a `validatesAssociated(association, options)` call. */
1995
2023
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
1996
- export { PolymorphicBelongsTo as $, databaseExecutor as A, valueMark as At, ValidationContexts as B, QueryEvent as C, lt as Ct, SchemaAdapter as D, CompiledSql as Dt, ConstraintFailure as E, InOrderOfOptions as Et, RecordStatement as F, column as Ft, BelongsTo as G, Page as H, NumberAttributeKey as I, sql$1 as It, HasManyDependent as J, HasMany as K, SaveOptions as L, Comparable as Lt, BatchResults as M, ColumnReference as Mt, batch as N, ColumnValue as Nt, AnyDatabase as O, QuerySql as Ot, Batch as P, SafeSql as Pt, HasOneThrough as Q, ValidationCallbackOptions as R, ComparisonBound as Rt, DatabaseExecutor as S, gte as St, Adapter as T, QueryPart as Tt, PageOptions as U, CountlessPage as V, AssociationOptions as W, HasOne as X, HasManyThrough as Y, HasOneDependent as Z, TableSchema as _, Returning as _t, ValidationOptions as a, Scoped as at, boundValue as b, between as bt, AttributeErrorMessages as c, Init as ct, RestrictMessages as d, WriteResult as dt, ThroughDependent as et, Model as f, Driver as ft, DatabaseSchema as g, OrderSpec as gt, TableAttributes as h, InsertOptions as ht, UniquenessOptions as i, ScopeMethods as it, BatchEntry as j, Attribute as jt, RelationsFor as k, Dialect as kt, ErrorMessage as l, ReturnedRow as lt, ScopeStatic as m, Conditions as mt, LengthOptions as n, Relation as nt, Errors as o, IterationOptions as ot, ModelClass as p, StatementResult as pt, HasManyCollection as q, NumericalityOptions as r, Scope as rt, ValidationError as s, GroupedRelation as st, AssociatedValidationOptions as t, ThroughOptions as tt, ErrorMessages as u, Statement as ut, TableSchemas as v, UpsertOptions as vt, QueryListener as w, lte as wt, AttributeConversions as x, gt as xt, FilterAttribute as y, Comparison as yt, ValidationContext as z, ComparisonOptions as zt };
2024
+ export { PolymorphicBelongsTo as $, databaseExecutor as A, Dialect as At, ValidationContexts as B, ComparisonOptions as Bt, QueryEvent as C, gte as Ct, SchemaAdapter as D, InOrderOfOptions as Dt, ConstraintFailure as E, QueryPart as Et, RecordStatement as F, SafeSql as Ft, BelongsTo as G, Page as H, NumberAttributeKey as I, column as It, HasManyDependent as J, HasMany as K, SaveOptions as L, sql$1 as Lt, BatchResults as M, Attribute as Mt, batch as N, ColumnReference as Nt, AnyDatabase as O, CompiledSql as Ot, Batch as P, ColumnValue as Pt, HasOneThrough as Q, ValidationCallbackOptions as R, Comparable as Rt, DatabaseExecutor as S, gt as St, Adapter as T, lte as Tt, PageOptions as U, CountlessPage as V, AssociationOptions as W, HasOne as X, HasManyThrough as Y, HasOneDependent as Z, TableSchema as _, OrderSpec as _t, ValidationOptions as a, Scoped as at, boundValue as b, Comparison as bt, AttributeErrorMessages as c, GroupedRelation as ct, RestrictMessages as d, Statement as dt, ThroughDependent as et, Model as f, WriteResult as ft, DatabaseSchema as g, InsertOptions as gt, TableAttributes as h, Conditions as ht, UniquenessOptions as i, ScopeMethods as it, BatchEntry as j, valueMark as jt, RelationsFor as k, QuerySql as kt, ErrorMessage as l, Init as lt, ScopeStatic as m, StatementResult as mt, LengthOptions as n, Relation as nt, Errors as o, IterationOptions as ot, ModelClass as p, Driver as pt, HasManyCollection as q, NumericalityOptions as r, Scope as rt, ValidationError as s, TouchOptions as st, AssociatedValidationOptions as t, ThroughOptions as tt, ErrorMessages as u, ReturnedRow as ut, TableSchemas as v, Returning as vt, QueryListener as w, lt as wt, AttributeConversions as x, between as xt, FilterAttribute as y, UpsertOptions as yt, ValidationContext as z, ComparisonBound as zt };