@forestfuture/active-record 0.8.0 → 0.8.2

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.
@@ -207,37 +207,6 @@ interface QuerySql {
207
207
  sql: string;
208
208
  params: unknown[];
209
209
  }
210
- /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
211
- interface CollectionMethods<M extends Model> {
212
- /**
213
- * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
214
- * together, resolving to `false`, with nothing written, if one can't be saved.
215
- */
216
- push(...records: M[]): Promise<boolean>;
217
- /**
218
- * Removes records from the association by its `dependent:` strategy, as Rails' collection
219
- * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
220
- * otherwise sets their foreign key to NULL. Resolves to the records.
221
- */
222
- delete(...records: M[]): Promise<M[]>;
223
- /**
224
- * Destroys records of the association, callbacks and dependents included, whatever its
225
- * `dependent:` is, in one write: if one refuses, it throws `RecordNotDestroyed` and nothing
226
- * is destroyed. Resolves to the records.
227
- */
228
- destroy(...records: M[]): Promise<M[]>;
229
- /**
230
- * Removes every record of the association as `deleteAll()` does, by its `dependent:`, and
231
- * forgets the records built through it: afterwards it reads as empty without a query.
232
- */
233
- clear(): Promise<void>;
234
- /**
235
- * Destroys every record of the association, callbacks and dependents included, whatever its
236
- * `dependent:` is, in one write, as `destroy` does; then it reads as empty without a query.
237
- * Resolves to the records.
238
- */
239
- destroyAll(): Promise<M[]>;
240
- }
241
210
  /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
242
211
  interface InspectOptions {
243
212
  depth?: number | null;
@@ -316,6 +285,160 @@ type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
316
285
  direction: OrderDirection;
317
286
  nulls?: NullsPlacement;
318
287
  }; };
