@forestfuture/active-record 0.8.1 → 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`. */
@@ -469,6 +592,38 @@ interface TouchOptions {
469
592
  }
470
593
  /** `touch`'s arguments on record type `R`: its datetime attributes' names, then its options. */
471
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
+ }
472
627
  /** What `findEach`, `findInBatches` and `inBatches` take. */
473
628
  interface IterationOptions {
474
629
  /** Records in each batch: each is one query. 1000 by default. */
@@ -789,160 +944,10 @@ declare class Relation<M extends Model, S = {}> {
789
944
  toArray(): Promise<M[]>;
790
945
  }
791
946
  /**
792
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
793
- * the target's Relation, with its scopes, and returns a narrowed one.
794
- */
795
- type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
796
- /** What an association declaration takes: the keys that link the Models, and a scope. */
797
- interface AssociationOptions<C extends ModelClass = ModelClass> {
798
- /**
799
- * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
800
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
801
- * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
802
- */
803
- foreignKey?: string;
804
- /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
805
- primaryKey?: string;
806
- /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
807
- scope?: AssociationScope<C>;
808
- /** What destroying the owner does to this association's records (hasMany and hasOne). */
809
- dependent?: Dependent;
810
- /**
811
- * Saving the owner also saves this association's loaded records that changed, and destroys
812
- * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
813
- */
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;
821
- }
822
- /**
823
- * What an association through another takes (#59): `projects = hasMany(Project, { through:
824
- * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
825
- * join records (`ThroughDependent`).
826
- */
827
- interface ThroughOptions<C extends ModelClass = ModelClass> {
828
- /** The owner's association it reaches its records through: one to the join Model. */
829
- through: string;
830
- /**
831
- * The association of the `through` association's Model that reaches the records. Left out, it's
832
- * the one named as this association, singular or plural (`projects` → `project`, `projects`).
833
- */
834
- source?: string;
835
- /** Narrows or orders its records: `(q) => q.order(…)`. */
836
- scope?: AssociationScope<C>;
837
- }
838
- /**
839
- * What destroying the owner, and removing records with `delete`, do to a hasMany through
840
- * another's join records (#434): destroy them, callbacks included, or delete their rows.
841
- */
842
- type ThroughDependent = "destroy" | "deleteAll";
843
- /** Rails' `dependent:` strategies for a hasMany. */
844
- type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
845
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
846
- type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
847
- type Dependent = HasManyDependent | HasOneDependent;
848
- /**
849
- * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
850
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
851
- */
852
- interface BelongsTo<C extends ModelClass> {
853
- (): Promise<InstanceType<C> | null>;
854
- set(record: InstanceType<C> | null): void;
855
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
856
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
857
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
858
- }
859
- /**
860
- * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
861
- * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
862
- * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
863
- * known.
864
- */
865
- interface PolymorphicBelongsTo<C extends ModelClass> {
866
- (): Promise<InstanceType<C> | null>;
867
- set(record: InstanceType<C> | null): void;
868
- }
869
- /**
870
- * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
871
- * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
872
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
873
- * old record, removed by `dependent:` when the new one is written.
874
- */
875
- interface HasOne<C extends ModelClass> {
876
- (): Promise<InstanceType<C> | null>;
877
- set(record: InstanceType<C> | null): Promise<void>;
878
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
879
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
880
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
881
- }
882
- /**
883
- * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
884
- * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
885
- */
886
- type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
887
- /**
888
- * `note.tags()` for an association through another (#59): a Relation of its records, which
889
- * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
890
- * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
891
- * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
892
- * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
893
- */
894
- type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
895
- /** The writes a through association's own Relation refuses (#434): they make no join records. */
896
- type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
897
- /**
898
- * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
899
- * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
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.
900
949
  */
901
- interface HasOneThrough<C extends ModelClass> {
902
- (): Promise<InstanceType<C> | null>;
903
- /**
904
- * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
905
- * through the association it goes through; `null` destroys the join record.
906
- */
907
- set(record: InstanceType<C> | null): Promise<void>;
908
- /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
909
- readonly [throughTarget]: C;
910
- }
911
- declare const throughTarget: unique symbol;
912
- /** What a hasMany accessor returns: its Relation, with the collection methods. */
913
- type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
914
- /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
915
- interface PageOptions {
916
- /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
917
- page?: number | string | null;
918
- /** Records on a page, a number or text as `page` is. */
919
- perPage?: number | string | null;
920
- /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
921
- count?: boolean;
922
- }
923
- /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
924
- interface CountlessPage<M extends Model> {
925
- records: M[];
926
- page: number;
927
- perPage: number;
928
- hasNext: boolean;
929
- hasPrevious: boolean;
930
- }
931
- /** A page of records, from `paginate()`, with the total it's a page of. */
932
- interface Page<M extends Model> extends CountlessPage<M> {
933
- total: number;
934
- totalPages: number;
935
- }
936
- /** `paginate` as a static of every Model, typed for the class it's called on. */
937
- interface PaginateStatic {
938
- <C extends QueryableClass>(this: C, options: PageOptions & {
939
- count: false;
940
- }): Promise<CountlessPage<InstanceType<C>>>;
941
- <C extends QueryableClass>(this: C, options?: PageOptions & {
942
- count?: true;
943
- }): Promise<Page<InstanceType<C>>>;
944
- <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
945
- }
950
+ type AroundCallback<R> = (record: R, next: () => Promise<void>) => unknown;
946
951
  /** A validation context: `"create"`, `"update"`, or a name the app chooses (`"signup"`). */
947
952
  type ValidationContext = "create" | "update" | (string & {});
948
953
  /** One context, or several: of those `X` names, when it's a Model's. */
@@ -1060,6 +1065,11 @@ type CallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback
1060
1065
  * `this.beforeValidation((record) => …, { on: "create" })`.
1061
1066
  */
1062
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;
1063
1073
  /** Every callback kind as a static, each documented here, so its doc comment shows on hover. */
1064
1074
  interface CallbackStatics {
1065
1075
  /**
@@ -1095,6 +1105,33 @@ interface CallbackStatics {
1095
1105
  * its batch). Not for a validation failure or an `abort()`: nothing was sent then.
1096
1106
  */
1097
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;
1098
1135
  }
1099
1136
  /** The commit callbacks as statics: each runs after every after-callback of its write. */
1100
1137
  interface CommitStatics {
@@ -1114,7 +1151,7 @@ interface CommitStatics {
1114
1151
  * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1115
1152
  * can't take.
1116
1153
  */
1117
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & CommitStatics;
1154
+ declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & CommitStatics;
1118
1155
  /**
1119
1156
  * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1120
1157
  * `"custom"` for a custom type, given bare or as `{ type }`.
@@ -1169,7 +1206,7 @@ declare abstract class AttributeWrites extends ModelStatics {
1169
1206
  /**
1170
1207
  * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1171
1208
  * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1172
- * was a row to write.
1209
+ * was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
1173
1210
  */
1174
1211
  touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1175
1212
  /**
@@ -1653,6 +1690,12 @@ declare class Model extends AttributeWrites {
1653
1690
  * names; none by default. `attributes()` still has them (#101).
1654
1691
  */
1655
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>;
1656
1699
  /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
1657
1700
  static humanAttributeName(attribute: string): string;
1658
1701
  /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
@@ -1805,7 +1848,9 @@ declare class Model extends AttributeWrites {
1805
1848
  updateOrThrow(attributes: Partial<AttributesOf<this>>): Promise<true>;
1806
1849
  /**
1807
1850
  * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
1808
- * 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.
1809
1854
  */
1810
1855
  destroy(): Promise<this | false>;
1811
1856
  /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
@@ -1831,6 +1876,12 @@ declare class Model extends AttributeWrites {
1831
1876
  isPersisted(): boolean;
1832
1877
  /** Deleted by this instance; a read-only snapshot of the row. */
1833
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;
1834
1885
  /** The record's attributes as a plain object of JavaScript values. */
1835
1886
  attributes(): Record<string, unknown>;
1836
1887
  /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
@@ -2021,4 +2072,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2021
2072
  }
2022
2073
  /** The options of a `validatesAssociated(association, options)` call. */
2023
2074
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
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 };
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 };