@forestfuture/active-record 0.9.0 → 0.9.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.
- package/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-Ca1JtVcK.mjs → batch-DpMoy3-7.mjs} +830 -698
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +5 -5
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +4 -4
- package/dist/{for-adapters-D35a5x3t.mjs → for-adapters-DSVRZL3n.mjs} +2 -2
- package/dist/{for-adapters-DoyXc8Dq.d.mts → for-adapters-GQfwyuMl.d.mts} +1 -1
- package/dist/{for-adapters-Bl6BCiR1.mjs → for-adapters-unqbZQM7.mjs} +1 -1
- package/dist/{generated-model-L4WAqgOZ.mjs → generated-model-CKIciUat.mjs} +37 -3
- package/dist/{identifiers-CzqYL_nC.mjs → identifiers-BP6aRwew.mjs} +38 -1
- package/dist/{index-Fq4gT3c8.d.mts → index-DkWlkGy2.d.mts} +26 -2
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/{metadata-BIUbGJlS.d.mts → metadata-nKZ_6DzA.d.mts} +17 -2
- package/dist/{plugin-BHUP4ssD.mjs → plugin-A93qwqAh.mjs} +3 -3
- package/dist/{plugin-BMAJKgj6.mjs → plugin-CsOOLZkx.mjs} +3 -3
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +4 -4
- package/dist/{src-fYq-nVHE.mjs → src-CB2AUq70.mjs} +2 -2
- package/dist/{storage-override-yF2NT5ST.mjs → storage-override-B7WTiA_U.mjs} +1 -1
- package/dist/{validations-CKPJoSj4.d.mts → validations-C2-HKi1V.d.mts} +80 -60
- package/llms-full.txt +220 -11
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +1 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-
|
|
1
|
+
import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-nKZ_6DzA.mjs";
|
|
2
2
|
/** What `comparison` compares: numbers with numbers, strings with strings, Dates by their time. */
|
|
3
3
|
type Comparable = number | string | Date;
|
|
4
4
|
/** A bound: a value, or a function of the record being validated (`(event) => event.startsAt`). */
|
|
@@ -260,6 +260,58 @@ interface InOrderOfOptions {
|
|
|
260
260
|
/** Keep only the records whose value is in the list (the default); `false` keeps every one, those not in it last. */
|
|
261
261
|
filter?: boolean;
|
|
262
262
|
}
|
|
263
|
+
/** What a signed id is for, and how long it lasts: forever unless given. */
|
|
264
|
+
interface SignedIdOptions {
|
|
265
|
+
/** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
|
|
266
|
+
readonly expiresIn?: Duration;
|
|
267
|
+
/** When it stops finding its record. */
|
|
268
|
+
readonly expiresAt?: Date;
|
|
269
|
+
/** What it's for (`"login"`): `findSigned` finds its record only given the same. */
|
|
270
|
+
readonly purpose?: string;
|
|
271
|
+
}
|
|
272
|
+
/** What `findSigned` takes: the purpose the signed id was made for. */
|
|
273
|
+
interface FindSignedOptions {
|
|
274
|
+
readonly purpose?: string;
|
|
275
|
+
}
|
|
276
|
+
/** The finders by token every Relation has. */
|
|
277
|
+
declare abstract class TokenFinders<M extends Model> {
|
|
278
|
+
#private;
|
|
279
|
+
abstract findBy(conditions: never): Promise<M | null>;
|
|
280
|
+
/**
|
|
281
|
+
* The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
|
|
282
|
+
* the same `purpose` and it hasn't expired, and this Relation matches it; or null.
|
|
283
|
+
*/
|
|
284
|
+
findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
|
|
285
|
+
/** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
|
|
286
|
+
findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
|
|
287
|
+
/**
|
|
288
|
+
* The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
|
|
289
|
+
* Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
|
|
290
|
+
* Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
|
|
291
|
+
*/
|
|
292
|
+
findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
|
|
293
|
+
/**
|
|
294
|
+
* Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
|
|
295
|
+
* `RecordNotFound` when its record is gone or the value it depends on changed.
|
|
296
|
+
*/
|
|
297
|
+
findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
|
|
298
|
+
}
|
|
299
|
+
/** The questions about how many records every Relation has. */
|
|
300
|
+
declare abstract class CountQuestions<M extends Model> extends TokenFinders<M> {
|
|
301
|
+
/**
|
|
302
|
+
* The number of records: a loaded association's (built records included) without a query;
|
|
303
|
+
* otherwise a `COUNT(*)`, plus an association's unsaved built records.
|
|
304
|
+
*/
|
|
305
|
+
size(): Promise<number>;
|
|
306
|
+
/** Whether there are no records: a loaded association answers itself, else `!exists()`. */
|
|
307
|
+
isEmpty(): Promise<boolean>;
|
|
308
|
+
/** Whether there are any records: the opposite of `isEmpty()`. */
|
|
309
|
+
hasAny(): Promise<boolean>;
|
|
310
|
+
/** Whether more than one record matches: one `COUNT` of at most two rows. */
|
|
311
|
+
hasMoreThanOne(): Promise<boolean>;
|
|
312
|
+
/** Whether exactly one record matches: one `COUNT` of at most two rows. */
|
|
313
|
+
hasExactlyOne(): Promise<boolean>;
|
|
314
|
+
}
|
|
263
315
|
/** A part of a query `unscope` drops by name: `unscope("order")`. */
|
|
264
316
|
type QueryPart = Exclude<UnscopedPart, object>;
|
|
265
317
|
/** One attribute's name, or several: what `unscope({ where })` takes. */
|
|
@@ -540,42 +592,6 @@ declare class Statement<Row = never> {
|
|
|
540
592
|
* `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
|
|
541
593
|
*/
|
|
542
594
|
type Init<M> = (record: M) => void | Promise<void>;
|
|
543
|
-
/** What a signed id is for, and how long it lasts: forever unless given. */
|
|
544
|
-
interface SignedIdOptions {
|
|
545
|
-
/** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
|
|
546
|
-
readonly expiresIn?: Duration;
|
|
547
|
-
/** When it stops finding its record. */
|
|
548
|
-
readonly expiresAt?: Date;
|
|
549
|
-
/** What it's for (`"login"`): `findSigned` finds its record only given the same. */
|
|
550
|
-
readonly purpose?: string;
|
|
551
|
-
}
|
|
552
|
-
/** What `findSigned` takes: the purpose the signed id was made for. */
|
|
553
|
-
interface FindSignedOptions {
|
|
554
|
-
readonly purpose?: string;
|
|
555
|
-
}
|
|
556
|
-
/** The finders by token every Relation has. */
|
|
557
|
-
declare abstract class TokenFinders<M extends Model> {
|
|
558
|
-
#private;
|
|
559
|
-
abstract findBy(conditions: never): Promise<M | null>;
|
|
560
|
-
/**
|
|
561
|
-
* The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
|
|
562
|
-
* the same `purpose` and it hasn't expired, and this Relation matches it; or null.
|
|
563
|
-
*/
|
|
564
|
-
findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
|
|
565
|
-
/** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
|
|
566
|
-
findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
|
|
567
|
-
/**
|
|
568
|
-
* The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
|
|
569
|
-
* Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
|
|
570
|
-
* Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
|
|
571
|
-
*/
|
|
572
|
-
findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
|
|
573
|
-
/**
|
|
574
|
-
* Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
|
|
575
|
-
* `RecordNotFound` when its record is gone or the value it depends on changed.
|
|
576
|
-
*/
|
|
577
|
-
findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
|
|
578
|
-
}
|
|
579
595
|
/** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
|
|
580
596
|
type AttributeList<M extends Model> = readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]];
|
|
581
597
|
/** The types a sum or an average takes; a custom type stored as one of them too. */
|
|
@@ -717,7 +733,7 @@ type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: n
|
|
|
717
733
|
/** A Relation of Model records `M` with the Model's scope methods `S`. */
|
|
718
734
|
type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
|
|
719
735
|
/** A lazy, immutable description of a query against one Model. */
|
|
720
|
-
declare class Relation<M extends Model, S = {}> extends
|
|
736
|
+
declare class Relation<M extends Model, S = {}> extends CountQuestions<M> {
|
|
721
737
|
#private;
|
|
722
738
|
/** Type-only: the Model's scopes, so chained calls keep their scope methods. */
|
|
723
739
|
readonly [scopeTypes]?: S;
|
|
@@ -781,6 +797,12 @@ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
|
|
|
781
797
|
select(...attributes: (keyof AttributesOf<M> & string)[]): Scoped<M, S>;
|
|
782
798
|
/** Removes duplicate rows (of the selected attributes). */
|
|
783
799
|
distinct(): Scoped<M, S>;
|
|
800
|
+
/**
|
|
801
|
+
* Makes the records this Relation loads read-only (#358): saving or destroying one throws
|
|
802
|
+
* `ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
|
|
803
|
+
* `readonly(false)` undoes it.
|
|
804
|
+
*/
|
|
805
|
+
readonly(flag?: boolean): Scoped<M, S>;
|
|
784
806
|
/**
|
|
785
807
|
* Preloads associations for every record this Relation loads, so reading them afterwards
|
|
786
808
|
* sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
|
|
@@ -959,19 +981,6 @@ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
|
|
|
959
981
|
calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
|
|
960
982
|
/** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
|
|
961
983
|
group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
|
|
962
|
-
/**
|
|
963
|
-
* The number of records: a loaded association's (built records included) without a query;
|
|
964
|
-
* otherwise a `COUNT(*)`, plus an association's unsaved built records.
|
|
965
|
-
*/
|
|
966
|
-
size(): Promise<number>;
|
|
967
|
-
/** Whether there are no records: a loaded association answers itself, else `!exists()`. */
|
|
968
|
-
isEmpty(): Promise<boolean>;
|
|
969
|
-
/** Whether there are any records: the opposite of `isEmpty()`. */
|
|
970
|
-
hasAny(): Promise<boolean>;
|
|
971
|
-
/** Whether more than one record matches: one `COUNT` of at most two rows. */
|
|
972
|
-
hasMoreThanOne(): Promise<boolean>;
|
|
973
|
-
/** Whether exactly one record matches: one `COUNT` of at most two rows. */
|
|
974
|
-
hasExactlyOne(): Promise<boolean>;
|
|
975
984
|
/** Whether any record matches, optionally with extra conditions. */
|
|
976
985
|
exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
|
|
977
986
|
/** Converted values of one attribute, or tuples of several, in this Relation's order. */
|
|
@@ -1057,7 +1066,7 @@ interface SaveOptions {
|
|
|
1057
1066
|
/** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
|
|
1058
1067
|
type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
|
|
1059
1068
|
/** The Relation methods every Model has as statics (besides the overloaded ones). */
|
|
1060
|
-
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", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "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"];
|
|
1069
|
+
declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "readonly", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "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"];
|
|
1061
1070
|
/** A Relation method with no overloads, by name. */
|
|
1062
1071
|
type RelationMethod = (typeof relationMethods)[number];
|
|
1063
1072
|
/**
|
|
@@ -1597,9 +1606,10 @@ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instance
|
|
|
1597
1606
|
/**
|
|
1598
1607
|
* A change to a generated attribute: its type alone, or its type, nullability, default and
|
|
1599
1608
|
* `generateId`, typed so `generateId` goes only with a string, and never with a default (#99); and
|
|
1600
|
-
* an enum on a string or an integer, whose stored values are of its type (#340)
|
|
1609
|
+
* an enum on a string or an integer, whose stored values are of its type (#340); and `readonly`
|
|
1610
|
+
* on a column (#358).
|
|
1601
1611
|
*/
|
|
1602
|
-
type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
|
|
1612
|
+
type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null" | "readonly"> & {
|
|
1603
1613
|
type?: "string";
|
|
1604
1614
|
storage?: never;
|
|
1605
1615
|
virtual?: false;
|
|
@@ -1607,24 +1617,24 @@ type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "nu
|
|
|
1607
1617
|
enum?: TextEnum | boolean;
|
|
1608
1618
|
/** A random token, generated for a new record (#355). */
|
|
1609
1619
|
secureToken?: boolean | SecureTokenOptions;
|
|
1610
|
-
} & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
|
|
1620
|
+
} & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
|
|
1611
1621
|
type?: "integer";
|
|
1612
1622
|
generateId?: false;
|
|
1613
1623
|
storage?: never;
|
|
1614
1624
|
virtual?: false;
|
|
1615
1625
|
enum: IntegerEnum;
|
|
1616
|
-
} & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
|
|
1626
|
+
} & EnumOptions) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
|
|
1617
1627
|
type: Exclude<AttributeType, "string" | "datetime">;
|
|
1618
1628
|
generateId?: false;
|
|
1619
1629
|
storage?: never;
|
|
1620
1630
|
enum?: never;
|
|
1621
1631
|
virtual?: false;
|
|
1622
|
-
}) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
|
|
1632
|
+
}) | (Pick<SpecOverride, "null" | "default" | "storage" | "readonly"> & {
|
|
1623
1633
|
type: "datetime";
|
|
1624
1634
|
generateId?: false;
|
|
1625
1635
|
enum?: never;
|
|
1626
1636
|
virtual?: false;
|
|
1627
|
-
}) | (Pick<SpecOverride, "null" | "default"> & {
|
|
1637
|
+
}) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
|
|
1628
1638
|
type: AnyCustomType;
|
|
1629
1639
|
generateId?: false;
|
|
1630
1640
|
storage?: never;
|
|
@@ -1723,6 +1733,16 @@ interface DatabaseSchema {
|
|
|
1723
1733
|
}
|
|
1724
1734
|
/** `{ attribute: [before, after] }` */
|
|
1725
1735
|
type Changes = Record<string, [before: unknown, after: unknown]>;
|
|
1736
|
+
/** The read-only mark Model's records have. */
|
|
1737
|
+
declare abstract class ReadonlyMarks extends AttributeWrites {
|
|
1738
|
+
/**
|
|
1739
|
+
* Marks the record read-only: saving, destroying, touching it or writing its columns throws
|
|
1740
|
+
* `ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.
|
|
1741
|
+
*/
|
|
1742
|
+
markReadonly<R extends Model>(this: R): R;
|
|
1743
|
+
/** Whether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation. */
|
|
1744
|
+
isReadonly(this: Model): boolean;
|
|
1745
|
+
}
|
|
1726
1746
|
/** Type-only brand on a scope static (`static newest = this.scope(…)`); never set at runtime. */
|
|
1727
1747
|
declare const scopeBrand: unique symbol;
|
|
1728
1748
|
/**
|
|
@@ -1799,7 +1819,7 @@ type AttributesOf<M> = M extends {
|
|
|
1799
1819
|
* methods, statics, callbacks and scopes declared there are shared by every Model built on it.
|
|
1800
1820
|
* It has no table, so it's never used as a Model itself.
|
|
1801
1821
|
*/
|
|
1802
|
-
declare class Model extends
|
|
1822
|
+
declare class Model extends ReadonlyMarks {
|
|
1803
1823
|
/** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
|
|
1804
1824
|
static table: string;
|
|
1805
1825
|
/**
|
|
@@ -2259,4 +2279,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
|
|
|
2259
2279
|
}
|
|
2260
2280
|
/** The options of a `validatesAssociated(association, options)` call. */
|
|
2261
2281
|
type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
|
|
2262
|
-
export { TouchOptions as $, databaseExecutor as A,
|
|
2282
|
+
export { TouchOptions as $, databaseExecutor as A, QueryPart as At, SaveOptions as B, ColumnValue as Bt, QueryEvent as C, UpsertOptions as Ct, SchemaAdapter as D, gte as Dt, ConstraintFailure as E, gt as Et, RecordStatement as F, QuerySql as Ft, Relation as G, ComparisonBound as Gt, ValidationContext as H, column as Ht, DatetimeAttributeKey as I, Dialect as It, Scoped as J, Scope as K, ComparisonOptions as Kt, NumberAttributeKey as L, valueMark as Lt, BatchResults as M, SignedIdOptions as Mt, batch as N, InOrderOfOptions as Nt, AnyDatabase as O, lt as Ot, Batch as P, CompiledSql as Pt, PageOptions as Q, SigningEnv as R, Attribute as Rt, DatabaseExecutor as S, Returning as St, Adapter as T, between as Tt, ValidationContexts as U, sql$1 as Ut, ValidationCallbackOptions as V, SafeSql as Vt, TokenForOptions as W, Comparable as Wt, CountlessPage as X, IterationOptions as Y, Page as Z, TableSchema as _, ThroughDependent as _t, ValidationOptions as a, Driver as at, boundValue as b, InsertOptions as bt, AttributeErrorMessages as c, BelongsTo as ct, RestrictMessages as d, HasManyDependent as dt, GroupedRelation as et, Model as f, HasManyThrough as ft, DatabaseSchema as g, PolymorphicBelongsTo as gt, TableAttributes as h, HasOneThrough as ht, UniquenessOptions as i, WriteResult as it, BatchEntry as j, FindSignedOptions as jt, RelationsFor as k, lte as kt, ErrorMessage as l, HasMany as lt, ScopeStatic as m, HasOneDependent as mt, LengthOptions as n, ReturnedRow as nt, Errors as o, StatementResult as ot, ModelClass as p, HasOne as pt, ScopeMethods as q, NumericalityOptions as r, Statement as rt, ValidationError as s, AssociationOptions as st, AssociatedValidationOptions as t, Init as tt, ErrorMessages as u, HasManyCollection as ut, TableSchemas as v, ThroughOptions as vt, QueryListener as w, Comparison as wt, AttributeConversions as x, OrderSpec as xt, FilterAttribute as y, Conditions as yt, SigningSecrets as z, ColumnReference as zt };
|
package/llms-full.txt
CHANGED
|
@@ -418,6 +418,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
418
418
|
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
|
|
419
419
|
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
|
|
420
420
|
- To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
|
|
421
|
+
- For records a request reads but must not write (a public page, a report), load them with `readonly()` (`Article.readonly().where(…)`) or call `record.markReadonly()`: a save, update, destroy, `touch()` or column write then throws `ReadonlyRecord` before anything runs. Bulk writes (`updateAll`, `deleteAll`) ignore the mark. For an attribute set once on create, such as a slug, declare `slug: { readonly: true }` in the Model's `static attributes`: changing it on a saved record throws `ReadonlyAttribute`, and posting back the value it holds is fine, so an edit form needn't leave it out.
|
|
421
422
|
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
422
423
|
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
423
424
|
- To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`.
|
|
@@ -5088,17 +5089,19 @@ export async function showUser(id: string): Promise<Response> {
|
|
|
5088
5089
|
|
|
5089
5090
|
## Lifecycle errors
|
|
5090
5091
|
|
|
5091
|
-
| Error | When
|
|
5092
|
-
| ----------------------- |
|
|
5093
|
-
| `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing
|
|
5094
|
-
| `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record
|
|
5095
|
-
| `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record`
|
|
5096
|
-
| `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved
|
|
5097
|
-
| `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError`
|
|
5098
|
-
| `RecordDestroyed` | writing to a record that’s already destroyed
|
|
5099
|
-
| `StaleRecord` | a [locked](/optimistic-locking) record’s row changed since it was loaded
|
|
5100
|
-
| `
|
|
5101
|
-
| `
|
|
5092
|
+
| Error | When |
|
|
5093
|
+
| ----------------------- | ------------------------------------------------------------------------------------------- |
|
|
5094
|
+
| `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing |
|
|
5095
|
+
| `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record |
|
|
5096
|
+
| `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
|
|
5097
|
+
| `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
|
|
5098
|
+
| `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
|
|
5099
|
+
| `RecordDestroyed` | writing to a record that’s already destroyed |
|
|
5100
|
+
| `StaleRecord` | a [locked](/optimistic-locking) record’s row changed since it was loaded |
|
|
5101
|
+
| `ReadonlyRecord` | writing a [read-only](/read-only) record; what was refused is on `.action` |
|
|
5102
|
+
| `ReadonlyAttribute` | changing a saved record’s [read-only](/read-only#declaring-read-only-attributes) attribute |
|
|
5103
|
+
| `CallbackAbort` | what `abort()` makes; caught by the lifecycle |
|
|
5104
|
+
| `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`) |
|
|
5102
5105
|
|
|
5103
5106
|
## Usage errors
|
|
5104
5107
|
|
|
@@ -9040,6 +9043,212 @@ export async function paidAt(db: D1Database, id: number) {
|
|
|
9040
9043
|
|
|
9041
9044
|
---
|
|
9042
9045
|
|
|
9046
|
+
# Read-only records
|
|
9047
|
+
Source: https://active-record.forestfuture.dev/read-only
|
|
9048
|
+
|
|
9049
|
+
## At a glance
|
|
9050
|
+
|
|
9051
|
+
| To | Write |
|
|
9052
|
+
| --------------------------------------- | ---------------------------------------------------------- |
|
|
9053
|
+
| load records that can’t be saved | `Article.readonly().toArray()` |
|
|
9054
|
+
| make one record read-only | `article.markReadonly()` |
|
|
9055
|
+
| ask whether a record is read-only | `article.isReadonly()` |
|
|
9056
|
+
| catch a refused write | `catch (error) { if (error instanceof ReadonlyRecord) … }` |
|
|
9057
|
+
| set an attribute only when it’s created | `slug: { readonly: true }` in the Model’s `attributes` |
|
|
9058
|
+
|
|
9059
|
+
## The Model
|
|
9060
|
+
|
|
9061
|
+
The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates:
|
|
9062
|
+
|
|
9063
|
+
```ts article.ts
|
|
9064
|
+
import { ApplicationRecord } from "./application-record";
|
|
9065
|
+
|
|
9066
|
+
export class Article extends ApplicationRecord {
|
|
9067
|
+
static override attributes = {
|
|
9068
|
+
slug: { readonly: true }, // set when the article is created, never changed after
|
|
9069
|
+
} as const;
|
|
9070
|
+
}
|
|
9071
|
+
```
|
|
9072
|
+
|
|
9073
|
+
```ts schema.ts
|
|
9074
|
+
// Generated by `active-record schema` from migrations/ — don't edit.
|
|
9075
|
+
// schema: df347ceeec61
|
|
9076
|
+
|
|
9077
|
+
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
|
|
9078
|
+
import { d1 } from "@forestfuture/active-record/d1";
|
|
9079
|
+
|
|
9080
|
+
/** articles — last changed by 0001_create_articles.sql */
|
|
9081
|
+
export const articles = {
|
|
9082
|
+
id: { type: "string", null: false, generateId: true },
|
|
9083
|
+
title: { type: "string", null: false },
|
|
9084
|
+
slug: { type: "string", null: false },
|
|
9085
|
+
body: "string",
|
|
9086
|
+
updatedAt: "datetime",
|
|
9087
|
+
} as const;
|
|
9088
|
+
|
|
9089
|
+
/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
|
|
9090
|
+
export const schema = defineSchema({
|
|
9091
|
+
adapter: d1({ binding: "DB" }),
|
|
9092
|
+
tables: {
|
|
9093
|
+
articles: { attributes: articles, primaryKey: "id" },
|
|
9094
|
+
},
|
|
9095
|
+
models: { Article: "articles" },
|
|
9096
|
+
});
|
|
9097
|
+
|
|
9098
|
+
declare module "../models/article" {
|
|
9099
|
+
interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
|
|
9100
|
+
}
|
|
9101
|
+
```
|
|
9102
|
+
|
|
9103
|
+
```sql D1
|
|
9104
|
+
CREATE TABLE articles (
|
|
9105
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
9106
|
+
title TEXT NOT NULL,
|
|
9107
|
+
slug TEXT NOT NULL UNIQUE,
|
|
9108
|
+
body TEXT,
|
|
9109
|
+
updated_at DATETIME
|
|
9110
|
+
);
|
|
9111
|
+
```
|
|
9112
|
+
|
|
9113
|
+
```sql Postgres
|
|
9114
|
+
CREATE TABLE articles (
|
|
9115
|
+
id UUID PRIMARY KEY,
|
|
9116
|
+
title TEXT NOT NULL,
|
|
9117
|
+
slug TEXT NOT NULL UNIQUE,
|
|
9118
|
+
body TEXT,
|
|
9119
|
+
updated_at TIMESTAMPTZ
|
|
9120
|
+
);
|
|
9121
|
+
```
|
|
9122
|
+
|
|
9123
|
+
## Loading read-only records
|
|
9124
|
+
|
|
9125
|
+
Call `readonly()` on a query, and the records it loads can’t be saved:
|
|
9126
|
+
|
|
9127
|
+
```ts
|
|
9128
|
+
import { Article } from "./models/article";
|
|
9129
|
+
|
|
9130
|
+
const articles = await Article.readonly().order({ title: "asc" }).toArray();
|
|
9131
|
+
console.log(articles[0]?.isReadonly()); // true
|
|
9132
|
+
|
|
9133
|
+
const article = await Article.readonly().findByOrThrow({ slug: "hello" });
|
|
9134
|
+
article.title = "Hello, world";
|
|
9135
|
+
await article.save(); // throws ReadonlyRecord, and sends nothing
|
|
9136
|
+
```
|
|
9137
|
+
|
|
9138
|
+
- Every way a query loads records marks them: `toArray()`, `find`, `findBy`, `first`, `sole`, `findEach`, and the rest.
|
|
9139
|
+
- Chaining keeps it, and so does `merge`. A scope, a default scope, or an association’s `scope` can call it too. `readonly(false)` undoes it.
|
|
9140
|
+
- The records `includes` preloads aren’t read-only, unless an association’s `scope` calls `readonly()`. Records the query builds or creates aren’t read-only either.
|
|
9141
|
+
|
|
9142
|
+
## Marking one record
|
|
9143
|
+
|
|
9144
|
+
`markReadonly()` makes a record you already have read-only:
|
|
9145
|
+
|
|
9146
|
+
```ts
|
|
9147
|
+
import { Article } from "./models/article";
|
|
9148
|
+
|
|
9149
|
+
const article = await Article.findByOrThrow({ slug: "hello" });
|
|
9150
|
+
article.markReadonly();
|
|
9151
|
+
|
|
9152
|
+
console.log(article.isReadonly()); // true
|
|
9153
|
+
await article.destroy(); // throws ReadonlyRecord, and the article stays
|
|
9154
|
+
```
|
|
9155
|
+
|
|
9156
|
+
A read-only record can still change in memory, and `reload()` still reads its row. It stays read-only.
|
|
9157
|
+
|
|
9158
|
+
## Refusing writes
|
|
9159
|
+
|
|
9160
|
+
Saving, updating, destroying, or touching a read-only record throws `ReadonlyRecord`, and so do `updateColumns`, `updateColumn`, `incrementColumn`, `decrementColumn`, and `toggleColumn`:
|
|
9161
|
+
|
|
9162
|
+
```ts
|
|
9163
|
+
import { ReadonlyRecord } from "@forestfuture/active-record";
|
|
9164
|
+
import { Article } from "./models/article";
|
|
9165
|
+
|
|
9166
|
+
const article = await Article.findByOrThrow({ slug: "hello" });
|
|
9167
|
+
article.markReadonly();
|
|
9168
|
+
try {
|
|
9169
|
+
await article.touch();
|
|
9170
|
+
} catch (error) {
|
|
9171
|
+
if (!(error instanceof ReadonlyRecord)) throw error;
|
|
9172
|
+
console.log(error.action); // "touch"
|
|
9173
|
+
}
|
|
9174
|
+
```
|
|
9175
|
+
|
|
9176
|
+
- It throws before validation or any callback runs, and sends nothing.
|
|
9177
|
+
- `save()` throws too, rather than returning `false`.
|
|
9178
|
+
- The error’s `record` is the refused record, and its `action` names what was refused: `"save"`, `"destroy"`, `"touch"`, or the column method.
|
|
9179
|
+
- A write that would reach a read-only record through another throws too, and writes nothing. Saving an owner that [autosaves](/autosaving) a changed read-only record, a [batch](/batches) holding one, and a has-many’s `push` throw before any callback runs. So does a write that would [touch](/touching) a loaded read-only record.
|
|
9180
|
+
- Some records are only loaded partway through a write: the record a has-one’s new record replaces, and a `dependent: "destroy"` association’s records. A read-only one throws once it’s loaded, after the owner’s before-callbacks, and nothing is written.
|
|
9181
|
+
|
|
9182
|
+
## Writing past it
|
|
9183
|
+
|
|
9184
|
+
Bulk writes don’t load records, so `readonly()` doesn’t stop them:
|
|
9185
|
+
|
|
9186
|
+
```ts
|
|
9187
|
+
import { Article } from "./models/article";
|
|
9188
|
+
|
|
9189
|
+
const updated = await Article.readonly().where({ slug: "hello" }).updateAll({ body: "" });
|
|
9190
|
+
console.log(updated); // 1: a bulk write doesn't load records, so it isn't refused
|
|
9191
|
+
```
|
|
9192
|
+
|
|
9193
|
+
`updateAll`, `deleteAll`, `insert`, and `upsert` all write as usual. So do the removals that work like them: `dependent: "delete"`, a has-one replacement whose `dependent` is `"delete"`, and a has-many’s `delete()` and `clear()`.
|
|
9194
|
+
|
|
9195
|
+
## Declaring read-only attributes
|
|
9196
|
+
|
|
9197
|
+
Give an attribute `readonly: true`, and it’s written when its record is created, then never changed by it:
|
|
9198
|
+
|
|
9199
|
+
```ts
|
|
9200
|
+
import { Article } from "./models/article";
|
|
9201
|
+
|
|
9202
|
+
const article = await Article.create({ title: "Getting started", slug: "getting-started" });
|
|
9203
|
+
console.log(article.slug); // "getting-started"
|
|
9204
|
+
|
|
9205
|
+
article.slug = "first-steps"; // throws ReadonlyAttribute: it's set when it's created
|
|
9206
|
+
```
|
|
9207
|
+
|
|
9208
|
+
- Assigning a saved record a new value throws `ReadonlyAttribute` straight away, whether you assign it, `update()` it, or write it with `updateColumns`. The error’s `attribute` names it.
|
|
9209
|
+
- Pointing a belongs-to at another record throws `ReadonlyAttribute` when its read-only foreign key would change. So does saving a record whose read-only foreign key a new record would fill once it’s inserted.
|
|
9210
|
+
- Changing a JSON value or a `Date` in place makes the save throw before anything runs. `touch()` refuses a read-only datetime the same way.
|
|
9211
|
+
- A new record can change it until it’s saved.
|
|
9212
|
+
- A [counter cache](/counter-caches) still counts a read-only column, so a save can’t overwrite the count. `Model.updateCounters` and `touchAll` write rows without loading them, as `updateAll` does, so they write a read-only column too.
|
|
9213
|
+
- An `upsert` leaves the value of a row it updates alone. `updateAll` still writes it.
|
|
9214
|
+
- A virtual attribute, a secure password, and a secure token can’t be read-only. Neither can `updatedAt` or `lockVersion`, which every save writes.
|
|
9215
|
+
|
|
9216
|
+
## Posting it back from a form
|
|
9217
|
+
|
|
9218
|
+
Assigning the value an attribute already holds isn’t a change, so a form that sends every field back still saves:
|
|
9219
|
+
|
|
9220
|
+
```ts
|
|
9221
|
+
import { ReadonlyAttribute } from "@forestfuture/active-record";
|
|
9222
|
+
import { Article } from "./models/article";
|
|
9223
|
+
|
|
9224
|
+
export async function updateArticle(request: Request): Promise<Response> {
|
|
9225
|
+
const id = new URL(request.url).searchParams.get("id") ?? "";
|
|
9226
|
+
const article = await Article.find(id);
|
|
9227
|
+
const form = await request.formData();
|
|
9228
|
+
const changes = Article.permit(form, "title", "slug");
|
|
9229
|
+
try {
|
|
9230
|
+
// A form that posts the slug back unchanged saves; one that changes it doesn't
|
|
9231
|
+
await article.updateOrThrow(changes);
|
|
9232
|
+
} catch (error) {
|
|
9233
|
+
if (!(error instanceof ReadonlyAttribute)) throw error;
|
|
9234
|
+
return new Response(`An article's ${error.attribute} can't be changed.`, { status: 422 });
|
|
9235
|
+
}
|
|
9236
|
+
return new Response("Saved");
|
|
9237
|
+
}
|
|
9238
|
+
```
|
|
9239
|
+
|
|
9240
|
+
The value is compared after it’s cast and normalized, so `" Hello "` matches `"hello"` when a [normalization](/models#normalizing-attributes) trims and lowercases it.
|
|
9241
|
+
|
|
9242
|
+
> **Compared with Rails**
|
|
9243
|
+
>
|
|
9244
|
+
> Rails names the error `ActiveRecord::ReadOnlyRecord`, and its record method is `readonly!`. Here it’s `markReadonly()`.
|
|
9245
|
+
>
|
|
9246
|
+
> Rails runs a read-only record’s own save and destroy callbacks, `dependent: :destroy` included, before it raises. Here they don’t run.
|
|
9247
|
+
>
|
|
9248
|
+
> With Rails 7.1’s defaults, `attr_readonly` raises `ActiveRecord::ReadonlyAttributeError` on any assignment to a saved record. Here assigning the value it holds is allowed.
|
|
9249
|
+
|
|
9250
|
+
---
|
|
9251
|
+
|
|
9043
9252
|
# Read replicas
|
|
9044
9253
|
Source: https://active-record.forestfuture.dev/read-your-own-writes
|
|
9045
9254
|
|
package/package.json
CHANGED
|
@@ -22,6 +22,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
22
22
|
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
|
|
23
23
|
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
|
|
24
24
|
- To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
|
|
25
|
+
- For records a request reads but must not write (a public page, a report), load them with `readonly()` (`Article.readonly().where(…)`) or call `record.markReadonly()`: a save, update, destroy, `touch()` or column write then throws `ReadonlyRecord` before anything runs. Bulk writes (`updateAll`, `deleteAll`) ignore the mark. For an attribute set once on create, such as a slug, declare `slug: { readonly: true }` in the Model's `static attributes`: changing it on a saved record throws `ReadonlyAttribute`, and posting back the value it holds is fine, so an edit form needn't leave it out.
|
|
25
26
|
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
26
27
|
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
27
28
|
- To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`.
|