288
+ /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
289
+ interface CollectionMethods<M extends Model> {
290
+ /**
291
+ * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
292
+ * together, resolving to `false`, with nothing written, if one can't be saved.
293
+ */
294
+ push(...records: M[]): Promise<boolean>;
295
+ /**
296
+ * Removes records from the association by its `dependent:` strategy, as Rails' collection
297
+ * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
298
+ * otherwise sets their foreign key to NULL. Resolves to the records.
299
+ */
300
+ delete(...records: M[]): Promise<M[]>;
301
+ /**
302
+ * Destroys records of the association, callbacks and dependents included, whatever its
303
+ * `dependent:` is, in one write: if one refuses, it throws `RecordNotDestroyed` and nothing
304
+ * is destroyed. Resolves to the records.
305
+ */
306
+ destroy(...records: M[]): Promise<M[]>;
307
+ /**
308
+ * Removes every record of the association as `deleteAll()` does, by its `dependent:`, and
309
+ * forgets the records built through it: afterwards it reads as empty without a query.
310
+ */
311
+ clear(): Promise<void>;
312
+ /**
313
+ * Destroys every record of the association, callbacks and dependents included, whatever its
314
+ * `dependent:` is, in one write, as `destroy` does; then it reads as empty without a query.
315
+ * Resolves to the records.
316
+ */
317
+ destroyAll(): Promise<M[]>;
318
+ }
319
+ /**
320
+ * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
321
+ * the target's Relation, with its scopes, and returns a narrowed one.
322
+ */
323
+ type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
324
+ /** What an association declaration takes: the keys that link the Models, and a scope. */
325
+ interface AssociationOptions<C extends ModelClass = ModelClass> {
326
+ /**
327
+ * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
328
+ * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
329
+ * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
330
+ */
331
+ foreignKey?: string;
332
+ /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
333
+ primaryKey?: string;
334
+ /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
335
+ scope?: AssociationScope<C>;
336
+ /** What destroying the owner does to this association's records (hasMany and hasOne). */
337
+ dependent?: Dependent;
338
+ /**
339
+ * Saving the owner also saves this association's loaded records that changed, and destroys
340
+ * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
341
+ */
342
+ autosave?: true;
343
+ /**
344
+ * The target's association that points back (#62), whose record is this one, so records loaded
345
+ * or built through either side point at each other without a query: a hasMany's or hasOne's
346
+ * belongsTo, or a belongsTo's hasOne. Inferred when left out; `false` turns it off.
347
+ */
348
+ inverseOf?: string | false;
349
+ }
350
+ /**
351
+ * What an association through another takes (#59): `projects = hasMany(Project, { through:
352
+ * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
353
+ * join records (`ThroughDependent`).
354
+ */
355
+ interface ThroughOptions<C extends ModelClass = ModelClass> {
356
+ /** The owner's association it reaches its records through: one to the join Model. */
357
+ through: string;
358
+ /**
359
+ * The association of the `through` association's Model that reaches the records. Left out, it's
360
+ * the one named as this association, singular or plural (`projects` → `project`, `projects`).
361
+ */
362
+ source?: string;
363
+ /** Narrows or orders its records: `(q) => q.order(…)`. */
364
+ scope?: AssociationScope<C>;
365
+ }
366
+ /**
367
+ * What destroying the owner, and removing records with `delete`, do to a hasMany through
368
+ * another's join records (#434): destroy them, callbacks included, or delete their rows.
369
+ */
370
+ type ThroughDependent = "destroy" | "deleteAll";
371
+ /** Rails' `dependent:` strategies for a hasMany. */
372
+ type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
373
+ /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
374
+ type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
375
+ type Dependent = HasManyDependent | HasOneDependent;
376
+ /**
377
+ * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
378
+ * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
379
+ */
380
+ interface BelongsTo<C extends ModelClass> {
381
+ (): Promise<InstanceType<C> | null>;
382
+ set(record: InstanceType<C> | null): void;
383
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
384
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
385
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
386
+ }
387
+ /**
388
+ * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
389
+ * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
390
+ * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
391
+ * known.
392
+ */
393
+ interface PolymorphicBelongsTo<C extends ModelClass> {
394
+ (): Promise<InstanceType<C> | null>;
395
+ set(record: InstanceType<C> | null): void;
396
+ }
397
+ /**
398
+ * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
399
+ * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
400
+ * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
401
+ * old record, removed by `dependent:` when the new one is written.
402
+ */
403
+ interface HasOne<C extends ModelClass> {
404
+ (): Promise<InstanceType<C> | null>;
405
+ set(record: InstanceType<C> | null): Promise<void>;
406
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
407
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
408
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
409
+ }
410
+ /**
411
+ * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
412
+ * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
413
+ */
414
+ type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
415
+ /**
416
+ * `note.tags()` for an association through another (#59): a Relation of its records, which
417
+ * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
418
+ * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
419
+ * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
420
+ * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
421
+ */
422
+ type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
423
+ /** The writes a through association's own Relation refuses (#434): they make no join records. */
424
+ type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
425
+ /**
426
+ * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
427
+ * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
428
+ */
429
+ interface HasOneThrough<C extends ModelClass> {
430
+ (): Promise<InstanceType<C> | null>;
431
+ /**
432
+ * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
433
+ * through the association it goes through; `null` destroys the join record.
434
+ */
435
+ set(record: InstanceType<C> | null): Promise<void>;
436
+ /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
437
+ readonly [throughTarget]: C;
438
+ }
439
+ declare const throughTarget: unique symbol;
440
+ /** What a hasMany accessor returns: its Relation, with the collection methods. */
441
+ type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
319
442
  /** One statement's result, the same on every database. */
320
443
  interface StatementResult {
321
444
  /** The rows it returned: a read's, or a write's `RETURNING`. */
@@ -462,6 +585,45 @@ declare class GroupedRelation<M extends Model, G extends readonly GroupTerm<M>[]
462
585
  calculate(operation: "average", attribute: NumberAttribute<M> | SafeSql): Promise<Map<GroupKey<M, G>, number | null>>;
463
586
  calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<Map<GroupKey<M, G>, CalculatedValue<M, K, unknown> | null>>;
464
587
  }
588
+ /** What `touch` and `touchAll` take after the attributes they name: the `time` to set. */
589
+ interface TouchOptions {
590
+ /** The time to set, now by default. */
591
+ time?: Date;
592
+ }
593
+ /** `touch`'s arguments on record type `R`: its datetime attributes' names, then its options. */
594
+ type TouchArguments<R> = DatetimeAttributeKey<R>[] | [...DatetimeAttributeKey<R>[], TouchOptions];
595
+ /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
596
+ interface PageOptions {
597
+ /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
598
+ page?: number | string | null;
599
+ /** Records on a page, a number or text as `page` is. */
600
+ perPage?: number | string | null;
601
+ /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
602
+ count?: boolean;
603
+ }
604
+ /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
605
+ interface CountlessPage<M extends Model> {
606
+ records: M[];
607
+ page: number;
608
+ perPage: number;
609
+ hasNext: boolean;
610
+ hasPrevious: boolean;
611
+ }
612
+ /** A page of records, from `paginate()`, with the total it's a page of. */
613
+ interface Page<M extends Model> extends CountlessPage<M> {
614
+ total: number;
615
+ totalPages: number;
616
+ }
617
+ /** `paginate` as a static of every Model, typed for the class it's called on. */
618
+ interface PaginateStatic {
619
+ <C extends QueryableClass>(this: C, options: PageOptions & {
620
+ count: false;
621
+ }): Promise<CountlessPage<InstanceType<C>>>;
622
+ <C extends QueryableClass>(this: C, options?: PageOptions & {
623
+ count?: true;
624
+ }): Promise<Page<InstanceType<C>>>;
625
+ <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
626
+ }
465
627
  /** What `findEach`, `findInBatches` and `inBatches` take. */
466
628
  interface IterationOptions {
467
629
  /** Records in each batch: each is one query. 1000 by default. */
@@ -608,6 +770,12 @@ declare class Relation<M extends Model, S = {}> {
608
770
  * Rails. A `none()` Relation sends nothing and resolves to 0.
609
771
  */
610
772
  updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
773
+ /**
774
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
775
+ * Relation matches, in one statement, as Rails' `touch_all` (#50). Resolves to the number of
776
+ * rows; skips what `updateAll` skips.
777
+ */
778
+ touchAll(...args: TouchArguments<M>): Promise<number>;
611
779
  /**
612
780
  * Adds to number attributes in every row this Relation matches, now, in one statement:
613
781
  * `updateCounters({ viewCount: 1 })` sets `view_count = COALESCE(view_count, 0) + 1`, so
@@ -776,154 +944,10 @@ declare class Relation<M extends Model, S = {}> {
776
944
  toArray(): Promise<M[]>;
777
945
  }
778
946
  /**
779
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
780
- * the target's Relation, with its scopes, and returns a narrowed one.
781
- */
782
- type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
783
- /** What an association declaration takes: the keys that link the Models, and a scope. */
784
- interface AssociationOptions<C extends ModelClass = ModelClass> {
785
- /**
786
- * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
787
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
788
- * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
789
- */
790
- foreignKey?: string;
791
- /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
792
- primaryKey?: string;
793
- /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
794
- scope?: AssociationScope<C>;
795
- /** What destroying the owner does to this association's records (hasMany and hasOne). */
796
- dependent?: Dependent;
797
- /**
798
- * Saving the owner also saves this association's loaded records that changed, and destroys
799
- * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
800
- */
801
- autosave?: true;
802
- }
803
- /**
804
- * What an association through another takes (#59): `projects = hasMany(Project, { through:
805
- * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
806
- * join records (`ThroughDependent`).
807
- */
808
- interface ThroughOptions<C extends ModelClass = ModelClass> {
809
- /** The owner's association it reaches its records through: one to the join Model. */
810
- through: string;
811
- /**
812
- * The association of the `through` association's Model that reaches the records. Left out, it's
813
- * the one named as this association, singular or plural (`projects` → `project`, `projects`).
814
- */
815
- source?: string;
816
- /** Narrows or orders its records: `(q) => q.order(…)`. */
817
- scope?: AssociationScope<C>;
818
- }
819
- /**
820
- * What destroying the owner, and removing records with `delete`, do to a hasMany through
821
- * another's join records (#434): destroy them, callbacks included, or delete their rows.
822
- */
823
- type ThroughDependent = "destroy" | "deleteAll";
824
- /** Rails' `dependent:` strategies for a hasMany. */
825
- type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
826
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
827
- type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
828
- type Dependent = HasManyDependent | HasOneDependent;
829
- /**
830
- * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
831
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
832
- */
833
- interface BelongsTo<C extends ModelClass> {
834
- (): Promise<InstanceType<C> | null>;
835
- set(record: InstanceType<C> | null): void;
836
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
837
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
838
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
839
- }
840
- /**
841
- * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
842
- * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
843
- * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
844
- * known.
845
- */
846
- interface PolymorphicBelongsTo<C extends ModelClass> {
847
- (): Promise<InstanceType<C> | null>;
848
- set(record: InstanceType<C> | null): void;
849
- }
850
- /**
851
- * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
852
- * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
853
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
854
- * old record, removed by `dependent:` when the new one is written.
855
- */
856
- interface HasOne<C extends ModelClass> {
857
- (): Promise<InstanceType<C> | null>;
858
- set(record: InstanceType<C> | null): Promise<void>;
859
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
860
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
861
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
862
- }
863
- /**
864
- * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
865
- * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
947
+ * An around callback: `next` runs the rest of the write, resolving once the record's write is kept
948
+ * and its inner callbacks have run.
866
949
  */
867
- type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
868
- /**
869
- * `note.tags()` for an association through another (#59): a Relation of its records, which
870
- * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
871
- * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
872
- * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
873
- * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
874
- */
875
- type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
876
- /** The writes a through association's own Relation refuses (#434): they make no join records. */
877
- type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
878
- /**
879
- * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
880
- * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
881
- */
882
- interface HasOneThrough<C extends ModelClass> {
883
- (): Promise<InstanceType<C> | null>;
884
- /**
885
- * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
886
- * through the association it goes through; `null` destroys the join record.
887
- */
888
- set(record: InstanceType<C> | null): Promise<void>;
889
- /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
890
- readonly [throughTarget]: C;
891
- }
892
- declare const throughTarget: unique symbol;
893
- /** What a hasMany accessor returns: its Relation, with the collection methods. */
894
- type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
895
- /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
896
- interface PageOptions {
897
- /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
898
- page?: number | string | null;
899
- /** Records on a page, a number or text as `page` is. */
900
- perPage?: number | string | null;
901
- /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
902
- count?: boolean;
903
- }
904
- /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
905
- interface CountlessPage<M extends Model> {
906
- records: M[];
907
- page: number;
908
- perPage: number;
909
- hasNext: boolean;
910
- hasPrevious: boolean;
911
- }
912
- /** A page of records, from `paginate()`, with the total it's a page of. */
913
- interface Page<M extends Model> extends CountlessPage<M> {
914
- total: number;
915
- totalPages: number;
916
- }
917
- /** `paginate` as a static of every Model, typed for the class it's called on. */
918
- interface PaginateStatic {
919
- <C extends QueryableClass>(this: C, options: PageOptions & {
920
- count: false;
921
- }): Promise<CountlessPage<InstanceType<C>>>;
922
- <C extends QueryableClass>(this: C, options?: PageOptions & {
923
- count?: true;
924
- }): Promise<Page<InstanceType<C>>>;
925
- <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
926
- }
950
+ type AroundCallback<R> = (record: R, next: () => Promise<void>) => unknown;
927
951
  /** A validation context: `"create"`, `"update"`, or a name the app chooses (`"signup"`). */
928
952
  type ValidationContext = "create" | "update" | (string & {});
929
953
  /** One context, or several: of those `X` names, when it's a Model's. */
@@ -948,7 +972,7 @@ interface SaveOptions {
948
972
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
949
973
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
950
974
  /** 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"];
975
+ 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
976
  /** A Relation method with no overloads, by name. */
953
977
  type RelationMethod = (typeof relationMethods)[number];
954
978
  /**
@@ -1041,6 +1065,11 @@ type CallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback
1041
1065
  * `this.beforeValidation((record) => …, { on: "create" })`.
1042
1066
  */
1043
1067
  type ValidationCallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback<InstanceType<C>>, options?: ValidationCallbackOptions<ContextOf<C>>) => void;
1068
+ /**
1069
+ * Declares a callback that runs synchronously as a record is loaded or built: nothing awaits it,
1070
+ * so its type refuses one that returns a promise (an `async` one), as running it does.
1071
+ */
1072
+ type SyncCallbackStatic = <C extends AbstractModelClass>(this: C, callback: (record: InstanceType<C>) => string | number | bigint | boolean | symbol | null | undefined) => void;
1044
1073
  /** Every callback kind as a static, each documented here, so its doc comment shows on hover. */
1045
1074
  interface CallbackStatics {
1046
1075
  /**
@@ -1069,11 +1098,40 @@ interface CallbackStatics {
1069
1098
  beforeDestroy: CallbackStatic;
1070
1099
  /** Runs after the row was deleted; the record is already destroyed. */
1071
1100
  afterDestroy: CallbackStatic;
1101
+ /** Runs after `touch()` wrote the record's timestamps (#50); no save callback runs for it. */
1102
+ afterTouch: CallbackStatic;
1072
1103
  /**
1073
1104
  * Runs when the database refused the record's save or destroy (a constraint, or another write in
1074
1105
  * its batch). Not for a validation failure or an `abort()`: nothing was sent then.
1075
1106
  */
1076
1107
  afterRollback: CallbackStatic;
1108
+ /**
1109
+ * Runs as a record is loaded from a row (#49): by a query, an association read, a preload or
1110
+ * `reload`, before `afterInitialize`. Synchronous: one that returns a promise throws `TypeError`.
1111
+ */
1112
+ afterFind: SyncCallbackStatic;
1113
+ /**
1114
+ * Runs as a record is built (after `build`'s `init`) or loaded (after `afterFind`) (#49).
1115
+ * Synchronous: one that returns a promise throws `TypeError`.
1116
+ */
1117
+ afterInitialize: SyncCallbackStatic;
1118
+ }
1119
+ /** An around callback static (#48): `this.aroundSave(async (record, next) => { …; await next(); … })`. */
1120
+ type AroundCallbackStatic = <C extends AbstractModelClass>(this: C, callback: AroundCallback<InstanceType<C>>) => void;
1121
+ /** The around callbacks as statics: each wraps the rest of a save or destroy (#48). */
1122
+ interface AroundStatics {
1123
+ /**
1124
+ * Wraps a save, after `beforeSave`: `await next()` runs `beforeCreate` or `beforeUpdate`, the
1125
+ * write, and `afterCreate` or `afterUpdate`; `afterSave` runs once it's finished. One that
1126
+ * doesn't call `next()` stops the save, as `abort()` does.
1127
+ */
1128
+ aroundSave: AroundCallbackStatic;
1129
+ /** Wraps a create, after `beforeCreate`: `await next()` runs the INSERT; then `afterCreate`. */
1130
+ aroundCreate: AroundCallbackStatic;
1131
+ /** Wraps an update, after `beforeUpdate`: `await next()` runs the UPDATE; then `afterUpdate`. */
1132
+ aroundUpdate: AroundCallbackStatic;
1133
+ /** Wraps a destroy, after `beforeDestroy`: `await next()` runs the DELETE; then `afterDestroy`. */
1134
+ aroundDestroy: AroundCallbackStatic;
1077
1135
  }
1078
1136
  /** The commit callbacks as statics: each runs after every after-callback of its write. */
1079
1137
  interface CommitStatics {
@@ -1093,7 +1151,7 @@ interface CommitStatics {
1093
1151
  * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1094
1152
  * can't take.
1095
1153
  */
1096
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & CommitStatics;
1154
+ declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & CommitStatics;
1097
1155
  /**
1098
1156
  * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1099
1157
  * `"custom"` for a custom type, given bare or as `{ type }`.
@@ -1112,7 +1170,7 @@ type AttributeKeyOf<R, T> = { [K in keyof SpecsOf<R>]: SpecsOf<R>[K] extends {
1112
1170
  type AttributeKey$1<R> = keyof AttributesOf<R> & string;
1113
1171
  /** A record's number attributes, which `increment` and `decrement` take. */
1114
1172
  type NumberAttributeKey<R> = AttributeKeyOf<R, "integer" | "real">;
1115
- /** A record's datetime attributes, which a counter's `touch` names (#61). */
1173
+ /** A record's datetime attributes, which `touch` (#50) and a counter's `touch` (#61) name. */
1116
1174
  type DatetimeAttributeKey<R> = AttributeKeyOf<R, "datetime">;
1117
1175
  /** A record's boolean attributes, which `toggle` takes. */
1118
1176
  type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
@@ -1138,12 +1196,19 @@ declare abstract class AttributeWrites extends ModelStatics {
1138
1196
  /**
1139
1197
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1140
1198
  * 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.
1199
+ * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
1200
+ * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
1201
+ * the record holds them (#50). Resolves to whether there was a row to write.
1143
1202
  */
1144
- incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1203
+ incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1145
1204
  /** `incrementColumn`, taking `by` away. */
1146
- decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): Promise<boolean>;
1205
+ decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1206
+ /**
1207
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1208
+ * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1209
+ * was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
1210
+ */
1211
+ touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1147
1212
  /**
1148
1213
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1149
1214
  * validation or callback, unlike Rails' `toggle!`, which runs the save callbacks.
@@ -1625,6 +1690,12 @@ declare class Model extends AttributeWrites {
1625
1690
  * names; none by default. `attributes()` still has them (#101).
1626
1691
  */
1627
1692
  static hiddenAttributes: readonly string[];
1693
+ /**
1694
+ * Runs `fn` with this Model's records not touched, nor those of the Models extending it
1695
+ * (`Model.noTouching` covers every Model), as Rails' `no_touching`: a belongsTo's `touch`
1696
+ * leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.
1697
+ */
1698
+ static noTouching<R>(fn: () => R | Promise<R>): Promise<R>;
1628
1699
  /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
1629
1700
  static humanAttributeName(attribute: string): string;
1630
1701
  /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
@@ -1777,7 +1848,9 @@ declare class Model extends AttributeWrites {
1777
1848
  updateOrThrow(attributes: Partial<AttributesOf<this>>): Promise<true>;
1778
1849
  /**
1779
1850
  * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
1780
- * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
1851
+ * A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy`
1852
+ * callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError`
1853
+ * association refused.
1781
1854
  */
1782
1855
  destroy(): Promise<this | false>;
1783
1856
  /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
@@ -1803,6 +1876,12 @@ declare class Model extends AttributeWrites {
1803
1876
  isPersisted(): boolean;
1804
1877
  /** Deleted by this instance; a read-only snapshot of the row. */
1805
1878
  isDestroyed(): boolean;
1879
+ /**
1880
+ * Whether the record has the attribute `name` loaded (Rails' `has_attribute?`): `false` for one
1881
+ * `select(...)` left out, whose read throws `MissingAttribute`, and for a name the Model doesn't
1882
+ * declare. A callback that runs for partial records, such as `afterFind`, checks it first.
1883
+ */
1884
+ hasAttribute(name: string): boolean;
1806
1885
  /** The record's attributes as a plain object of JavaScript values. */
1807
1886
  attributes(): Record<string, unknown>;
1808
1887
  /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
@@ -1993,4 +2072,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
1993
2072
  }
1994
2073
  /** The options of a `validatesAssociated(association, options)` call. */
1995
2074
  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 };
2075
+ export { ReturnedRow as $, databaseExecutor as A, QuerySql as At, ValidationContext as B, ComparisonBound as Bt, QueryEvent as C, gt as Ct, SchemaAdapter as D, QueryPart as Dt, ConstraintFailure as E, lte as Et, RecordStatement as F, ColumnValue as Ft, Scoped as G, Relation as H, DatetimeAttributeKey as I, SafeSql as It, Page as J, IterationOptions as K, NumberAttributeKey as L, column as Lt, BatchResults as M, valueMark as Mt, batch as N, Attribute as Nt, AnyDatabase as O, InOrderOfOptions as Ot, Batch as P, ColumnReference as Pt, Init as Q, SaveOptions as R, sql$1 as Rt, DatabaseExecutor as S, between as St, Adapter as T, lt as Tt, Scope as U, ValidationContexts as V, ComparisonOptions as Vt, ScopeMethods as W, TouchOptions as X, PageOptions as Y, GroupedRelation as Z, TableSchema as _, InsertOptions as _t, ValidationOptions as a, BelongsTo as at, boundValue as b, UpsertOptions as bt, AttributeErrorMessages as c, HasManyDependent as ct, RestrictMessages as d, HasOneDependent as dt, Statement as et, Model as f, HasOneThrough as ft, DatabaseSchema as g, Conditions as gt, TableAttributes as h, ThroughOptions as ht, UniquenessOptions as i, AssociationOptions as it, BatchEntry as j, Dialect as jt, RelationsFor as k, CompiledSql as kt, ErrorMessage as l, HasManyThrough as lt, ScopeStatic as m, ThroughDependent as mt, LengthOptions as n, Driver as nt, Errors as o, HasMany as ot, ModelClass as p, PolymorphicBelongsTo as pt, CountlessPage as q, NumericalityOptions as r, StatementResult as rt, ValidationError as s, HasManyCollection as st, AssociatedValidationOptions as t, WriteResult as tt, ErrorMessages as u, HasOne as ut, TableSchemas as v, OrderSpec as vt, QueryListener as w, gte as wt, AttributeConversions as x, Comparison as xt, FilterAttribute as y, Returning as yt, ValidationCallbackOptions as z, Comparable as zt };